SyntaxPilot
Courses/C Coding Questions/Lesson 1

C Coding Questions · Lesson 1 of 30 · 11 min

Pattern printing I

right-angle star trianglenumber pyramidinverted triangle; how to plan rows and columnsnested loopsoff-by-one errors

These are the notes for C Coding Questions, episode 1, the placement-practice series for people who finished the SyntaxPilot C course. Pattern printing is the most common first question in campus coding tests, because it checks one skill: can you control loops exactly, row by row and character by character.

Every question below is solved the same way as in the video: read the problem, think out loud (input, output, edge cases), write the obvious attempt, watch it fail for real, find out why, fix it, run every test case, and state the time and space complexity.

Every program was compiled with the SyntaxPilot compiler's C command with warnings switched on, gcc -Wall -O2 -Wno-unused-result main.c -o main -lm (gcc 13.3, Linux x86-64), and every output shown here is the real output.

The idea: a pattern is a cinema hall

In a cinema hall In a pattern program
Rows A, B, C, D, one after another The outer loop: one turn prints one line
Seats 1, 2, 3 in one row The inner loop: prints the characters of that line
The usher says "next row" printf("\n") after the inner loop

A loop inside another loop is a nested loop. Every pattern program has this shape:

for (int i = 1; i <= rows; i++) {        /* one turn per row      */
    for (int j = 1; j <= count(i); j++)  /* the columns of row i  */
        printf("*");
    printf("\n");                        /* next row               */
}

The 3-question plan for any pattern

  1. How many rows? That is the outer loop.
  2. In row i, how many spaces and how many symbols? A column is one character position in a line, so this asks how many columns of each kind.
  3. Which symbol? A star, the column number j, a counter, ...

Then write a small table of row number against each count and read the formula off the table. Never guess a formula: check it on the first and the last row.

Q1: Right-angle star triangle

Problem. Read an integer n. Print a right-angle triangle of stars with n rows: row i has i stars.

Example. Input 4:

*
**
***
****

Think out loud

Row i Stars
1 1
2 2
3 3
i i
  • Outer loop: i from 1 to n. Inner loop: j from 1 to i, one star each.
  • Edge cases (inputs at the boundary, where programs usually break): n = 1 must print one star; n = 0 must print nothing.

The obvious attempt

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j < i; j++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}

Input 4:


*
**
***

No error and no warning, but the answer is wrong: the first line is empty and the last line has three stars instead of four.

Why it failed: the off-by-one error

A fence 4 metres long with a post every metre needs 5 posts, not 4: you must count both ends. Being wrong by exactly one like this is an off-by-one error, the most common loop bug.

for (int j = 1; j < i; j++) starts at 1 and stops before i, so it runs i - 1 times. Row 1 gets 0 stars, row 4 gets 3. Check the first and the last turn of a loop:

Loop Values of j when i = 4 Turns
j = 1; j < i 1, 2, 3 3 (one short)
j = 1; j <= i 1, 2, 3, 4 4
j = 0; j < i 0, 1, 2, 3 4

The fix

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}

All the test cases:

Input 4:

*
**
***
****

Input 1:

*

Input 0:

(no output)

Input -3:

(no output)

For n = 0 (and any negative n) the outer condition 1 <= n is false from the start, so the body never runs and nothing is printed, which is the right answer.

Complexity

  • Stars printed: 1 + 2 + ... + n = n(n+1)/2.
  • Time complexity describes how the work grows when the input grows. Here it grows like n², written O(n²): double n and you print about four times as many stars.
  • Space complexity describes the extra memory the program needs. We keep only n, i and j, whatever n is: O(1), constant space.

Q2: Number pyramid

Problem. Read n (1 to 9) and print a centred pyramid of numbers. Row i counts up from 1 to i and back down to 1.

Example. Input 4:

   1
  121
 12321
1234321

Think out loud: the plan table (n = 4)

Row i Spaces Rising Falling Width
1 3 1 (none) 1
2 2 12 1 3
3 1 123 21 5
4 0 1234 321 7

So each row is three small loops:

  1. spaces: n - i
  2. rising numbers: j from 1 to i
  3. falling numbers: j from i - 1 down to 1

The digits in row i take 2i - 1 columns. Edge cases: n = 1, n = 9 (the largest allowed), and n = 10 or n = 0, which break the rules: print a clear message instead of a broken shape.

The obvious attempt

#include <stdio.h>

int main() {
    int n, k;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        for (int s = 1; s <= n - i; s++) printf(" ");
        for (int j = 1; j <= i; j++) printf("%d", j);
        printf("\n");
    }
    return 0;
}

