An inverted hollow star pyramid is a pattern where the first row contains stars across the entire width, while the following rows contain stars only at the boundaries. The remaining positions are filled with spaces, creating a hollow structure that narrows toward the bottom.
- The number of leading spaces increases by one after every row.
- The number of positions decreases by two in each successive row.
Illustration
Input:
R = 5
Output:
******
* *
* *
* *
*
For R = 10, the pattern becomes:
***********
* *
* *
* *
* *
* *
* *
* *
* *
*
Approach
The pattern can be generated using nested loops:
- Print the required leading spaces for each row.
- Calculate the number of positions in the current row.
- Print * for the first row.
- For the remaining rows, print * only at the first and last positions.
- Print spaces between the boundary stars.
- Move to the next row.
For row i, the number of positions containing stars or spaces is:
2 * R - (2 * i - 1)
This value decreases by two after every row.
#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:
******
* *
* *
* *
*