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

One thought on “Java Program 06: Print a Floyd Triange of given number of rows

Leave a Reply