Floyd triangle in java

In this post we are going to learn floyd triangle in java. Basically it is named after computer scientist Robert Floyd.

Floyd Triangle In Java

Floyd triangle is a right angled triangular array of natural numbers consisting of numbers starting with 1 in the top left corner.

1
2 3
4 5 6
7 8 9 10

Also read – gcd and lcm of two numbers

As you can see above numbers are filled in rows of triangle. Now let’s see java program to print floyd’s triangle,

import java.util.Scanner;

public class FloydTriangle
{
   public static void main(String[] args)
   {
      int x;
      int number = 1;
      int y;
      int z;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the number of rows to print Floyd's Triangle: ");
      x = sc.nextInt();
      System.out.println("Floyd Triangle : ");
      for(y = 1; y <= x; y++)
      {
         for(z = 1; z <= y; z++)
         {
            System.out.println(number + " ");
            number++;
         }
         System.out.println();
      }
   }
}

Output:

Enter the number of rows to print Floyd’s Triangle: 5
Floyd Triangle :

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


Floyd triangle in java using method

Now let’s learn java program to print floyd’s triangle using method,

import java.util.Scanner;

public class FloydTriangle
{
   public static void main(String[] args)
   {
      int rows;
      Scanner sc = new Scanner(System.in); 
      System.out.println("Enter the number of rows to print Floyd Triangle : ");
      rows = sc.nextInt(); 
      floyd(rows);
      sc.close();
   }
 
   public static void floyd(int rows)
   {
      int a, b, number = 1;
      for(a = 1 ; a <= rows; a++)
      {
         for(b = 1 ; b <= a; b++)
         {
            System.out.format("%d ", number);
            number++;
         }
         System.out.println("");
      }
   }
}

Output:

Enter the number of rows to print Floyd Triangle : 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Related Posts