Python Program to Print Right Triangle Star Pattern
* equal to the current outer loop count; for example, for i in range(1, n+1): print('*' * i) prints a right triangle star pattern.Examples
How to Think About It
Algorithm
Code
n = int(input("Enter the number of lines: ")) for i in range(1, n + 1): print('*' * i)
Dry Run
Let's trace the program with input n=3 to see how it prints the star pattern.
Input
User inputs n = 3
First iteration (i=1)
Print '*' repeated 1 time: *
Second iteration (i=2)
Print '*' repeated 2 times: **
Third iteration (i=3)
Print '*' repeated 3 times: ***
| i | Printed Stars |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
Why This Works
Step 1: Outer loop controls lines
The outer loop runs from 1 to n, each number representing the current line number.
Step 2: Print stars equal to line number
For each line i, printing '*' repeated i times creates the right triangle shape.
Step 3: Moving to next line
After printing stars for one line, the program moves to the next line until all lines are printed.
Alternative Approaches
n = int(input("Enter number of lines: ")) for i in range(1, n + 1): for j in range(i): print('*', end='') print()
n = int(input("Enter number of lines: ")) for i in range(1, n + 1): print(''.join(['*' for _ in range(i)]))
Complexity: O(n^2) time, O(1) space
Time Complexity
The outer loop runs n times and the inner printing of stars takes up to n steps in the last line, resulting in O(n^2) time.
Space Complexity
The program uses constant extra space, only storing loop counters and printing directly.
Which Approach is Fastest?
Using string multiplication is faster and simpler than nested loops because it avoids inner loop overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String multiplication | O(n^2) | O(1) | Simple and fast printing |
| Nested loops | O(n^2) | O(1) | Explicit control over printing |
| List comprehension | O(n^2) | O(1) | Flexible string building |