Floyd’s triangle is a triangle with first natural numbers. It is the right arrangement of the numbers/values or patterns. Basically, it is a left to right arrangement of natural numbers in a right-angled triangle
Illustration: Suppose if no of rows to be displayed is 5 then the desired output should display 5 rows as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Algorithm:
- Initialization of variables
- Create variables in memory holding rows and columns.
- Create and initialize variable holding patter or values to be displayed.
- Traversing over rows and columns using nested for loops.
- Outer loop for rows.
- Inner loop for columns in the current row.
- Dealing with variable holding dynamic values as per execution as initialized outside nested loops.
- If values are to be displayed, increment this variable inside the loop for rows and outside loop for columns.
- If patterns are to be displayed, assign the character outside loop while creation and no alternation of holder value in any of loops.
Below is the implementation of Floyd’s Triangle:
Java
// Java program to display Floyd's triangle // Importing Java libraries import java.util.*; class GFG { // Main driver method public static void main(String[] args) { // No of rows to be printed int n = 5 ; // Creating and initializing variable for // rows, columns and display value int i, j, k = 1 ; // Nested iterating for 2D matrix // Outer loop for rows for (i = 1 ; i <= n; i++) { // Inner loop for columns for (j = 1 ; j <= i; j++) { // Printing value to be displayed System.out.print(k + " " ); // Incremeting value displayed k++; } // Print elements of next row System.out.println(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.