Write a program to print the following pattern:
1
2 3
4 5 6
7 8 9 10
Objective
Write a Java program to print Floyd's Triangle (a right-angled triangle with running sequential numbers).
Algorithm / Approach
- Initialize a counter
k = 1outside the loops. - Use an outer loop (
i) from 1 to 4. - Use an inner loop (
j) from 1 toi. - Print the value of
k, then incrementkby 1. - Print a newline.
Test.java
class Test {
public static void main(String[] a)
{
int k = 1;
for(int i = 1; i<= 4; i++) {
for(int j = 1; j<=i; j++) {
System.out.print(k+" ");
k++;
}
System.out.println();
}
}
}
Explanation of the Program
- Floyd's Triangle is a classic computer science problem.
- Similar to the even-number triangle, it relies on a stateful variable (
k) declared outside the loops. - The variable simply increments by 1 on every single inner loop execution, creating a continuous sequence spanning across multiple rows.
Complexity
Time Complexity
O(n2)
Space Complexity
O(1)