Java program to generate and print Floyd’s triangle

Java Programming Java8Java Technologies

Floyd's triangle, named after Robert Floyd, is a right-angled triangle, which is made using natural numbers. It starts at 1 and consecutively selects the next greater number in the sequence.

Algorithm

  • Take a number of rows to be printed, n.
  • Make outer iteration I for n times to print rows
  • Make inner iteration for J to I
  • Print K
  • Increment K
  • Print NEWLINE character after each inner iteration

Example

import java.util.Scanner;
public class FloyidsTriangle {
   public static void main(String args[]){
      int n,i,j,k = 1;
      System.out.println("Enter the number of lines you need in the FloyidsTriangle");
      Scanner sc = new Scanner(System.in);
      n = sc.nextInt();

      for(i = 1; i <= n; i++) {
         for(j=1;j <= i; j++){
            System.out.print(" "+k++);
         }
         System.out.println();
      }
   }
}

Output

Enter the number of lines you need in the FloyidsTriangle
9
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
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
raja
Published on 25-Apr-2018 13:54:05
Advertisements