๐Ÿ”“ Understanding the do-while Loop

You already know about for and while loops. But what about the do-while loop? Itโ€™s a cool oneโ€”and a bit different.


๐Ÿง  Think of It Like This:

โ€œDo this thing first, then keep doing it while the condition is true.โ€


๐Ÿงฉ How It Works:

  1. do โ€” Do something once, no matter what.
  2. while (condition) โ€” Check the condition after doing it.

    • If itโ€™s true, repeat.
    • If itโ€™s false, stop.

๐ŸŽฎ Example: Number Guessing Game

Imagine a friend is guessing a number between 1 and 10. They must guess at least once, right?

int guess;

do {
    printf("Guess a number between 1 and 10: ");
    scanf("%d", &guess);
} while (guess != secretNumber);

printf("You got it!\n");

๐Ÿ’ก Even if the first guess is correct, the loop still runs once before checking.


โšก Why Use do-while?

Use it when you want the code to run at least once, even if the condition is false right away. Thatโ€™s the key difference from while and for.


๐Ÿ“ Quick Quiz

Q1: What makes the do-while loop different from the while loop?

(a) It always runs the code block at least once (b) while loops always run once (c) do-while is only for counting (d) while is only for conditions


Q2: Which loop would you use if you want a user to enter a character until they type 'q'?

(a) for โ€” best for fixed repeats (b) while โ€” only checks first (c) do-while โ€” ensures at least one prompt (d) None of the above


<
Previous Post
๐Ÿ† Celebrating Excellence: Meet the Programming Whiz Kids of Clasam Schools!
>
Next Post
๐Ÿ” Understanding Loops in C: The for Loop Made Simple