C Program For Printing Inverted Pyramid
Last Updated :
19 Jul, 2022
Here, we will see how to print an inverted pyramid using a C program. Below are the examples:
Input: 8
Output:
* * * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Input: 5
Output:
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Method 1:
The pattern would be divided into three parts:
- A for loop will be used to print the blank spaces
- A for loop will be used to print the triangle from the left-hand side
- A for loop will be used to print the rest of the triangle, making the exact pattern
Algorithm:
1. Initialize variables i, j, and space for rows, columns, and blank spaces, respectively.
2. The number of rows here is 8, the user can take any number.
3. Initialize a for loop that will work as the main loop in printing the pattern and drive the other loops inside it.
4. Initialize a for loop that will print the blank spaces inside the main loop.
5. Now, in order to print the star pattern, we will first print the half pyramid as shown below. To do that, we will initialize a for loop with the condition given as 2 * i – 1, because the number of stars is odd.
6. After it, we’ll use another for loop to print the rest of the pattern.
Below is the C program to print an inverted pyramid pattern:
C
#include <stdio.h>
int main()
{
int rows = 8, i, j, space;
for (i = rows; i >= 1; --i)
{
for (space = 0;
space < rows - i; ++space)
printf ( " " );
for (j = i; j <= 2 * i - 1; ++j)
printf ( "* " );
for (j = 0; j < i - 1; ++j)
printf ( "* " );
printf ( "\n" );
}
return 0;
}
|
Output
* * * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Time Complexity: O(n2)
Auxiliary Space: O(1)
Method 2:
Two for loops will be used:
- A for loop will be used to print the blank spaces
- A for loop will be used to print the stars
Algorithm:
- Initialize variables i, j, and rows.
- The number of rows here is 8, the user can take any number.
- Initialize a for loop that will work as the main loop in printing the pattern and drive the other loops inside it.
- Initialize a for loop that will print the blank spaces inside the main loop and will run from 1 to i.
- Run a for loop from 1 to rows * 2 – (i * 2 – 1), to print the stars.
- Move to the next line with the help of the new line character.
Below is the C program to print an inverted pyramid pattern:
C
#include <stdio.h>
int main()
{
int i, j, rows = 8;
for (i = 1; i <= rows; i++)
{
for (j = 1; j < i; j++)
{
printf ( " " );
}
for (j = 1;
j <= (rows * 2 - (2 * i - 1));
j++)
{
printf ( "*" );
}
printf ( "\n" );
}
return 0;
}
|
Output
***************
*************
***********
*********
*******
*****
***
*
Time Complexity: O(n2)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...