Python Program to Print Christmas Tree Pattern
for i in range(1, n+1): print(' '*(n-i) + '*'*(2*i-1)) to create the tree shape.Examples
How to Think About It
Algorithm
Code
n = 5 for i in range(1, n + 1): print(' ' * (n - i) + '*' * (2 * i - 1)) # Print the trunk for _ in range(2): print(' ' * (n - 1) + '*')
Dry Run
Let's trace the program with n=3 to see how it prints the Christmas tree.
First row
Spaces: 3 - 1 = 2, Stars: 2*1 - 1 = 1, Line: ' *'
Second row
Spaces: 3 - 2 = 1, Stars: 2*2 - 1 = 3, Line: ' ***'
Third row
Spaces: 3 - 3 = 0, Stars: 2*3 - 1 = 5, Line: '*****'
| Row | Spaces | Stars | Printed Line |
|---|---|---|---|
| 1 | 2 | 1 | * |
| 2 | 1 | 3 | *** |
| 3 | 0 | 5 | ***** |
Why This Works
Step 1: Calculate spaces
We print spaces first to center the stars. The number of spaces is n - i where i is the current row.
Step 2: Calculate stars
Stars increase by two each row, calculated as 2 * i - 1, making the tree wider as we go down.
Step 3: Print trunk
After printing the leaves, we print the trunk as a vertical line of stars centered under the tree.
Alternative Approaches
n = 5 i = 1 while i <= n: print(' ' * (n - i) + '*' * (2 * i - 1)) i += 1 j = 0 while j < 2: print(' ' * (n - 1) + '*') j += 1
n = 5 for i in range(1, n + 1): print(('*' * (2 * i - 1)).center(2 * n - 1)) for _ in range(2): print('*'.center(2 * n - 1))
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops where the outer loop runs n times and the inner printing of stars can be up to 2n-1 characters, resulting in O(n^2) time.
Space Complexity
The program uses constant extra space for variables and prints directly, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; using string center method can improve readability but not performance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops with manual spaces | O(n^2) | O(1) | Clear control over spacing |
| While loops | O(n^2) | O(1) | Beginners learning loops |
| String center method | O(n^2) | O(1) | Cleaner code, easier to read |
2*i - 1 for stars and n - i for spaces to keep the tree symmetrical.