C++ Program to Print Diamond Pattern
for loops to print spaces and stars in the right order; for example, use for (int i = 1; i <= n; i++) to print the top half and for (int i = n-1; i >= 1; i--) for the bottom half.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n - i; j++) cout << ' '; for (int j = 1; j <= 2 * i - 1; j++) cout << '*'; cout << '\n'; } for (int i = n - 1; i >= 1; i--) { for (int j = 1; j <= n - i; j++) cout << ' '; for (int j = 1; j <= 2 * i - 1; j++) cout << '*'; cout << '\n'; } return 0; }
Dry Run
Let's trace the diamond pattern for 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 spaces first
Each line starts with spaces to center the stars; the number of spaces is n - i for line i.
Step 2: Print stars next
Stars increase by two each line in the top half using 2 * i - 1 to form the diamond shape.
Step 3: Repeat for bottom half
The bottom half reverses the process, decreasing stars and increasing spaces to complete the diamond.
Alternative Approaches
#include <iostream> using namespace std; int main() { int n, i = 1; cin >> n; while (i <= n) { int j = 1; while (j <= n - i) { cout << ' '; j++; } j = 1; while (j <= 2 * i - 1) { cout << '*'; j++; } cout << '\n'; i++; } i = n - 1; while (i > 0) { int j = 1; while (j <= n - i) { cout << ' '; j++; } j = 1; while (j <= 2 * i - 1) { cout << '*'; j++; } cout << '\n'; i--; } return 0; }
#include <iostream> using namespace std; int main() { int n; cin >> n; int total = 2 * n - 1; for (int i = 1; i <= total; i++) { int stars = i <= n ? 2 * i - 1 : 2 * (total - i + 1) - 1; int spaces = (total - stars) / 2; for (int j = 0; j < spaces; j++) cout << ' '; for (int j = 0; j < stars; j++) cout << '*'; cout << '\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 2n times, resulting in O(n^2) time.
Space Complexity
Only a few variables are used; no extra data structures, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar O(n^2) time; using a single loop can be slightly cleaner but does not improve performance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Two for loops (top and bottom) | O(n^2) | O(1) | Simple and clear code |
| While loops | O(n^2) | O(1) | Alternative loop style |
| Single loop with conditions | O(n^2) | O(1) | Compact code combining halves |