The compiler message (we compile with -Wall):

main.c: In function ‘main’:
main.c:4:12: warning: unused variable ‘k’ [-Wunused-variable]
    4 |     int n, k;
      |            ^

Input 4:

   1
  12
 123
1234

Two problems:

  1. A warning is a message from the compiler about code that is legal but probably a mistake; the program still compiles and runs. unused variable 'k' means some code is left over. -Wall switches on the common warnings; always compile with it.
  2. The output is a staircase, not a pyramid: only parts 1 and 2 of the plan were written. Each row must be 2i - 1 digits wide, and the staircase stops at i.

The fix

Delete k, reject inputs outside 1 to 9, and add part 3, the falling numbers:

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    if (n < 1 || n > 9) {
        printf("n must be 1 to 9\n");
        return 0;
    }
    for (int i = 1; i <= n; i++) {
        for (int s = 1; s <= n - i; s++) printf(" ");
        for (int j = 1; j <= i; j++) printf("%d", j);
        for (int j = i - 1; j >= 1; j--) printf("%d", j);
        printf("\n");
    }
    return 0;
}

All the test cases:

Input 4:

   1
  121
 12321
1234321

Input 1:

1

Input 9:

        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321

Input 10:

n must be 1 to 9

Input 0:

n must be 1 to 9

Why reject 10? Ten has two digits, so the columns would no longer line up. Always respect the constraints (the limits on the input) in the problem statement.

Complexity

Row i prints (n - i) spaces and 2i - 1 digits, n + i - 1 characters. Over all rows this is about 1.5 n² characters: O(n²) time, O(1) space.

Q3: Inverted pyramid

Problem. Read n and print an upside-down pyramid of stars: 2n - 1 stars on top, two fewer on each row, shifted one space right each time, one star at the bottom.

Example. Input 4:

*******
 *****
  ***
   *

Think out loud: rows counted from 0

Row i Spaces Stars
0 0 7
1 1 5
2 2 3
3 3 1

Spaces in row i: i. Stars: 7 = 2n - 1 at the top, two fewer per row. Edge cases: n = 1 prints one star, n = 0 prints nothing.

The obvious attempt (a guessed formula)

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        for (int s = 0; s < i; s++) printf(" ");
        for (int j = 0; j < 2 * (n - i) + 1; j++) printf("*");
        printf("\n");
    }
    return 0;
}

Input 4:

*********
 *******
  *****
   ***

Nine, seven, five, three: every row has two stars too many, and there is no single star at the bottom.

Why it failed: find the formula, don't guess it

The count drops by 2 each row, so stars = a - 2i for some start a. Row 0 needs 2n - 1 stars, so a = 2n - 1:

stars = 2n - 1 - 2i = 2 * (n - i) - 1

Check the ends: row 0 gives 2n - 1; the last row, i = n - 1, gives 2 * 1 - 1 = 1. The guess 2 * (n - i) + 1 gives 2n + 1 on top and 3 at the bottom.

The fix

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        for (int s = 0; s < i; s++) printf(" ");
        for (int j = 0; j < 2 * (n - i) - 1; j++) printf("*");
        printf("\n");
    }
    return 0;
}

All the test cases:

Input 4:

*******
 *****
  ***
   *

Input 1:

*

Input 0:

(no output)

Complexity: n rows, at most 2n - 1 stars plus n - 1 spaces each: O(n²) time, O(1) space.

Complexity summary

Question Characters printed Time Extra space
Q1 star triangle n(n+1)/2 O(n²) O(1)
Q2 number pyramid about 1.5 n² O(n²) O(1)
Q3 inverted pyramid about 1.5 n² O(n²) O(1)

A pattern program can't be faster than O(n²) when it has to print about n² characters: printing them is the work.

Common mistakes (and the real messages)

Mistake What you see Why Fix
for (int j = 1; j < i; j++) no error: an empty first row, one star short the loop runs i - 1 times j <= i, or j = 0; j < i
int n, k; with k never used warning: unused variable 'k' [-Wunused-variable] leftover code delete it; compile with -Wall
only spaces and 1..i in a pyramid row no error: a staircase the falling part is missing add j = i - 1 down to 1
2 * (n - i) + 1 stars no error: 9, 7, 5, 3 a guessed formula 2 * (n - i) - 1, checked on both ends
printf("\n") inside the inner loop no error: one star per line the new line belongs to the row, not the column put it after the inner loop
printing spaces after the last star looks right, but some judges compare exactly trailing spaces print spaces only before the symbols

