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.
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.
Syntax
- 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
ifor triangular shapes.
Code examples
Right-angled triangle
* ** *** ****
Multiplication grid
1 2 3 4 2 4 6 8 3 6 9 12
More examples
Pyramid and prime search
* *** ***** ******* Primes below 30: 2 3 5 7 11 13 17 19 23 29
Step-by-step explanation
- For row
i, the first inner loop printsn - ispaces to centre the row. - The second inner loop prints
2i − 1stars: 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). breakstops the inner loop at the first divisor; the outer loop continues with the nextx.
Expected output
Running “Pyramid and prime search” prints exactly:
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
Prefer
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
Prefer
Every star ends up on its own line. The newline belongs after the inner loop.
Important notes
breakandcontinueaffect 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
- 1Print Floyd's triangle for 5 rows (1 / 2 3 / 4 5 6 / …).
- 2Print an inverted pyramid of stars for n read from input.
- 3Find 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?