Printing a Pyramid Star Pattern (Spaces and Stars)
Master multi-inner-loop patterns by learning how to coordinate leading spaces and asterisks to print a perfectly centered pyramid.
Handling Blank Space
The standard right-angled triangle prints all its stars pushed against the left wall. To print a centered pyramid, you have to realize that blank space is just another character that must be printed mathematically.
The Problem
Print a pyramid of size N. If N = 3:
*
***
*****
The Analysis
For every row, we must print spaces, THEN print stars. This requires two independent inner loops. Let's map N = 3.
- Row 1: 2 spaces, 1 star.
- Row 2: 1 space, 3 stars.
- Row 3: 0 spaces, 5 stars.
The Space Formula:
The spaces decrease as the row increases: N - row. (e.g., 3 - 1 = 2 spaces).
The Star Formula:
The stars follow the odd number progression: (2 * row) - 1.
The Code Implementation
int n = 3;
for (int row = 1; row <= n; row++) {
// Inner Loop 1: Print spaces
for (int space = 1; space <= n - row; space++) {
System.out.print(" ");
}
// Inner Loop 2: Print stars
for (int star = 1; star <= (2 * row) - 1; star++) {
System.out.print("*");
}
// Move to next line
System.out.println();
}
Execution Flow
The outer loop locks onto row = 1. The first inner loop prints 2 spaces and finishes. The second inner loop takes over, prints 1 star, and finishes. Finally, the newline executes.
The Takeaway
A single row can contain multiple, sequential tasks. By breaking a visual pattern down into its distinct character components (spaces vs stars), you can solve complex centering problems with sequential inner loops.
Because you must print a specific, mathematically decreasing number of invisible space characters before you can print the mathematically increasing stars.
No. They are placed sequentially (one after the other) inside the outer loop. The space loop finishes completely before the star loop begins.
If N is the total height and 'row' is the current row, the formula for leading spaces is N - row.
The stars follow the odd-number sequence, which is mathematically represented as (2 * row) - 1.
You either miscalculated the space formula, or you are adding extra spaces after the stars, which pushes the subsequent newlines out of alignment.
