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
- Use an outer loop (
i) from 1 to 4. - Print increasing spaces using a loop from 1 to
i-1. - Print the left half of the numbers counting up to
5-i. - Print the right half of the numbers counting down from
4-ito 1. - 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
iincreases. - The math
5-iand4-idynamically 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)