Unlocking the Mystery of the do-while Loop
๐ 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:
do
โ Do something once, no matter what.-
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