Skip to content
Related Articles

Related Articles

C++ Program To Print Inverted Hollow Star Pyramid Pattern

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 05 Jul, 2022

Given the value of R(number of rows), write a C++ program to print the Inverted Hollow Pyramid using stars and white spaces.

Examples:

Input: R = 5

Output:

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

Input: R = 10

Output:

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

Algorithm:

  • At first, take the number of rows as input.
  • The next step is to implement the nested loop to print this pattern.
  • A space-maintaining variable(sp) is required to maintain the space at the beginning.
  • Calculate the last column by Last Column = (length _of_row * 2 – (2 * Current_row – 1))
  • Print star( “*” ) at the first column and last column and proceed to the next row.

Below is the C++ program to implement the above approach:

C++




// C++ program to Print a Inverted
// hollow Star Pyramid
#include <bits/stdc++.h>
using namespace std;
 
void print_patt(int R)
{
  // To iterate through the rows
  for(int i = 1; i <= R; i++)
  {
    // To print the  beginning spaces
    for(int sp = 1;
            sp <= i - 1 ; sp++)
    {
      cout << " ";
    }
       
    // Iterating from ith column to
    // last column (R*2 - (2*i - 1))
    int last_col = (R * 2 - (2 * i - 1));
         
    // To iterate through column
    for(int j = 1; j <= last_col; j++)
    {
      // To Print all star for first
      // row (i==1) ith column (j==1)
      // and for last column
      // (R*2 - (2*i - 1))
      if(i == 1)
        cout << "*";
      else if(j == 1)
        cout << "*";
      else if(j == last_col)
        cout << "*";
      else
        cout << " ";
    }
         
    // After printing a row proceed
    // to the next row
    cout << "\n";
  }
}
 
// Driver code
int main()
{
  // Number of rows
  int R = 5;
  print_patt(R);
  return 0;
}

Output

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

Time Complexity: O(R*last_col), where R represents the row and last_col represents the last column.

Auxiliary Space: O(1), no extra space is required, so it is a constant.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!