C Program to Print Inverted Pyramid Pattern
for loops where the outer loop controls the rows and the inner loops print spaces and stars, for example: for(int i = n; i >= 1; i--) { for(int j = 0; j < n - i; j++) printf(" "); for(int k = 0; k < 2*i - 1; k++) printf("*"); printf("\n"); }.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int n, i, j, k; printf("Enter number of rows: "); scanf("%d", &n); for(i = n; i >= 1; i--) { for(j = 0; j < n - i; j++) printf(" "); for(k = 0; k < 2*i - 1; k++) printf("*"); printf("\n"); } return 0; }
Dry Run
Let's trace the program with input 3 to see how it prints the inverted pyramid.
Input
User enters n = 3
First row (i=3)
Print 0 spaces, then print 5 stars (2*3-1)
Second row (i=2)
Print 1 space, then print 3 stars (2*2-1)
Third row (i=1)
Print 2 spaces, then print 1 star (2*1-1)
| Row (i) | Spaces (n - i) | Stars (2*i - 1) |
|---|---|---|
| 3 | 0 | 5 |
| 2 | 1 | 3 |
| 1 | 2 | 1 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from n down to 1, controlling how many rows the pyramid has.
Step 2: Print spaces to center stars
The first inner loop prints spaces equal to n - i to shift stars right and center the pyramid.
Step 3: Print stars in decreasing odd numbers
The second inner loop prints stars equal to 2*i - 1, which decreases by 2 each row, forming the inverted pyramid shape.
Alternative Approaches
#include <stdio.h> int main() { int n, i, j, k; printf("Enter number of rows: "); scanf("%d", &n); i = n; while(i >= 1) { j = 0; while(j < n - i) { printf(" "); j++; } k = 0; while(k < 2*i - 1) { printf("*"); k++; } printf("\n"); i--; } return 0; }
#include <stdio.h> void printRow(int spaces, int stars) { if(spaces > 0) { printf(" "); printRow(spaces - 1, stars); } else if(stars > 0) { printf("*"); printRow(0, stars - 1); } } void printPyramid(int n) { if(n == 0) return; printRow(n - 1, 2*n - 1); printf("\n"); printPyramid(n - 1); } int main() { int n; printf("Enter number of rows: "); scanf("%d", &n); printPyramid(n); return 0; }
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops where the outer loop runs n times and inner loops run up to 2*n times in total, resulting in O(n^2) time.
Space Complexity
Only a few integer variables are used, so space complexity is O(1), constant space.
Which Approach is Fastest?
The for-loop approach is straightforward and efficient; recursion adds overhead and is less readable for this simple pattern.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Simple and clear pattern printing |
| While loops | O(n^2) | O(1) | Equivalent to for loops, more verbose |
| Recursion | O(n^2) | O(n) | Elegant but less efficient and complex |