C++ program to print right triangle star pattern

In this program, we will learn how to print a right triangle having stars (asterisk *) as elements.

Program 1 (With fixed number of rows)

#include<iostream> 
using namespace std; 
int main() 
{ 
    int i, j, n = 5; 
    for( i = 1;i <= n; i++) 
    { 
        for(j = 1;j <= i; j++) 
        { 
            cout << "*"; 
        } 
        cout<<endl; 
    } 
    return 0; 
}

Output:

*
* *
* * *
* * * *
* * * * *

Explanation:

  • We have declared three variables named i, j, and n. i, j variables are used in the loops whereas the variable n contains the total number of rows of the triangle.
  • The outer loop starts from 1 to 5(as the value of n is 5). For every iteration of the outer loop the inner loop will execute from 1 to the current value of i. That means for the first iteration of the outer loop, the inner loop will execute one time (as the current value of i is 1). It will print one start and the line will be breaked by ‘endl’. For the second iteration of the outer loop, the inner loop will execute two times (as the value of i has been incremented from 1 to 2.). So the inner loop will print two stars and again the line will be breaked.
  • This process will continue till the value of n becomes 5. So in the last iteration, 5 stars will be printed and with that the program will terminate.

program 2(with number of rows entered by the user)

#include<iostream>
using namespace std;
int main() 
{
    int i, j, n;
    cout<<"Enter the no. of rows";
    cin>>n;
    
    for( i=1;i<=n;i++)
    {
        for(j=1;j<=i;j++)
        {
            cout << "*";
        }
        cout<<endl;
    }

return 0;

}

Output: Enter the no. of rows4

*
* *
* * *
* * * *