Assignment: Module 03- Part 01
![]() |
Assignment: Module 03- Part 01 |
11. Write a class FloydExample1 to display the output as below using control structures Enter the value of Floyd triangle 3
Output:
1 1
2 2 2
3 3 3 3
class FloydExample1 {
void floydTriangle(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
public class Main {
public static void main(String[] args) {
FloydExample1 obj = new FloydExample1();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of Floyd triangle: ");
int n = sc.nextInt();
obj.floydTriangle(n);
}
}
In the above code, we create a class 'FloydExample1' with a method 'floydTriangle' which accepts an integer and prints the Floyd triangle of the number passed. In the main method, we create an object of the 'FloydExample1' class, take input from the user for the number, then call the 'floydTriangle' method with the number passed as an argument.
The output of the above code when the input is 3 is
1
2 2
3 3 3
The Floyd's triangle is a right-angled triangle where the first and the last number of each row is 1 and the middle numbers of each row are consecutive integers starting from 2. This pattern is formed using nested loops, where the outer loop is to handle the rows and the inner loop is to handle the columns.
In this example, I used two nested loops, where the outer loop iterates through the number of rows and the inner loop iterates through the number of columns. The inner loop prints the current value of the outer loop 'i' for the number of times equal to the current row number.
Each time the inner loop runs, the value of 'i' is incremented and the same number of 'i' is printed in each row.