Skip to main content

ProwessApps

Learn · Practice · Excel

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

Java Code Example — Pattern Programs

ADVERTISEMENT

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

Objective

Write a Java program to print an inverted palindromic number pyramid.

Algorithm / Approach

  1. Use an outer loop (i) from 1 to 4.
  2. Print increasing spaces using a loop from 1 to i-1.
  3. Print the left half of the numbers counting up to 5-i.
  4. Print the right half of the numbers counting down from 4-i 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 =1; j < i;j++) {
    System.out.print(" ");
   }
   for(int j = 1; j<=5-i; j++) {
    System.out.print(j);
   }
   for(int k = 4-i;k>=1; k--) {
    System.out.print(k);
   }
   System.out.println();
  }
 }
}

Explanation of the Program

  • This is an inverted version of the standard number pyramid.
  • Instead of growing larger, the bounds of the number loops shrink as i increases.
  • The math 5-i and 4-i dynamically reduces the peak number on each subsequent row (e.g., Row 1 goes up to 4, Row 2 goes up to 3, etc.).

Complexity

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