Write a program to print the following pattern:
1
121
12321
1234321
Objective
Write a Java program to print a palindromic number pyramid.
Algorithm / Approach
- Use an outer loop (
i) for 4 rows. - Print decreasing spaces based on
i. - Use a loop (
k) to print ascending numbers from 1 toi. - Use a loop (
m) to print descending numbers fromi-1down to 1. - Print a newline.
Test.java
class Test {
public static void main(String[] a)
{
for(int i = 1; i<=4; i++) {
for(int j = 3; j>=i; j--) {
System.out.print(" ");
}
for(int k = 1; k<=i; k++) {
System.out.print(k);
}
for(int m = i-1; m>=1;m--) {
System.out.print(m);
}
System.out.println();
}
}
}
Explanation of the Program
- This pattern requires three inner loops per row: one for spaces, one for the left half of the numbers, and one for the right half.
- The left half loop counts up from 1 to the current row number
i. - The right half loop counts down from
i-1to 1, creating the mirrored palindromic effect.
Complexity
Time Complexity
O(n2)
Space Complexity
O(1)
Common Mistakes
- Starting the descending loop from
iinstead ofi-1, which would duplicate the peak number (e.g., printing 123321 instead of 12321).