Python Program to Print Diamond Star Pattern
for i in range(n) to print spaces and stars in increasing and then decreasing order, for example: for i in range(n): print(' '*(n-i-1) + '*'*(2*i+1)) and then reverse 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 n=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 | Printed Line |
|---|---|---|---|
| 0 | 2 | 1 | * |
| 1 | 1 | 3 | *** |
| 2 | 0 | 5 | ***** |
| 1 | 1 | 3 | *** |
| 0 | 2 | 1 | * |
Why This Works
Step 1: Top half printing
The first loop prints the top half of the diamond by decreasing spaces and increasing stars using print(' ' * (n - i - 1) + '*' * (2 * i + 1)).
Step 2: Bottom half printing
The second loop prints the bottom half by increasing spaces and decreasing stars, reversing the top half pattern.
Step 3: Center alignment
Spaces before stars center the pattern horizontally, making the diamond shape symmetrical.
Alternative Approaches
n = int(input('Enter diamond size: ')) for i in range(n): print(('*' * (2 * i + 1)).center(2 * n - 1)) for i in range(n - 2, -1, -1): print(('*' * (2 * i + 1)).center(2 * n - 1))
n = int(input('Enter diamond size: ')) for i in range(2 * n - 1): if i < n: stars = 2 * i + 1 spaces = n - i - 1 else: stars = 2 * (2 * n - i - 2) + 1 spaces = i - n + 1 print(' ' * spaces + '*' * stars)
Complexity: O(n^2) time, O(1) space
Time Complexity
The program runs two loops each up to n, printing up to 2*n-1 characters per line, resulting in O(n^2) time.
Space Complexity
Only a few variables are used; printing is done directly, so space is O(1).
Which Approach is Fastest?
All approaches have similar time and space complexity; using center() is cleaner but not faster.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops with manual spaces | O(n^2) | O(1) | Clear control over spaces and stars |
| Using string center() | O(n^2) | O(1) | Cleaner code, easier to read |
| Single loop with conditions | O(n^2) | O(1) | Compact code, slightly complex logic |