Easy–medium · nested loops

Star Pyramid

Print a centered pyramid of stars with N rows. Pattern printing is where loops stop being abstract — you can see an off-by-one in the shape.

At a glanceRow i is N−i spaces followed by 2i−1 stars, printed with two nested loops — the leading spaces are part of the expected output, so a flush-left pyramid is rejected.

Problem

Input: one integer N (1 ≤ N ≤ 20).

Output: a pyramid with N rows. Row i (counting from 1) has N − i leading spaces followed by 2i − 1 stars.

Sample: for N = 3:

  *
 ***
*****

Row 1: 2 spaces + 1 star. Row 2: 1 space + 3 stars. Row 3: 0 spaces + 5 stars. Spaces matter — the judge compares them.

Your solution

main.cpp — your solution
Custom input for "Run my input"

Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.

Stuck? Hints

Hint 1 — think in rows, then columns

One outer for over rows i = 1…N. For each row, two inner loops: first print n - i spaces, then print 2*i - 1 stars, then cout << endl;. Nested loops = one thing per level.

Hint 2 — debug with N=1 and N=2

Run tiny cases first. If N=1 works but N=2 is misaligned, your space count is off by one — the formulas n - i and 2*i - 1 are the whole problem; get them from counting the sample, not from guessing.

Solution (try it first!)
#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        for (int s = 0; s < n - i; s++) cout << " ";
        for (int k = 0; k < 2 * i - 1; k++) cout << "*";
        cout << endl;
    }
    return 0;
}

Once it passes, remix it: right triangle (drop the space loop), inverted pyramid (count i down), hollow pyramid (stars only at edges — if/else inside the inner loop). Same three skeletons cover half the pattern problems on the internet. Next: Prime Check.

Deep dive

Why this works

Two counters per row — spaces then stars — teach the rule that nested loops mean one loop per dimension of the output.

The cost

O(n²) characters printed. The output itself is quadratic, so no algorithm can beat it.

Where it goes wrong

  • Leading spaces are compared byte for byte — one too many and the row is wrong. Trailing spaces are trimmed by this judge (real OJs usually are not).
  • Memorising 2*i - 1 works until you change the base. Derive the count from the row number each time.

Next step

Nesting with numeric output: Multiplication Table.

Two things to remember

  • One loop per dimension of the output.
  • Leading spaces matter; trailing spaces fail.
🐞 This version fails — open it and try

One leading space too many on every row

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n - i + 1; j++) cout << " ";
        for (int j = 1; j <= 2 * i - 1; j++) cout << "*";
        cout << endl;
    }
    return 0;
}