Three of these give no message at all. That is why you test n = 1, n = 0 and the limits every time.

Your turn: hollow square (solution)

Problem. Read n and print an n × n square of stars with only the border filled.

Idea. In row i, column j, print a star when i or j is the first (1) or the last (n); otherwise print a space.

Show the solution
#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (i == 1 || i == n || j == 1 || j == n) printf("*");
            else printf(" ");
        }
        printf("\n");
    }
    return 0;
}

Input 4:

****
*  *
*  *
****

Input 1:

*

Input 2:

**
**

Time O(n²), space O(1). For n = 1 and n = 2 every cell is on the border, so the square is full.

Practice questions (with solutions)

1. A right-angle triangle of numbers: 1, 12, 123, 1234.

Solution
#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) printf("%d", j);
        printf("\n");
    }
    return 0;
}

Input 4:

1
12
123
1234

2. An inverted number pyramid (Q2 upside down).

Solution

The same three parts, with the outer loop counting down.

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    if (n < 1 || n > 9) {
        printf("n must be 1 to 9\n");
        return 0;
    }
    for (int i = n; i >= 1; i--) {
        for (int s = 1; s <= n - i; s++) printf(" ");
        for (int j = 1; j <= i; j++) printf("%d", j);
        for (int j = i - 1; j >= 1; j--) printf("%d", j);
        printf("\n");
    }
    return 0;
}

Input 4:

1234321
 12321
  121
   1

3. Rewrite Q1 with i and j starting at 0.

Solution

Row i (0-based) has i + 1 stars, so the inner loop is j = 0; j <= i.

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= i; j++) printf("*");
        printf("\n");
    }
    return 0;
}

Input 3:

*
**
***

Quick quiz

for (int i = 0; i <= 3; i++)
    for (int j = 0; j < i; j++)
        printf("*");

How many stars are printed? (A) 6 (B) 10 (C) 9 (D) 4

Answer

(A) 6. i takes four values, 0, 1, 2, 3, and row i prints i stars: 0 + 1 + 2 + 3 = 6.

Interview questions

  1. How do you approach any pattern question? Count the rows (outer loop), then for row i write the number of spaces and symbols in a table, find the formula, and check it on the first and last row.
  2. What is an off-by-one error? Give an example. A loop that runs one time too many or too few, like j < i where j <= i was needed.
  3. What is the time complexity of printing an n-row pyramid? O(n²), because it prints about n² characters.
  4. What does -Wall do? It turns on gcc's common warnings, such as unused variables and wrong printf formats. A warning doesn't stop compilation, but usually points at a real bug.
  5. Why does the number pyramid limit n to 9? Numbers from 10 have two digits, so the columns stop lining up. Respect the constraints the problem gives.

Glossary

Term Meaning Example
Pattern question A problem that asks you to print a shape with characters a pyramid of stars
Row One line of output; one turn of the outer loop ****
Column One character position in a line the 3rd character
Nested loop A loop inside another loop for i { for j { } }
Outer loop The loop that walks over the rows for (int i = 1; i <= n; i++)
Inner loop The loop that prints the characters of one row for (int j = 1; j <= i; j++)
Edge case An input at the boundary, where programs usually break n = 0, n = 1
Off-by-one error A loop that runs one time too many or too few j < i instead of j <= i
Test case One input with the output it must produce input 4 → 4 rows
Constraint A limit on the input given by the problem 1 <= n <= 9
Warning A compiler message about legal but suspicious code; the program still builds unused variable 'k'
-Wall The gcc option that turns on the common warnings gcc -Wall main.c
Time complexity How the amount of work grows as the input grows O(n²)
Space complexity How much extra memory the program needs as the input grows O(1)
Big O notation A way to write the growth rate, ignoring constants O(n²), O(1)
O(1) Constant: the same amount whatever the input three int variables
O(n²) Grows with the square of n: double n, four times the work a pyramid of n rows

Summary

  • Every pattern is rows (outer loop) and columns (inner loops), with printf("\n") after each row.
  • Plan with a table of row i against spaces and symbols; read the formula off it.
  • Check the first and the last turn of every loop: that is where off-by-one errors live.
  • A pyramid row is three parts: spaces, rising, falling.
  • Compile with -Wall and read the warnings.
  • Test n = 1, n = 0 and the limits.
  • Pattern programs are O(n²) time and O(1) space.

Next episode: Pattern printing II: a diamond, Floyd's triangle and Pascal's triangle (nCr without factorial overflow).