Open In App

C++ Program To Print Left Half Pyramid Pattern

Improve
Improve
Like Article
Like
Save
Share
Report

Here, we will build a C++ program to print the left half of pyramid pattern using 2 approaches i.e.

  1. Using for loop
  2. Using while loop

1. Using for loop

Input: 

rows = 5

Output:

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

First, for loop is used to identify the number of rows and the second for loop is used to identify the number of columns. Here the values will be changed according to the first for loop.  If j is greater than i then it will print the output otherwise print the space.

C++




// C++ program to print 180 degree rotation of simple
// pyramid pattern using for loop
#include <iostream>
using namespace std;
 
int main()
{
 
    int rows = 5;
 
    // first for loop is used to identify number of rows
    for (int i = rows; i > 0; i--) {
       
        // second for loop is used to identify number of
        // columns and here the values will be changed
        // according to the first for loop
        for (int j = 0; j <= rows; j++) {
           
            // if j is greater than i then it will print
            // the output otherwise print the space
            if (j >= i) {
                cout << "*";
            }
            else {
                cout << " ";
            }
        }
        cout << "\n";
    }
    return 0;
}


Output

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

Time complexity: O(n2

Here n is number of rows.

Auxiliary Space: O(1)

As constant extra space is used.

2. Using while loop

Input: 

rows = 5

Output:

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

The while loops check the condition until the condition is false. If the condition is true then it enters into the loop and executes the statements. 

C++




// C++ program to print 180 degree rotation of simple
// pyramid pattern using while loop
#include <iostream>
using namespace std;
 
int main()
{
 
    int i = 0, j = 0, sp = 0;
    int rows = 5;
    // while loop check the condition until the given
    // condition is false if it is true then enteres in to
    // the loop
 
    while (i < rows) {
 
        // second while loop is used for printing spaces
        while (sp < (rows - i - 1)) {
            cout << "  ";
            sp++;
        }
 
        // assigning sp value as 0 because we need to run sp
        // from starting
 
        sp = 0;
       
        // this loop will print the pattern
        while (j <= i) {
            cout << "* ";
            j++;
        }
 
        j = 0;
        i++;
        cout << "\n";
    }
    return 0;
}


Output

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

Time complexity: O(n2) where n is number of rows

Space complexity: O(1)



Last Updated : 23 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads