Java ProgramsPatternsPrint Floyd's Triangle

Print Floyd's Triangle in Java

beginner·  Patterns  ·  Number Patterns

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.

Input
n = 5
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Java Program

Java
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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

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.

How It Works
  1. 1num is declared once, before the outer loop, starting at 1.
  2. 2The outer loop runs i from 1 to n, and the inner loop runs j from 1 to i, printing num and incrementing it after every single number.
  3. 3Because num lives outside the outer loop, it's never reset — it just keeps counting up as row after row consumes it.
  4. 4Row i ends up holding exactly i consecutive numbers, continuing from wherever the previous row left off.
For 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.

Complexity
Time Complexity: O(n²)Space Complexity: O(1)

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.

Key Concepts

nested for loopshared countercontinuous sequence

Related Programs