Skip to content

Module 3 · Decisions and Loops — topic 4 of 5

Nested Loops

A loop inside another loop handles two-dimensional work: tables, grids, patterns and pairwise comparisons. Learn how the iterations multiply and how to trace them.

Beginner 14 min read·Lesson 14 of 37 in C Programming

Learning objectives

  • Trace the execution order of nested loops
  • Print number and star patterns
  • Estimate how the number of iterations grows (n × m)

Definition

A nested loop is an iteration statement whose body contains another iteration statement; for each iteration of the outer loop, the inner loop runs through all of its iterations.

Introduction

Some problems have two dimensions: rows and columns of a table, every pair of students, every pixel in an image. A loop inside a loop handles them naturally — the outer loop picks a row, the inner loop walks across it.

The key fact: the inner loop restarts from the beginning on every iteration of the outer loop. With an outer loop of 4 and an inner loop of 3, the inner body runs 12 times.

Why it matters

Pattern-printing questions (triangles, pyramids, number grids) are a fixture of C lab exams because they test precise loop control.

Nested loops are also the starting point for algorithm analysis: two nested loops over n items mean about n² operations, which matters when n is a million.

Detailed explanation

Use different counter names (i for rows, j for columns). Reusing the same variable in both loops is a common and confusing bug.

For patterns, ask two questions per row: how many characters to print, and what each character is. The inner loop's limit often depends on the outer counter (e.g. row i prints i stars).

To print a new line after each row, put printf("\n") after the inner loop but still inside the outer loop.

break inside the inner loop exits only the inner loop. To leave both, use a flag variable checked by the outer loop, or move the loops into a function and return.

Row iSpaces (n − i)Stars (2i − 1)
131
223
315
407

Syntax

C
for (int i = 1; i <= rows; i++) { /* outer: once per row */
for (int j = 1; j <= cols; j++) { /* inner: once per column */
/* work for cell (i, j) */
}
printf("\n"); /* end of row */
}
  • The inner loop completes fully for each outer iteration.
  • Total inner iterations = rows × cols when the limits are fixed.
  • The inner limit may depend on i for triangular shapes.

Code examples

Right-angled triangle

C
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++)
printf("*");
printf("\n");
}
return 0;
}
Output
*
**
***
****

Multiplication grid

C
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 4; j++)
printf("%4d", i * j);
printf("\n");
}
return 0;
}
Output
   1   2   3   4
   2   4   6   8
   3   6   9  12

More examples

Pyramid and prime search

C
#include <stdio.h>
int main(void) {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int s = 0; s < n - i; s++) printf(" ");
for (int k = 0; k < 2 * i - 1; k++) printf("*");
printf("\n");
}
printf("Primes below 30:");
for (int x = 2; x < 30; x++) {
int prime = 1;
for (int d = 2; d * d <= x; d++) {
if (x % d == 0) { prime = 0; break; }
}
if (prime) printf(" %d", x);
}
printf("\n");
return 0;
}
Output
   *
  ***
 *****
*******
Primes below 30: 2 3 5 7 11 13 17 19 23 29

Step-by-step explanation

  • For row i, the first inner loop prints n - i spaces to centre the row.
  • The second inner loop prints 2i − 1 stars: 1, 3, 5, 7.
  • printf("\n") after both inner loops ends the row.
  • In the prime search, the inner loop tries divisors only up to √x (d * d <= x).
  • break stops the inner loop at the first divisor; the outer loop continues with the next x.

Expected output

Running “Pyramid and prime search” prints exactly:

TextOutput
*
***
*****
*******
Primes below 30: 2 3 5 7 11 13 17 19 23 29

Practical applications

  • Image filters loop over every row and column of pixels.
  • Matrix multiplication in scientific code is three nested loops.
  • Timetable generators check every pair of classes for clashes.

Best practices

  • Name counters by meaning (row, col) in larger programs.
  • Work out the formula for spaces and symbols per row on paper first.
  • Be aware that nested loops over large inputs grow quadratically.

Common mistakes

Reusing the outer counter

Avoid

for (i = 0; i < 3; i++)
for (i = 0; i < 3; i++)
printf("x");

Prefer

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

The inner loop leaves i at 3, so the outer loop ends after one row — or loops forever with other limits.

Newline inside the inner loop

Avoid

for (int i = 1; i <= 3; i++)
for (int j = 1; j <= i; j++) {
printf("*");
printf("\n");
}

Prefer

for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++)
printf("*");
printf("\n");
}

Every star ends up on its own line. The newline belongs after the inner loop.

Important notes

  • break and continue affect only the innermost loop that contains them.
  • Checking divisors up to √x is a standard optimisation: a composite number always has a divisor no larger than its square root.

Key takeaways

  • The inner loop runs completely for every iteration of the outer loop.
  • Patterns: decide count and character per row; newline after the inner loop.
  • Nested loops over n items do about n² work.

Try it yourself

  1. 1
    Print Floyd's triangle for 5 rows (1 / 2 3 / 4 5 6 / …).
  2. 2
    Print an inverted pyramid of stars for n read from input.
  3. 3
    Find all pairs (a, b) with 1 ≤ a < b ≤ 20 whose sum is 21.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • ModerateTwo nested loops each run n times. Roughly how many times does the inner body run?
Practise this topic