Course contentsShow
← C
Lesson 321 of 1,2194. Control FlowFree lesson

Choosing the right loop for the task

Choosing the right loop for the task

What you'll learn: How to select the most readable and efficient loop structure based on whether you know the iteration count in advance.

C gives you three main tools for repetition: for, while, and do-while. While you can technically use any loop to solve any problem, choosing the "wrong" one makes your code harder to read, like using a screwdriver to hammer in a nail.

The Counter: The for loop

Use a for loop when you know exactly how many times you need to repeat an action before the loop even starts. It’s perfect for counting. Think of it like a track coach telling an athlete to run exactly 10 laps. The initialization, condition, and increment are all tucked neatly into one line, keeping your code tidy.

The Condition: The while loop

Use a while loop when you don’t know the number of iterations in advance, but you know the condition that must stay true. This is like a security guard who stays at their post as long as the building is open. If the building is already closed when they arrive, they never start their shift (the loop may run zero times).

The "At Least Once": The do-while loop

This is the rarest loop. Use it when the code must execute at least once before the condition is checked. Think of it like a vending machine: you enter your selection first, and then the machine checks if you have enough credit.

Choosing in Practice

#include <stdio.h>

int main() {
    // 1. Use 'for' when counting is the priority
    printf("Counting to 3:\n");
    for (int i = 1; i <= 3; i++) {
        printf("%d\n", i);
    }

    // 2. Use 'while' when waiting for a specific event
    int energy = 2;
    while (energy > 0) {
        printf("Working... energy left: %d\n", energy);
        energy--;
    }

    // 3. Use 'do-while' for tasks that must happen at least once
    int choice;
    do {
        printf("Press 0 to exit: ");
        // Imagine user input happens here
        choice = 0; 
    } while (choice != 0);

    return 0;
}

Key takeaway

Use for for counting, while for waiting, and do-while when the action must happen at least once.