C Program to Print Diamond Pattern
for loops to print spaces and stars in increasing and then decreasing order, like for (int i = 1; i <= n; i++) for the top and for (int i = n-1; i > 0; i--) for the bottom part.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int n = 5; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n - i; j++) printf(" "); for (int k = 1; k <= 2 * i - 1; k++) printf("*"); printf("\n"); } for (int i = n - 1; i > 0; i--) { for (int j = 1; j <= n - i; j++) printf(" "); for (int k = 1; k <= 2 * i - 1; k++) printf("*"); printf("\n"); } return 0; }
Dry Run
Let's trace n=3 through the code
Top half line 1
Print 2 spaces and 1 star: ' *'
Top half line 2
Print 1 space and 3 stars: ' ***'
Top half line 3
Print 0 spaces and 5 stars: '*****'
Bottom half line 1
Print 1 space and 3 stars: ' ***'
Bottom half line 2
Print 2 spaces and 1 star: ' *'
| Line | Spaces | Stars | Output |
|---|---|---|---|
| 1 | 2 | 1 | * |
| 2 | 1 | 3 | *** |
| 3 | 0 | 5 | ***** |
| 4 | 1 | 3 | *** |
| 5 | 2 | 1 | * |
Why This Works
Step 1: Print top half
The first loop prints lines with spaces decreasing and stars increasing using n - i spaces and 2*i - 1 stars.
Step 2: Print bottom half
The second loop prints lines with spaces increasing and stars decreasing, mirroring the top half.
Step 3: Use nested loops
Nested loops control spaces and stars separately for each line to form the diamond shape.
Alternative Approaches
#include <stdio.h> int main() { int n = 5, i = 1, j, k; while (i <= n) { j = 1; while (j <= n - i) { printf(" "); j++; } k = 1; while (k <= 2 * i - 1) { printf("*"); k++; } printf("\n"); i++; } i = n - 1; while (i > 0) { 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> int main() { int n = 5, total = 2 * n - 1; for (int line = 1; line <= total; line++) { int stars = line <= n ? 2 * line - 1 : 2 * (total - line + 1) - 1; int spaces = (total - stars) / 2; for (int s = 0; s < spaces; s++) printf(" "); for (int st = 0; st < stars; st++) printf("*"); printf("\n"); } return 0; }
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops where the outer loop runs about 2n times and inner loops run up to n times, resulting in O(n^2) time.
Space Complexity
Only a few variables are used; no extra memory proportional to input size, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar O(n^2) time; using a single loop with calculations can be slightly cleaner but not faster.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Simple and clear code |
| While loops | O(n^2) | O(1) | Alternative syntax preference |
| Single loop with condition | O(n^2) | O(1) | Compact code combining halves |