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 patterns 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.
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(); } } } |
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)