Python Program to Print Diamond Pattern
for loops to print spaces and stars in the right order, for example: for i in range(n): print(' '*(n-i-1) + '*'*(2*i+1)) for the top half and similarly for the bottom half.Examples
How to Think About It
Algorithm
Code
n = int(input('Enter diamond size: ')) for i in range(n): print(' ' * (n - i - 1) + '*' * (2 * i + 1)) for i in range(n - 2, -1, -1): print(' ' * (n - i - 1) + '*' * (2 * i + 1))
Dry Run
Let's trace input 3 through the code
Top half loop i=0
Print 2 spaces and 1 star: ' *'
Top half loop i=1
Print 1 space and 3 stars: ' ***'
Top half loop i=2
Print 0 spaces and 5 stars: '*****'
Bottom half loop i=1
Print 1 space and 3 stars: ' ***'
Bottom half loop i=0
Print 2 spaces and 1 star: ' *'
| i | Spaces | Stars | Line Printed |
|---|---|---|---|
| 0 | 2 | 1 | * |
| 1 | 1 | 3 | *** |
| 2 | 0 | 5 | ***** |
| 1 | 1 | 3 | *** |
| 0 | 2 | 1 | * |
Why This Works
Step 1: Print top half
The first loop prints lines with increasing stars centered by spaces using print(' ' * (n - i - 1) + '*' * (2 * i + 1)).
Step 2: Print bottom half
The second loop prints lines with decreasing stars in reverse order to complete the diamond shape.
Step 3: Center alignment
Spaces before stars ensure the diamond is centered horizontally.
Alternative Approaches
n = int(input('Enter diamond size: ')) i = 0 while i < n: print(' ' * (n - i - 1) + '*' * (2 * i + 1)) i += 1 i = n - 2 while i >= 0: print(' ' * (n - i - 1) + '*' * (2 * i + 1)) i -= 1
n = int(input('Enter diamond size: ')) width = 2 * n - 1 for i in range(n): print(('*' * (2 * i + 1)).center(width)) for i in range(n - 2, -1, -1): print(('*' * (2 * i + 1)).center(width))
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses two loops each running about n times, and each line prints up to 2n-1 characters, so overall time is O(n^2).
Space Complexity
Only a few variables are used and output is printed directly, so space is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; using center() may improve readability but not speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops with spaces | O(n^2) | O(1) | Simple and clear |
| While loops | O(n^2) | O(1) | Alternative loop style |
| String center method | O(n^2) | O(1) | Cleaner alignment |