Skip to main content

ProwessApps

Learn · Practice · Excel

Write a program to print the following pattern:
2
4 6
8 10 12

Java Code Example — Pattern Programs

ADVERTISEMENT

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

  1. Initialize an integer k = 1 outside the loops.
  2. Use an outer loop for the rows (1 to 3).
  3. Use an inner loop for the columns (1 to i).
  4. Print (2 * k) followed by a space.
  5. Increment k by 1.
  6. 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 k is declared outside the loops so it retains its state across row changes.
  • Multiplying k by 2 ensures that only even numbers (2, 4, 6, 8...) are printed.

Complexity

Time Complexity O(n2)
Space Complexity O(1)
ADVERTISEMENT