Inverted Pyramid Star Pattern Logic
Learn how to flip the mathematical logic of spaces and stars to print an upside-down centered pyramid.
Turning the Pyramid Upside Down
Printing an inverted pyramid tests your ability to reverse both the space generation and the star generation logic simultaneously.
The Problem
Print an inverted pyramid of size N. If N = 3:
*****
***
*
The Analysis (Mathematical Approach)
Let's map N = 3.
- Row 1: 0 spaces, 5 stars.
- Row 2: 1 space, 3 stars.
- Row 3: 2 spaces, 1 star.
The Space Formula:
The spaces increase as the row increases. space = row - 1.
The Star Formula:
The stars decrease by 2 each time. star = 2 * (N - row) + 1.
The Code Implementation (Formula Method)
int n = 3;
for (int row = 1; row <= n; row++) {
for (int space = 1; space <= row - 1; space++) {
System.out.print(" ");
}
for (int star = 1; star <= 2 * (n - row) + 1; star++) {
System.out.print("*");
}
System.out.println();
}
The Simpler Approach (Reversing the Outer Loop)
Instead of recalculating complex formulas, you can literally take the exact code for a normal pyramid and just run the outer loop backward!
int n = 3;
// Start from N, go down to 1
for (int row = n; row >= 1; row--) {
// The exact same inner loops as a normal pyramid!
for (int space = 1; space <= n - row; space++) {
System.out.print(" ");
}
for (int star = 1; star <= (2 * row) - 1; star++) {
System.out.print("*");
}
System.out.println();
}
The Takeaway
In programming, if a problem is simply the reverse of a problem you already solved, don't rewrite the core logic. Just reverse the data flow (the outer loop). It is cleaner, faster, and infinitely less prone to math errors.
Take the exact code used for a normal pyramid, and simply change the outer loop to count down from N to 1 instead of 1 to N.
If counting rows 1 to N, the leading spaces increase according to the formula: row - 1.
If counting rows 1 to N, the stars decrease according to the formula: 2 * (N - row) + 1.
Trailing spaces exist on the right side of the stars, but since there are no visible characters after them, printing a newline immediately achieves the exact same visual result and saves CPU cycles.
No. The number of characters printed is exactly the same, just in a different order. The time complexity remains O(N^2).
