Print Floyd's Triangle in Java
Problem
Floyd's triangle is a triangle of consecutive natural numbers, where the count keeps climbing from one row straight into the next instead of restarting.
Given a number of rows, print Floyd's triangle — row i containing i numbers, counting continuously from 1.
Java Program
public class FloydsTriangle {
public static void main(String[] args) {
int n = 5;
int num = 1; // shared across every row, never reset
for (int i = 1; i <= n; i++) {
StringBuilder line = new StringBuilder();
for (int j = 1; j <= i; j++) {
if (j > 1) line.append(" ");
line.append(num);
num++;
}
System.out.println(line);
}
}
}Output
Core Logic
Keeping a single counter alive outside the row loop, instead of resetting it every row, lets the numbers climb continuously across the whole triangle.
- 1
numis declared once, before the outer loop, starting at 1. - 2The outer loop runs
ifrom 1 ton, and the inner loop runsjfrom 1 toi, printingnumand incrementing it after every single number. - 3Because
numlives outside the outer loop, it's never reset — it just keeps counting up as row after row consumes it. - 4Row
iends up holding exactlyiconsecutive numbers, continuing from wherever the previous row left off.
n = 5, row 3 doesn't restart at 1 — it picks up right where row 2 ended, printing 4 5 6.Key Point: This is the one difference from a plain number triangle — there, the inner counter resets every row; here, it's declared outside the row loop specifically so it never does.
Why: The total count of numbers printed is still proportional to n² — the only difference from the plain number triangle is that the running counter is shared instead of reset each row.