C Program To Print Inverted Hollow Star Pyramid
Here we will see how to print an inverted hollow star pyramid using a C program. Below are the examples:
Input: row = 5
Output:
*********
* *
* *
* *
*
Input: row = 7
Output:
*************
* *
* *
* *
* *
* *
*
There are 2 ways to print an inverted hollow star pyramid in C:
- Using For Loop.
- Using While Loop.
Let’s start discussing each of these methods in detail.
Using For Loop
Approach:
The approach is to use three loops:
- One is to control the number of rows.
- The second is to control the blank spaces.
- The third is to control the number of columns.
Then by using concepts of the nested loop one can easily print the pattern.
Algorithm:
- Take the Input of row value for the Inverted Pyramid.
- We need to use three loops one is the outer loop to change the line and two inner loops one to print the star and the other to print the space.
- The outer loop iterate row times and print a newline after completing the inner loop.
- The first inner loop is used to print the space from 1 to (current_row -1).
- The second inner loop is used to print the star ( “*” ) at first and last column (i.e length _of_row * 2 – (2 * Current_row – 1)) .
- The second loop iterates from 1 to the last column.
Below is the C program to print an inverted hollow star pyramid using for loop:
C
#include <stdio.h>
void pattern_fun( int row)
{
for ( int j = 1; j <= row; j++)
{
for ( int sp = 1; sp <= j - 1; sp++)
{
printf ( " " );
}
int last_col = (row * 2 - (2 * j - 1));
for ( int k = 1; k <= last_col; k++)
{
if (j == 1 || k == 1)
printf ( "*" );
else if (k == last_col)
printf ( "*" );
else
printf ( " " );
}
printf ( "\n" );
}
}
int main()
{
int row = 7;
pattern_fun(row);
return 0;
}
|
Output
*************
* *
* *
* *
* *
* *
*
- Time Complexity: O(n2), as the nested loop, is used.
- Auxiliary Space: O(1), no extra space is required, so it is a constant.
Using While Loop:
Below is the C program to print an inverted hollow star pyramid using a while loop:
C
#include <stdio.h>
void pattern_fun( int row)
{
int j = 1;
int sp = 1;
int k = 1;
while (j <= row)
{
sp = 1;
while (sp <= j - 1)
{
printf ( " " );
sp++;
}
int last_col = (row * 2 - (2 * j - 1));
k = 1;
while (k <= last_col)
{
if (j == 1 || k == 1)
printf ( "*" );
else if (k == last_col)
printf ( "*" );
else
printf ( " " );
k++;
}
printf ( "\n" );
j++;
}
}
int main()
{
int row = 4;
pattern_fun(row);
return 0;
}
|
- Time Complexity: O(n2), as the nested loop is used.
- Auxiliary Space: O(1), no extra space is required, so it is a constant.
Last Updated :
19 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...