Skip to content
CurriculumChapter 08 ยท Control Flow
BeginnerHigh focus~16 min

for, while & Nested Loops

Loops repeat work. The interesting part is whether the condition is checked before the body, and what happens when loops are nested.

In plain English

A loop is a treadmill. A for loop counts the steps, and a while loop runs until you say stop.

01

for loops and loop variants

A for loop groups initialization, condition, and update in one header. The loop runs while the condition is true. The update expression can be empty, and multiple expressions can be separated with commas. Keep the loop simple enough to trace by hand.

chapter-08.cC
for (int i = 0; i < 5; i++) {
    printf("%d ", i);
}

for (int i = 0, j = 10; i < j; i++, j--) {
    printf("%d %d\n", i, j);
}
02

while and nested loops

A while loop checks its condition before each iteration; use it when the number of iterations is not known in advance. A nested loop places one loop inside another. The inner loop completes for every iteration of the outer loop, so the total number of iterations is the product of the two counts.

chapter-08.cC
int n = 3;
while (n > 0) {
    printf("%d ", n--);
}

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
        printf("%d ", row * col);
    }
    printf("\n");
}

Key takeaways

  • for and while are top-tested loops.
  • The for header contains initialization, condition, and update.
  • Nested loops multiply their iteration counts.
  • while is useful when the iteration count is unknown.

Common pitfalls

  • Off-by-one errors in loop bounds.
  • Changing the loop variable inside the body.
  • Forgetting braces around a multi-statement loop body.

Key focus

  • Trace loops with a table of iteration number and variable values.
  • Expect nested-loop output questions with rows and columns.

Quick check

0 / 2 answered

1. How many times does for (int i = 0; i < 4; i++) run?

2. How many total iterations does a loop with 3 outer and 4 inner iterations perform?