Floyd's Triangle Program in Java
In this lesson: Print Floyd's triangle in Java with nested loops and a counter — code, dry run and output. In Hindi & English.
What is Floyd's Triangle
Floyd's Triangle is a right-angled triangle of numbers, filled row by row with numbers counting up continuously. Row 1 has one number, row 2 has two, and so on. It is a classic pattern exercise combining nested loops with a running counter.
The pattern
For 4 rows, Floyd's Triangle looks like:
1 2 3 4 5 6 7 8 9 10
Notice the numbers never restart — they flow continuously. Row 3 ends at 6, so row 4 begins at 7. Each row has one more number than the last.
The Java program
public class Floyd {
public static void main(String[] args) {
int rows = 4;
int num = 1; // running counter
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num + " ");
num++; // never resets
}
System.out.println(); // new line per row
}
}
}
2 3
4 5 6
7 8 9 10
The outer loop i is the row; the inner loop runs i times to print that row's numbers. The key is num, which keeps counting up and is never reset.
Dry run
| Row (i) | Printed in that row | num reached |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 2 3 | 4 |
| 3 | 4 5 6 | 7 |
| 4 | 7 8 9 10 | 11 |
Row i prints i numbers. The counter num is never reset between rows, so it flows on: row 3 ends at 6, and row 4 continues from 7.
The running counter
The heart of Floyd's Triangle is that num is declared before the loops and increased after every print, but never reset inside a row. This continuous counting is what makes the numbers flow smoothly from one row to the next, unlike patterns that restart each row.
Common mistakes
- Resetting the counter each row. Declare
numoutside the loops so it keeps rising. - Wrong inner loop limit. Row
ineedsj <= ito print i numbers. - Forgetting the newline. Add
println()after each row. - Confusing rows and counter. Rows control how many numbers; the counter controls their value.
Summary
- Floyd's Triangle fills numbers row by row, continuously.
- Row
ihasinumbers. - Use nested loops: outer for rows, inner for numbers.
- Keep a single counter that never resets between rows.
- Add a newline after each row.
Next, try more shapes in nested loops, or a maths pattern in the Armstrong number program.
Frequently Asked Questions
What is Floyd's Triangle?
How many numbers are in each row?
i has exactly i numbers. So row 1 has 1, row 2 has 2, row 3 has 3. The triangle grows wider by one number each row.How does the counter work in Floyd's Triangle?
Why does Floyd's Triangle need nested loops?
i times for row i, which creates the triangular shape.