Skip to content

Chapter 7 of 21

Loops

Repeat work safely with for, while, do-while, break, and continue.

24 minutes 10 quick checksBy Subha Prasad
Lesson 7 of 21Course navigation

Lesson content

Read, practise, then check your understanding

A loop repeats a block while a condition remains true. Every reliable loop answers: where do we start, when do we stop, what changes, and is the boundary valid? Choose the form that makes those answers easiest to see.

Count with a for loop

Use for when the number of iterations is known or controlled by a counter.

for (int i = 1; i <= 5; i++) {
    printf("Step %d\n", i);
}

The three expressions initialize i, test the stopping condition, and update i. This example prints five lines.

Any for clause may be empty. for (;;) is an intentional infinite loop that must exit through break, return, or another transfer. Avoid hiding unrelated side effects in the update expression.

Repeat with while

Use while when repetition depends on a changing state rather than a fixed count.

int balance = 100;

while (balance >= 30) {
    balance -= 30;
    printf("Remaining: %d\n", balance);
}

The condition is checked before each iteration, so a while loop can run zero times. Ensure something inside the loop eventually makes the condition false.

Run once with do...while

A do...while loop checks its condition after the body, so it always executes at least once.

int choice;

do {
    printf("Enter 0 to exit: ");
    scanf("%d", &choice);
} while (choice != 0);

This pattern works well for menus and input prompts.

Traverse arrays without overruns

Use size_t for object sizes and indexes. Derive the element count while the object is still an array:

int values[] = {4, 8, 15, 16, 23, 42};
size_t count = sizeof values / sizeof values[0];

for (size_t i = 0; i < count; ++i) {
    printf("values[%zu] = %d\n", i, values[i]);
}

Inside a function parameter an apparent array is adjusted to a pointer, so the caller must provide the length.

Control an iteration

break exits the nearest loop. continue skips the rest of the current iteration and begins the next one.

for (int n = 1; n <= 10; n++) {
    if (n % 2 != 0) continue;
    if (n > 8) break;
    printf("%d ", n);
}

This prints 2 4 6 8. Use these controls sparingly; a clear loop condition is often easier to understand.

Nested loops and complexity

Nested loops process matrices or pairs. Give counters meaningful names and estimate work: two loops each running n times usually perform O(n²) iterations.

for (size_t row = 0; row < rows; ++row) {
    for (size_t column = 0; column < columns; ++column) {
        matrix[row][column] = 0;
    }
}

Avoid common mistakes

  • Check whether you need < or <= at the boundary.
  • Update the loop state to avoid an accidental infinite loop.
  • Use braces even for a one-line body.
  • Give nested loop counters distinct names such as row and column.
  • Do not change a loop counter unexpectedly inside the body.
  • Ensure input-driven loops handle end-of-file and malformed input.

Knowledge check

Answer every question correctly to complete this chapter.

Which part of a for loop normally updates its counter?
Which loop always executes its body at least once?
When is a while condition checked?
What does break do inside the nearest loop?
What does continue do?
How many times does for (int i = 0; i < 4; ++i) run?
What does for (;;) represent?
Which type is normally appropriate for array indexes and counts?
Two nested loops each running n times usually perform how much work?
What is a common cause of an accidental infinite loop?

0 of 10 checks passed

Your progress is saved on this device.