Home Tutorials C Tutorial Loop Comparison
Loop Comparison

Loop Comparison


Comparison: for vs while vs do...while

Choosing the right loop depends on two main factors: How many times the code needs to run and when the condition should be checked.

Feature for Loop while Loop do...while Loop
Control Type Entry-Controlled Entry-Controlled Exit-Controlled
Condition Check At the beginning At the beginning At the end
Minimum Runs 0 (May never run) 0 (May never run) 1 (Always runs once)
Best Used When... Number of iterations is fixed/known. Number of iterations is unknown/dynamic. The code must execute at least once (e.g. menus).

Which loop should I use?

The "Fixed" Scenario

If you need to print the first 100 even numbers, use a for loop. It keeps all the counter logic in one line.

The "Waiting" Scenario

If you are waiting for a user to type "QUIT" or a file to finish loading, use a while loop.

The "Action" Scenario

If you want to display a game menu and then ask the player if they want to play again, use a do...while loop.

Visualizing Loop Logic

🛡️ Entry-Controlled (for, while)

The "Security Guard" Analogy: Imagine a guard at a club gate. He checks your "ticket" (the condition) before you enter. If your ticket is invalid (False), you never get inside the club.

🍴 Exit-Controlled (do...while)

The "Restaurant" Analogy: You enter, sit down, and "eat" (execute code) first. You only check the "bill" (the condition) after you are finished. Even if you can't pay, you've already eaten once!

Choosing the Right Loop

Scenario A: The "10-Day Countdown"

Since you know exactly how many times the loop will run (10), the for loop is the cleanest and most readable choice.

for (int i = 10; i > 0; i--) {
    printf("%d...", i);
}

Scenario B: Waiting for a Sensor (100°C)

You don't know if this will take 5 seconds or 50 minutes. Since the condition depends on external data, the while loop is best.

while (temperature < 100) {
    check_sensor(); 
}

Scenario C: The "Play Again" Prompt

You want the user to play the game at least once before asking if they want to repeat. The do...while loop is the perfect fit.

do {
    play_game();
    printf("Press 1 to play again: ");
    scanf("%d", &choice);
} while (choice == 1);

💡 Key Takeaway for Students

If you know the count? Use for
Don't know the count? Use while
Must run at least once? Use do...while

🏋️ Test Yourself With Exercises

Take our quiz on Loop Comparison to test your knowledge.

Browse Quizzes »