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
- Use an outer loop (
i) from 0 to 4. - Use an inner loop (
j) from 0 toi. - Inside the loop, print
(i + j) % 2followed by a space. - 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
iand column indexj, 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)