Floyd triangle in java

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

Floyd Triangle In Java

Floyd triangle is defined as 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 how to print floyd’s triangle in java 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


Program for printing pyramid patterns in java

Now let’s see how to print simple pyramid pattern in java,

import java.util.Scanner;

public class FloydTriangleExample
{
   public static void main(String[] args)
   {
      int row, a, b;
      Scanner sc = new Scanner(System.in); 
      System.out.println("Enter the number of rows : ");
      row = sc.nextInt();
 
      for(a = 1 ; a <= row; a++)
      {
         for(b = 1 ; b <= a; b++)
         {
            System.out.format("* ");
         }
         System.out.println("");
      }
      sc.close();
   }
}

Output:

Enter the number of rows : 6
*
* *
* * *
* * * *
* * * * *
* * * * * *


Related Posts