C Program to Print Pyramid Pattern
for loops where the outer loop controls the rows and the inner loops print spaces and stars; for example: for(i=1; i<=n; i++){ for(j=1; j<=n-i; j++) printf(" "); for(k=1; 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 = 1; i <= n; i++) { for(j = 1; j <= n - i; j++) printf(" "); for(k = 1; k <= 2 * i - 1; k++) printf("*"); printf("\n"); } return 0; }
Dry Run
Let's trace the program for input n=3 to see how spaces and stars print each row.
Row 1
Print 2 spaces and 1 star: ' *'
Row 2
Print 1 space and 3 stars: ' ***'
Row 3
Print 0 spaces and 5 stars: '*****'
| Row | Spaces | Stars | Output |
|---|---|---|---|
| 1 | 2 | 1 | * |
| 2 | 1 | 3 | *** |
| 3 | 0 | 5 | ***** |
Why This Works
Step 1: Outer loop controls rows
The for loop with variable i runs from 1 to n, controlling how many rows the pyramid has.
Step 2: Print spaces before stars
For each row, print n - i spaces to align stars in the center forming the pyramid shape.
Step 3: Print stars increasing by two
Print 2 * i - 1 stars for each row, increasing the count by two to form the pyramid's width.
Alternative Approaches
#include <stdio.h> int main() { int n, i = 1, j, k; printf("Enter number of rows: "); scanf("%d", &n); while(i <= n) { j = 1; while(j <= n - i) { printf(" "); j++; } k = 1; while(k <= 2 * i - 1) { printf("*"); k++; } printf("\n"); i++; } return 0; }
#include <stdio.h> void printPyramid(int n, int row) { if(row > n) return; for(int i = 1; i <= n - row; i++) printf(" "); for(int i = 1; i <= 2 * row - 1; i++) printf("*"); printf("\n"); printPyramid(n, row + 1); } int main() { int n; printf("Enter number of rows: "); scanf("%d", &n); printPyramid(n, 1); 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 n times, resulting in O(n^2) time.
Space Complexity
Only a few integer variables are used; no extra space proportional to input size, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; iterative for-loop method is simplest and most readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Simplicity and readability |
| While loops | O(n^2) | O(1) | Explicit loop control |
| Recursion | O(n^2) | O(n) due to call stack | Demonstrating recursion |