Run Once with do while
Run once, then check
Sometimes a program must record what just happened before deciding whether to repeat. An ordinary while checks its condition first and might skip the body. A do ... while checks afterward, so its body runs at least once.
#include <stdio.h>
int main(void) {
int attempt = 3;
do {
printf("Attempt %d\n", attempt);
attempt++;
} while (attempt < 3);
printf("No more attempts\n");
return 0;
}
Here attempt starts at 3. The body records Attempt 3 and increases the number to 4. Only then does the program test attempt < 3. The test is false, so it prints No more attempts. A pre-tested while (attempt < 3) would have skipped the attempt entirely.
The trailing while (attempt < 3); needs its semicolon. That is different from a while header before a body. Run the code and check for exactly two lines. If you start at 1 instead, the body prints attempts 1 and 2 before the condition stops the loop.
The next lesson uses nested loops to label positions on a shelf grid.