Step 5 of 7
do-while
while and for check their condition before each pass. do ... while checks it after, so the body always runs at least once:
do {
body
} while (condition);
Note the semicolon after the closing parenthesis; forgetting it is a compile error.
This fits situations where you must do something before you can decide whether to repeat, such as asking for input and then checking it:
#include <stdio.h>
int main(void) {
int guess;
int tries = 0;
do {
scanf("%d", &guess);
tries++;
} while (guess != 42);
printf("got it in %d tries\n", tries);
return 0;
}
10 50 42 7
got it in 3 tries
With a plain while, you'd need to read once before the loop and again inside it, repeating code. do-while avoids that.
Validation loops
"Keep asking until the input is valid" is the classic use. The condition describes invalid input, so the loop repeats while the input is bad. Write the condition carefully: "less than 1 or greater than 5" is outside the range; "less than 1 and greater than 5" can never be true, so the loop would never repeat.
Your task
Read numbers until one is between 1 and 5 (inclusive). For every invalid number print invalid N. Then print chose N.
Challenge 2
Keep reading numbers and adding them up until the total is at least 100. Then print the total and how many numbers it took. Use a do { ... } while (...); loop. Input 40 30 50 prints:
total 120
numbers 3
Challenge 3
Read a number that is 0 or more and print how many digits it has. Divide by 10 until nothing is left, counting each division. A do-while makes 0 come out right (it has 1 digit) without a special case. Input 12345 prints 5.