Print Floyd’s Triangle in java

Exercise:

Write a Java Program to print Floyd’s Triangle.

Click Here to View the Solution!
public class FloydTraingle {
  
   public static void main(String[] args) {
     int rows = 6, number = 1;
  
     for(int i = 1; i <= rows; i++) 
      {
        for(int j = 1; j <= i; j++) {
         System.out.print(number + " ");
         ++number;
       }
        System.out.println();
     }
   }
 } 
Click Here to View the Output!
 1 
 2 3 
 4 5 6 
 7 8 9 10 
 11 12 13 14 15 
 16 17 18 19 20 21 
Click Here to View the Explanation!
  • In this program, we firstly pre-define the number of rows rows =6 and give the initial starting number number = 1.
  • The first for loop determines the row number on which the program is currently executing. Thus, the variable ‘i’ represents the row number. Initially, the value of i is 1. After execution of first loop, program enters the second loop.
  • The second loop which is the inner loop, determines the number of digits to be printed on a row. It works in such a way that it starts from 1 i.e. j=1 every time the outer loop is iterated and then increments till j is less than or equal to i, which in our case is the current row number.
  • So for every iteration of the inner loop, two operations take place. One, the value of number with space character is printed on the screen. And second, the value of number is incremented by 1 so that in the next iteration, the value has exceeded by 1. Since number is a global variable, thus it retains its value even after the inner loop has broken off.
  • When the value of j exceeds the value of i, the inner loop is broken and a new line is printed, which will be the next row of the pyramid. Then the next iteration of outer loop begins which increments i and it goes on till i is less than or equal to the variable rows.