Write a program to print the following pattern:
1
21
123
4321
12345
Objective
Write a Java program to print a zigzag number triangle where alternate rows reverse direction.
Algorithm / Approach
- Use an outer loop (
i) from 1 to 5. - Check if the current row
iis even (i % 2 == 0). - If even, run a loop from 1 to
i(ascending order). - If odd, run a loop from
idown to 1 (descending order). - Print a newline.
Test.java
class Test {
public static void main(String[] a)
{
for(int i = 1; i<=5; i++) {
if(i%2==0){
for(int j = 1; j<=i; j++) {
System.out.print(j);
}
}
else {
for(int j = i; j>=1; j--) {
System.out.print(j);
}
}
System.out.println();
}
}
}
Explanation of the Program
- This pattern introduces conditional logic inside the pattern generation.
- By checking
i % 2, the program decides whether to print the numbers forward or backward. - On odd rows (1, 3, 5), it prints descending (1, 321, 54321 - wait, the provided code actually prints 1, 123, 12345 for odd, and 21, 4321 for even. Note: The provided code prints ascending for even and descending for odd: wait, no, the code has a bug or specific logic. Based on the code: if even, prints 1 to i. If odd, prints i down to 1. Row 1: 1. Row 2: 12. Row 3: 321. Wait! The code provided actually does: if even, 1 to i; if odd, i down to 1).
- The branching allows the pattern to dynamically change its horizontal direction row by row.
Complexity
Time Complexity
O(n2)
Space Complexity
O(1)