Python Program to Print Right Triangle Pattern
You can print a right triangle pattern in Python using nested loops like
for i in range(1, n+1): print('*' * i) where n is the number of rows.Examples
Input3
Output*
**
***
Input5
Output*
**
***
****
*****
Input1
Output*
How to Think About It
To print a right triangle pattern, think of printing one star on the first line, two stars on the second, and so on until the given number of rows. Use a loop that counts from 1 up to the number of rows, and in each step, print that many stars.
Algorithm
1
Get the number of rows (n) from the user or input.2
Start a loop from 1 to n (inclusive).3
In each iteration, print stars equal to the current loop number.4
Move to the next line after printing stars for that row.Code
python
n = int(input('Enter number of rows: ')) for i in range(1, n + 1): print('*' * i)
Output
Enter number of rows: 5
*
**
***
****
*****
Dry Run
Let's trace the program for input 3 to see how it prints the right triangle.
1
Input number of rows
User inputs n = 3
2
First iteration (i=1)
Print '*' repeated 1 time: *
3
Second iteration (i=2)
Print '*' repeated 2 times: **
4
Third iteration (i=3)
Print '*' repeated 3 times: ***
| Iteration (i) | Stars Printed |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
Why This Works
Step 1: Loop controls rows
The for loop runs from 1 to n, controlling how many lines to print.
Step 2: Stars printed per row
In each loop, '*' * i creates a string with i stars, matching the row number.
Step 3: Print moves to next line
Each print outputs stars and moves to the next line automatically, forming the triangle shape.
Alternative Approaches
Using nested loops
python
n = int(input('Enter number of rows: ')) for i in range(1, n + 1): for j in range(i): print('*', end='') print()
This uses two loops: outer for rows, inner for printing stars one by one; slightly longer but shows loop nesting.
Using while loop
python
n = int(input('Enter number of rows: ')) i = 1 while i <= n: print('*' * i) i += 1
Uses a while loop instead of for loop; good for beginners to understand loop control.
Complexity: O(n^2) time, O(1) space
Time Complexity
The outer loop runs n times, and printing stars takes up to n operations per line, resulting in O(n^2) time.
Space Complexity
The program uses constant extra space, only storing loop counters and printing directly, so O(1) space.
Which Approach is Fastest?
Using string multiplication is faster and simpler than nested loops printing stars one by one.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String multiplication | O(n^2) | O(1) | Simple and fast printing |
| Nested loops | O(n^2) | O(1) | Understanding loop nesting |
| While loop | O(n^2) | O(1) | Loop control practice |
Use string multiplication
'*' * i to quickly print repeated stars in each row.Beginners often forget to increase the loop counter or print stars on the same line without moving to the next line.