Write a program to print the following pattern:
1
3 3
5 5 5
7 7 7 7
Objective
Write a Java program to print a right-angled triangle where each row is filled with the same odd number.
Algorithm / Approach
- Use an outer loop (
i) from 0 to 3. - Use an inner loop (
j) from 0 toi. - Inside the loop, print
(2 * i + 1)followed by a space. - Print a newline.
Test.java
class Test {
public static void main(String[] a)
{
int k = 1;
for(int i = 0; i< 4; i++) {
for(int j = 0; j<=i; j++) {
System.out.print((2*i+1)+" ");
}
System.out.println();
}
}
}
Explanation of the Program
- Because the number printed relies on the outer loop variable
i, the number remains constant across the entire row. - The formula
2 * i + 1generates the sequence of odd numbers (1, 3, 5, 7) based on the current row index.
Complexity
Time Complexity
O(n2)
Space Complexity
O(1)