Python Program to Print Floyd Triangle
for i in range(1, n+1): for j in range(i): print(num, end=' ') num += 1 print() where n is the number of rows.Examples
How to Think About It
Algorithm
Code
n = int(input('Enter number of rows: ')) num = 1 for i in range(1, n + 1): for j in range(i): print(num, end=' ') num += 1 print()
Dry Run
Let's trace the program for input n=3 to see how Floyd's triangle is printed.
Initialize
n=3, num=1
First row (i=1)
Print num=1, then num=2; move to next line
Second row (i=2)
Print num=2, num=3, then num=4; move to next line
Third row (i=3)
Print num=4, num=5, num=6, then num=7; move to next line
| Row | Numbers Printed | Next num value |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 2 3 | 4 |
| 3 | 4 5 6 | 7 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, controlling how many rows to print.
Step 2: Inner loop prints numbers in each row
The inner for loop runs as many times as the current row number, printing numbers sequentially.
Step 3: Increment number after each print
After printing each number, num is increased by 1 to keep the sequence continuous.
Step 4: Print new line after each row
A print() statement without arguments moves the cursor to the next line after each row.
Alternative Approaches
n = int(input('Enter number of rows: ')) num = 1 i = 1 while i <= n: j = 0 while j < i: print(num, end=' ') num += 1 j += 1 print() i += 1
n = int(input('Enter number of rows: ')) num = 1 for i in range(1, n + 1): line = ' '.join(str(x) for x in range(num, num + i)) print(line) num += i
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops where the inner loop runs i times for each row i, totaling about n*(n+1)/2 iterations, which is O(n^2).
Space Complexity
Only a few variables are used to track numbers and loops, so space complexity is O(1), constant space.
Which Approach is Fastest?
All approaches have similar time complexity O(n^2). Using string join may be slightly slower due to string operations but improves readability.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Simple and clear logic |
| Nested while loops | O(n^2) | O(1) | Alternative syntax preference |
| Single loop with string join | O(n^2) | O(1) | Cleaner output formatting |