Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Floyd Triangle

Print Floyd's triangle with a counter shared across rows. Students trace Python nested loops and distinguish a persistent number from a reset column index.

IntermediatePhase 2 - Level 4: Pattern PrintingExample 10 of 13
floyd-triangle.py
1# Take n
2n = int(input("Enter number of rows: "))
3
4# Print Floyd triangle
5num = 1
6for i in range(1, n + 1):
7 for j in range(1, i + 1):
8 print(num, end=" ")
9 num += 1
10 print()

Output

Enter number of rows: 4
1
2 3
4 5 6
7 8 9 10

In this one

  • Keep a shared counter
  • Increase row capacity
  • Continue numbering across rows

How it works

  1. 1

    Initialize num once before the loops.

  2. 2

    Print num in each cell and increment it.

  3. 3

    End a row after i cells without resetting num.

Edge cases

What is the first number in row three?

What is the first number in row three?

Four.

What does n = 0 do?

What does n = 0 do?

No cells or rows print.

What's going on

num begins at one before either loop. Each cell prints num and then increments it, so numbering continues when the next row starts.

For three rows, the values are 1, then 2 3, then 4 5 6. The outer loop decides how many cells a row has; num decides their contents. Moving its initialization inside the row loop would restart the sequence.

What is the first number in row three? Four.

What does n = 0 do? No cells or rows print.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why initialize num outside the loops?

Pick an answer to check it.

Question 2

What is the first number in row three?

Pick an answer to check it.

Questions people ask

What is the first number in row three?

Four.

What does n = 0 do?

No cells or rows print.

Why initialize num outside the loops?

It must continue across rows.