Floyd’s triangle in Java

Floyd's triangle is a is a right angled triangle of natural numbers. Printing Floyd's triangle is usually given as a programming exercise while learning a new language. It is formed by multiple rows of continuously increasing natural numbers with each row having increasing number of natural numbers. One interesting feature of Floyd's triangle is that in each row the last number is a triangular number corresponding to the row number! An n-th triangular number is equal to the sum of all numbers starting from 1 up to n.

For example, the following is a Floyd's triangle with 5 rows,

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

In the above diagram, 4th row has 10 as the last number which is the triangular number for that row (1+2+3+4 = 10)!

Floyd's triangle in Java

The following Java program creates a Floyd's triangle with the specified number of rows.

/* Program to print Floyd's Triangle in Java */
public class FloydTriangle {
    
    public static void main(String[] args) {
        int rows = 6 ;
        printFloydTriangle(rows);
    }
    
    public static void printFloydTriangle(int rows) {
        int current = 1;
        for(int i=1;i<=rows ;i++) {
            for(int j=1;j<=i;j++) {
                System.out.format("%-3d",current++);  // left justified in 3 spaces
            }
            System.out.println();
        }
    }
    
}

 

Note the use of the format string "%-3d". This tells the formatter to print the number left justified within 3 character spaces. This creates a neatly formatted Floyd's Triangle.