Pattern 7
Java source ↗ Edit this article ↗
Jump to code:
Problem
Given an integer n, print a centred pyramid of stars with n rows. Row i (0-based) contains 2i + 1 stars with no spaces between them, preceded by n - 1 - i spaces so that every row is centred under the top star. The last row is 2n - 1 stars wide and starts at the left margin.
Output format: every row ends with a newline and there are no trailing spaces. (Some references print symmetric trailing spaces too; they are invisible and judges ignore them, so this article omits them.) n = 0 prints nothing.
Constraints: 0 ≤ n ≤ 100 is typical.
Example 1
n = 4
*
***
*****
*******
Leading spaces 3, 2, 1, 0 and star counts 1, 3, 5, 7.
Example 2
n = 1
*
A single star with no padding.
The idea: two inner loops, spaces then stars
So far every row consisted of one kind of cell. A centred pyramid is the first pattern where a row has two parts: a run of spaces and a run of stars. The cleanest way to handle that is two inner loops in sequence, one per part, each with its own count. Then the whole problem reduces to two formulas in the row index i:
- stars: the widths are the odd numbers
1, 3, 5, ..., so rowihas2i + 1stars; - spaces: the widest row needs no padding and each row above it needs one more space, so row
ihasn - 1 - ispaces.
Why odd widths? Each step down adds one star on each side of the centre, so the width grows by two. That is also why the leading space count drops by exactly one per row: adding one star on the left shifts the start one column left.
All approaches return the pattern as a String so the tests can compare it with expected literals.
Approach 1: Nested loops
Intuition. For each row, run one loop n - 1 - i times appending a space, then another 2i + 1 times appending a star, then a newline.
Algorithm.
- For
ifrom0ton - 1: - Append
n - 1 - ispaces. - Append
2i + 1stars. - Append
\n.
static String nestedLoops(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1 - i; j++) sb.append(' ');
for (int j = 0; j < 2 * i + 1; j++) sb.append('*');
sb.append('\n');
}
return sb.toString();
}
Complexity. Time O(n^2): row i has n + i characters, so the total is about 1.5 n^2. Space O(n^2) for the output, O(1) extra.
Approach 2: Decide each cell by its distance from the centre
Intuition. Think of the row as a strip of cells numbered from 0. The top star is in column mid = n - 1. In row i a cell c is a star exactly when it is within i columns of the centre, that is when |c - mid| ≤ i; otherwise it is a space. Walking c from 0 to mid + i (the last star) and applying this test gives the row with no trailing spaces. There is a single inner loop with a condition instead of two loops with counts.
This “predicate on (row, column)” view is the most general pattern-printing technique. It is how you handle shapes with holes, hollow borders, or two symmetric halves, where counting runs becomes awkward.
Algorithm.
mid = n - 1.- For
ifrom0ton - 1: forcfrom0tomid + i: append*if|c - mid| ≤ i, else a space. - Append
\nafter each row.
static String centerDistance(int n) {
StringBuilder sb = new StringBuilder();
int mid = n - 1; // column of the top star
for (int i = 0; i < n; i++) {
for (int c = 0; c <= mid + i; c++) {
sb.append(Math.abs(c - mid) <= i ? '*' : ' ');
}
sb.append('\n');
}
return sb.toString();
}
Dry run for n = 3, mid = 2:
| i | columns c |
abs(c - mid) <= i |
row |
|---|---|---|---|
| 0 | 0, 1, 2 | F, F, T | " *" |
| 1 | 0..3 | F, T, T, T | " ***" |
| 2 | 0..4 | T, T, T, T, T | "*****" |
Complexity. Time O(n^2), space O(1) extra.
Approach 3: String.repeat
Intuition. A row is “n - 1 - i spaces followed by 2i + 1 stars”. Java 11’s String.repeat lets you write exactly that: " ".repeat(n - 1 - i) + "*".repeat(2 * i + 1). The loops disappear into the library and the formulas stand alone, which makes mistakes in them obvious.
Algorithm.
- For
ifrom0ton - 1: append" ".repeat(n - 1 - i), then"*".repeat(2 * i + 1), then\n.
static String repeat(int n) {
StringBuilder out = new StringBuilder();
for (int i = 0; i < n; i++) {
out.append(" ".repeat(n - 1 - i)).append("*".repeat(2 * i + 1)).append('\n');
}
return out.toString();
}
Complexity. Time O(n^2), space O(n) extra per row.
Both arguments to repeat are non-negative for every valid i: n - 1 - i ≥ 0 because i ≤ n - 1, and 2i + 1 ≥ 1. A negative count would throw IllegalArgumentException, so when you adapt the formulas, check their range.
Edge cases and pitfalls
n = 0. Returns""; the outer loop does not run.n = 1.mid = 0, zero spaces, one star.- Trailing spaces. If you print symmetric spaces on the right as some tutorials do, string comparison against the expected output fails. Either omit them or strip them before comparing. This article omits them.
- Even widths. If your rows have 2, 4, 6 stars, the formula was
2iinstead of2i + 1and the pyramid will not be centred. - Space count off by one.
n - ispaces shifts the whole pyramid one column right and the last row no longer starts at the margin. The widest row must have zero leading spaces. - Tabs for indentation. Never use
\tto centre; tab width is not fixed. printlnversusprint. The returned string already ends in\n.