Floyd’s Triangle:
- Floyd’s triangle is a right angled triangular array of natural numbers.
- It named after Robert Floyd.
- Rows of the triangle filled by consecutive numbers.
- First row will have single number which is 1.
- Second row will have two numbers, which are 2 and 3
- Third row will have three numbers, which are 4, 5 and 6..
- And so on
Example:
First 5 lines… 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Approach:
- Two nested loops.
- Outer loop will take care for rows.
- Inner loop will take care of printing the numbers.
- Line break after each iteration of inner loop.
- Keep track of numbers printed so far in a variable.
- See the code for more understanding.
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FloydTriangle { | |
public static void printTriangle(int rows){ | |
if(rows<=0) | |
return; | |
int count=1; | |
int number = 1; | |
while(count<=rows){ | |
for (int i = 0; i <count ; i++) { | |
System.out.print(number + " "); | |
number++; | |
} | |
count++; | |
System.out.println(); | |
} | |
} | |
public static void main(String[] args) { | |
int rows = 7; | |
printTriangle(rows); | |
} | |
} |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28