C++ Program To Print Inverted Hollow Star Pyramid Pattern
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++
#include <bits/stdc++.h>
using namespace std;
void print_patt( int R)
{
for ( int i = 1; i <= R; i++)
{
for ( int sp = 1;
sp <= i - 1 ; sp++)
{
cout << " " ;
}
int last_col = (R * 2 - (2 * i - 1));
for ( int j = 1; j <= last_col; j++)
{
if (i == 1)
cout << "*" ;
else if (j == 1)
cout << "*" ;
else if (j == last_col)
cout << "*" ;
else
cout << " " ;
}
cout << "\n" ;
}
}
int main()
{
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...