Python Program to Print Inverted Triangle Pattern
for i in range(n, 0, -1): print('* ' * i) where n is the number of rows.Examples
How to Think About It
Algorithm
Code
n = int(input('Enter number of rows: ')) for i in range(n, 0, -1): print('* ' * i)
Dry Run
Let's trace the program with input 3 to see how it prints the inverted triangle.
Input number of rows
User inputs n = 3
First iteration (i=3)
Print '* ' repeated 3 times: '* * * '
Second iteration (i=2)
Print '* ' repeated 2 times: '* * '
Third iteration (i=1)
Print '* ' repeated 1 time: '* '
| Iteration (i) | Stars Printed |
|---|---|
| 3 | * * * |
| 2 | * * |
| 1 | * |
Why This Works
Step 1: Loop from n down to 1
The outer loop counts down from the total rows to 1, controlling how many stars to print each line.
Step 2: Print stars using string multiplication
For each iteration, printing '* ' multiplied by the current count prints the correct number of stars.
Step 3: Move to next line automatically
The print function adds a newline after each row, so stars appear in a triangle shape.
Alternative Approaches
n = int(input('Enter number of rows: ')) for i in range(n, 0, -1): for j in range(i): print('*', end=' ') print()
n = int(input('Enter number of rows: ')) i = n while i > 0: print('* ' * i) i -= 1
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested printing of stars where the total stars printed is roughly n + (n-1) + ... + 1 = n(n+1)/2, which is O(n^2).
Space Complexity
The program uses constant extra space, only variables for counters; printing does not require extra memory proportional to input.
Which Approach is Fastest?
Using string multiplication is faster and simpler than nested loops because it reduces the number of print calls.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String multiplication | O(n^2) | O(1) | Simple and fast printing |
| Nested loops | O(n^2) | O(1) | More control over printing format |
| While loop | O(n^2) | O(1) | Alternative loop style for beginners |