Java program to print Floyd’s triangle

Let’s learn java program to print Floyd’s triangle.

Java program to print Floyd’s triangle

floyd triangle in java is one of the common java interview question. First let’s learn what is floyd’s triangle in java.

Floyd triangle is a right angled triangle of array of natural numbers starting with 1 in the top left corner. In floyd’s triangle there are total (n(n + 1)) / 2 integers where “n” is integers in nth row. Floyd’s triangle pattern looks like this,

1
2 3
4 5 6
7 8 9 10

So to print floyd’s triangle in java first user enters number of rows. To read user input we are using nextInt() method of Scanner class.

Once you have number of rows it is very easy to print floyd’s triangle. If you notice below java program output, floyd’s triangle will look like two dimensional array or a table.

Obviously we need two for loops. First for loop print number of rows and second for loop print numbers in each row.

Here we need to keep an integer outside for loop and increase it on inner for loop. This doesn’t make rows to reset in-between. Now let’s see java program to print floyd’s triangle.

 /*
 * Java program to print floyd's triangle:
 * 1
 * 2 3
 * 4 5 6
 * 7 8 9 10
 */
import java.util.Scanner;
public class PrintFloydsTriangle
{
   public static void main(String[] args)
   {
      int row, y, z, number = 1;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the number of rows of floyd's triangle you want to print: ");
      row = sc.nextInt();
      System.out.println("Floyd's Triangle: ");
      for(y = 1; y <= row; y++)
      {
         for(z = 1; z <= y; z++)
         {
            System.out.print(number + " ");
            number++;
         }
         System.out.println();
      }
      sc.close();
   }
}


Output:

Enter the number of rows of floyd’s triangle you want to print: 4
Floyd’s Triangle:

1
2 3
4 5 6
7 8 9 10

Enter the number of rows of floyd’s triangle you want to print: 5
Floyd’s Triangle:

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