Skip to main content

ProwessApps

Learn · Practice · Excel

Write a program to print the following pattern:
1
121
12321
1234321

Java Code Example — Pattern Programs

ADVERTISEMENT

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

  1. Use an outer loop (i) for 4 rows.
  2. Print decreasing spaces based on i.
  3. Use a loop (k) to print ascending numbers from 1 to i.
  4. Use a loop (m) to print descending numbers from i-1 down to 1.
  5. 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-1 to 1, creating the mirrored palindromic effect.

Complexity

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

Common Mistakes

  • Starting the descending loop from i instead of i-1, which would duplicate the peak number (e.g., printing 123321 instead of 12321).
ADVERTISEMENT