Skip to main content

ProwessApps

Learn · Practice · Excel

Write a program to print the following pattern:
0
1 0
0 1 0
1 0 1 0
0 1 0 1 0

Java Code Example — Pattern Programs

ADVERTISEMENT

Write a program to print the following pattern:
0
1 0
0 1 0
1 0 1 0
0 1 0 1 0

Objective

Write a Java program to print a binary (0 and 1) alternating right-angled triangle.

Algorithm / Approach

  1. Use an outer loop (i) from 0 to 4.
  2. Use an inner loop (j) from 0 to i.
  3. Inside the loop, print (i + j) % 2 followed by a space.
  4. Print a newline.
Test.java
class Test {
 public static void main(String[] a)
 {
  for(int i = 0; i<=4; i++) {
   for(int j = 0; j<=i; j++) {
    System.out.print((i+j)%2+" ");
   }
   System.out.println();
  }
 }
}

Explanation of the Program

  • This pattern alternates 0s and 1s in a checkerboard fashion.
  • A clever mathematical trick is used: by adding the row index i and column index j, and taking modulo 2, the result perfectly alternates between 0 and 1 across both rows and columns.
  • This avoids needing a toggle variable that constantly switches state.

Complexity

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