Program to print Floyd's triangle in Java
The Floyd’s triangle is a triangle of natural consecutive numbers and it is starting with a 1 to n. it is named after Robert Floyd an American computer scientist.
It looks like the following pattern
1
2 3
4 5 6
7 8 9 10
11 12 113 14 15
import java.util.*;
public class
FloydTriangle
{
public static void main(String args[])
{
int rows; // input number of rows
int i, j; // i and j used as loop
int k = 1; // k generate the floyd's
Triangle
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of
rows to generate Floyd's Triangle:");
rows = sc.nextInt();
// loop
for(i=1; i<=rows; i++)
{
for(j=1; j<=i; j++)
{
// print the values of triangle
System.out.print(k + "
");
k++;
}
System.out.println();
}
}
}
Output:
Enter number of rows
to generate Floyd's Triangle: 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Here another output
with 10 rows
Enter the number of rows
to generate Floyd's Triangle: 10
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
36
37 38 39 40 41 42 43
44 45
46 47 48 49 50 51 52
53 54 55
We can also print with
5 rows Floyd’s triangle as
15
14 13
12 11 10
9 8 7 6
5 4 3 2 1
By just changing k=1
to k=15 and in the loop k++ to k—as below
for(i=1; i<=rows;
i++)
{
for(j=1; j<=i; j++)
{
// print the values of triangle
System.out.print(k + "
");
k--;
}
System.out.println();
}