How to Print an Inverted Right-Angled Triangle Pattern
Understand how to reverse mathematical boundaries in your nested loops to print an upside-down star triangle.
Inverting the Logic
Once you can print a standard triangle, printing an inverted one is a simple exercise in reversing mathematical logic.
The Problem
Print an inverted triangle of size N. If N = 4:
****
***
**
*
The Analysis
- Rows: There are exactly N rows. Outer loop runs from 1 to N.
- Columns: Look at the relationship.
- Row 1 has 4 stars.
- Row 2 has 3 stars.
- Row 3 has 2 stars.
- Relationship: As the row increases, the stars decrease. The mathematical formula connecting them is
N - row + 1.- If N=4, Row 1 = 4 - 1 + 1 = 4.
- If N=4, Row 2 = 4 - 2 + 1 = 3.
The Code Implementation (Method 1: Formula)
int n = 4;
for (int row = 1; row <= n; row++) {
// Using the derived mathematical formula
for (int col = 1; col <= n - row + 1; col++) {
System.out.print("*");
}
System.out.println();
}
The Code Implementation (Method 2: Reverse Outer Loop)
Instead of complex math, you can just reverse the outer loop!
int n = 4;
// Start at N, go down to 1
for (int row = n; row >= 1; row--) {
// Inner loop logic stays exactly the same as a normal triangle
for (int col = 1; col <= row; col++) {
System.out.print("*");
}
System.out.println();
}
The Takeaway
There are multiple ways to solve a pattern. You can either construct a complex mathematical boundary for your inner loop, or you can invert the direction of your outer loop to keep the inner logic simple. Flexibility is key.
If the outer loop runs from 1 to N, the number of stars per row is N - row + 1.
Reversing the outer loop (starting from N and decrementing) is usually much cleaner and easier to read, reducing the chance of off-by-one math errors.
Use the same loop structure, but inside the inner loop, print the variable 'col' (for 1234, 123) or 'row' (for 4444, 333).
You likely used <= instead of < when checking the boundary, causing the math to yield 0 on the final iteration, or you started counting from 0 instead of 1 without adjusting the math.
No, traversing from N to 1 takes the exact same amount of hardware cycles as traversing from 1 to N.
