Thursday, September 25, 2025
HomeLanguagesJavaJava Program to Display Floyd’s Triangle

Java Program to Display Floyd’s Triangle

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:

  1. Initialization of variables
    • Create variables in memory holding rows and columns.
    • Create and initialize variable holding patterns or values to be displayed.
  2. Traversing over rows and columns using nested for loops.
    • Outer loop for rows.
    • Inner loop for columns in the current row.
  3. 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.

Implementation: Floyd’s Triangle

Example 

Java




// Java program to display Floyd's triangle
 
// Importing Java libraries
import java.util.*;
 
// Main class
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();
        }
    }
}


Output

1  
2  3  
4  5  6  
7  8  9  10  
11  12  13  14  15

Time Complexity: O(n2) for given n

Auxiliary Space: O(1)

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32319 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6680 POSTS0 COMMENTS
Nicole Veronica
11852 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6794 POSTS0 COMMENTS
Ted Musemwa
7070 POSTS0 COMMENTS
Thapelo Manthata
6752 POSTS0 COMMENTS
Umr Jansen
6761 POSTS0 COMMENTS