C++ Program to Print a half pyramid pattern of stars


January 31, 2023, Learn eTutorial
1310

Here we are discussing a simple C++ program to print a pattern of stars that looks like half-pyramid

How to write a C++ program to print half pyramid pattern of stars?

Here we are using nested for loops, the outer for loop and the inner for loop. The outer for loop is responsible for rows and the inner for loop is responsible for columns.


for(i=0; i<6; i++)

    {

        for(j=0; j<=i; j++)
          {
           cout<<"* ";
          }
           cout<<endl;
    }
    cout<<endl;
    return 0;
}
        cout<


Initially, the value of i is 0 in the outer for loop and the condition is evaluated. i<6 if it is evaluated to be true then the program flow goes inside the loop. Inside the loop, another for loop is defined. The value of j is initialized to 0 and checked for the condition j<=i; If the condition evaluates true then the program flow goes within the loop and prints a * and a space.

Now j gets incremented. After that the condition went wrong j<=i; The execution of the inner loop gets paused and an endl is used to print a newline.

Now the program control goes to the outer loop and increments the value of i. Again the condition evaluates true and program flow goes inside the loop and the procedure continues until the condition evaluates false. In this way, a half-pyramid pattern using a star gets printed.

Algorithm

Step 1: Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare two integer type variables i, j;

Step 5: initialize the value of i to 0; check for the condition i<6; 

Step 6: initialize the value of j to 0; check for the condition j<=i;

Step 7: print a * and space; 

Step 8: increment the value of j by 1;

Step 9: print a new line if the condition j<=i is false;

Step 10: increment the value i by 1 ;

Step 11: check for the condition i<6;

Step 12: Go to step 6;

Step 13:Exit;

C++ Source Code

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

OUTPUT

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