Java Program to Print Floyd Triangle with Output
for loops and a counter variable, for example: int num = 1; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { System.out.print(num++ + " "); } System.out.println(); }.Examples
How to Think About It
Algorithm
Code
public class FloydTriangle { public static void main(String[] args) { int rows = 5; int num = 1; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { System.out.print(num++ + " "); } System.out.println(); } } }
Dry Run
Let's trace printing Floyd's triangle for 3 rows through the code.
Initialize variables
rows = 3, num = 1
First row (i=1)
Print 1, num becomes 2
Second row (i=2)
Print 2 and 3, num becomes 4
Third row (i=3)
Print 4, 5, 6, num becomes 7
| Row (i) | Numbers Printed | Value of num after row |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 2 3 | 4 |
| 3 | 4 5 6 | 7 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to the number of rows, deciding how many rows to print.
Step 2: Inner loop prints numbers per row
The inner for loop runs as many times as the current row number, printing numbers in sequence.
Step 3: Counter increments after each print
The variable num increases by 1 after printing each number to keep the sequence continuous.
Alternative Approaches
public class FloydTriangle { public static void main(String[] args) { int rows = 5; int num = 1; int i = 1; while (i <= rows) { int j = 1; while (j <= i) { System.out.print(num++ + " "); j++; } System.out.println(); i++; } } }
public class FloydTriangle { static int num = 1; public static void printRow(int row, int maxRow) { if (row > maxRow) return; printNumbers(row, 1); System.out.println(); printRow(row + 1, maxRow); } public static void printNumbers(int count, int current) { if (current > count) return; System.out.print(num++ + " "); printNumbers(count, current + 1); } public static void main(String[] args) { printRow(1, 5); } }
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops where the outer loop runs n times and the inner loop runs up to n times cumulatively, resulting in O(n^2) time.
Space Complexity
Only a few variables are used for counting and looping, so space complexity is O(1), constant space.
Which Approach is Fastest?
The for-loop approach is straightforward and efficient; recursion adds overhead and is less practical here.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Simple and efficient printing |
| While loops | O(n^2) | O(1) | Alternative loop style |
| Recursion | O(n^2) | O(n) | Elegant but less efficient |