You are here

Java program to print Floyd's triangle

Java program to display Floyd's triangle. In Floyd's triangle, there are n integers in the nth row and a total of (n(n+1))/2 integers in n rows. It is a simple pattern to print but helpful in learning how to create other patterns. Key to develop patterns is using nested loops appropriately.

Java programming source code

  1. import java.util.Scanner;
  2.  
  3. class FloydTriangle
  4. {
  5.   public static void main(String args[])
  6.   {
  7.     int n, num = 1, c, d;
  8.     Scanner in = new Scanner(System.in);
  9.  
  10.     System.out.println("Enter the number of rows of Floyd's triangle to display");
  11.     n = in.nextInt();
  12.  
  13.     System.out.println("Floyd's triangle:");
  14.  
  15.     for (c = 1; c <= n; c++)
  16.     {
  17.       for (d = 1; d <= c; d++)
  18.       {
  19.         System.out.print(num+" ");
  20.         num++;
  21.       }
  22.  
  23.       System.out.println(); // Moving to next row
  24.     }
  25.   }
  26. }

Output of program:
Java Floyd's triangle program output

Download Floyd's triangle program class file.