Floyd Triangle in Java
Build Floyd's triangle in Java with nested loops and a counter kept outside both loops. Post-increment continues across rows; five rows finish at 15.
1public class Main {2 public static void main(String[] args) {3 int n = 5;4 int num = 1;5 for (int i = 1; i <= n; i++) {6 for (int j = 1; j <= i; j++) {7 System.out.print(num++ + " ");8 }9 System.out.println();10 }11 }12}
Sample Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Row 1 uses 1; row 2 uses 2,3; row 3 uses 4,5,6. Five rows consume 15 consecutive numbers.
In this one
- Keep a counter across rows
- Understand print-then-increase
- Distinguish row position from displayed value
How it works
- 1
Set num to 1 outside the loops.
- 2
Choose each row i.
- 3
Print num++ exactly i times.
- 4
Finish the row with a newline.
Edge cases
Resetting too often
Move num = 1 inside the outer loop
Each row starts again at 1, which is a different pattern.
One row
Set n = 1
The output is just 1.
What's going on
Floyd's triangle prints consecutive whole numbers in growing rows. Unlike the number pattern that restarts each row at 1, this one continues counting across row boundaries. It is a useful exercise in deciding where a variable must be created so its value is kept.
The outer loop chooses rows and the inner loop prints i values on row i. num starts at 1 before both loops. The expression num++ prints its current value and then increases it by one. This is called post-increment, meaning the increase happens after that expression uses the value.
With five rows, the final number is 15. Do not put num = 1 inside the outer loop; that would restart the count each row. The newline belongs after the inner loop so that row lengths grow correctly. The value of j counts places within a row while num tracks the value printed across the whole triangle.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is the first value in row 3?
Pick an answer to check it.
Question 2
Where should num start?
Pick an answer to check it.
Questions people ask
Why not print j?
j restarts for each row. num preserves the continuous sequence.
What does num++ print?
It uses the old num for this print and then increases num by one.
How is this different from the basic number triangle?
The basic triangle resets its printed values at each row. Floyd's triangle continues the numbering.