Write a program to print the following pattern:
2
4 6
8 10 12
Objective
Write a Java program to print a right-angled triangle filled with sequential even numbers.
Algorithm / Approach
- Initialize an integer
k = 1outside the loops. - Use an outer loop for the rows (1 to 3).
- Use an inner loop for the columns (1 to
i). - Print
(2 * k)followed by a space. - Increment
kby 1. - Print a newline at the end of each row.
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((2*k)+" ");
k++;
}
System.out.println();
}
}
}
Explanation of the Program
- Unlike previous patterns that reset their numbers on every row, this pattern continues counting upwards sequentially.
- The variable
kis declared outside the loops so it retains its state across row changes. - Multiplying
kby 2 ensures that only even numbers (2, 4, 6, 8...) are printed.
Complexity
Time Complexity
O(n2)
Space Complexity
O(1)