Frequently Asked Java Program 06: Print a Floyd Triangle of given number of rows

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a Java program to Print a Floyd Triangle of given number of rows.

Problem: Write a java program to print a Floyd’s triangle for a given number of rows.
Solution:

Floyd’s triangle is a right-angled triangular array of natural numbers, used in computer science education. It is named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner:

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

Logic to draw such pattern:

• In JAVA, such patterns are known as pyramid. We can easily draw using matrix.
• First, we think about row count which will be user input. If user enters 5, there will be 5 rows in triangle. For N, there will be N rows in triangle. So we need to have a for loop which will keep track of number of rows. It must start with 1 and iterate till N.
• Now consider number of columns. For first row, there is only column. For second row, there are only two columns. For nth row, there should be only N columns. So we need to use another for loop, which will start from 1 and keep counter till it reaches number of row.
• Since, we need to print natural numbers in a order, we will initialize a variable and increment it after printing once.

Java Program:

```import java.util.Scanner;

public class FloydTriangle {

public static void main(String[] args) {

// input for number of rows
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows: ");
int r = in.nextInt();
int k=1;
System.out.println("Floyd Triangle of rows: "+r);
// for number of rows
for(int i=1;i<=r;i++)
{
// for no of columns in each row
for(int j=1;j<=i;j++)
{
System.out.print(k+++" ");
}
System.out.println();
}
}
}
```

Output:
Enter the number of rows:
7
Floyd Triangle of rows: 7
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

I hope this programming section would be very useful for you all. If you have any doubt, please comment or write to me.

If you like my posts, please like, comment, share and subscribe.

#HappyCoding

1 thought on “Frequently Asked Java Program 06: Print a Floyd Triangle of given number of rows”

1. RANJAN V says:

Nice…)))