C While Loops
Reduce a remaining-work count with while and use do-while when one action must happen first.
How it works
A while loop tests before entering its body. A do-while loop tests after its body, guaranteeing one execution. Neither form guarantees progress automatically: the body must move its state toward a stopping condition or leave deliberately. When reading input, a sentinel is a special value that means stop; the input operation must also detect end of file and errors. This fixed countdown isolates loop control before the stream lessons add those separate failure conditions.
Run it locally
Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.
cc -std=c17 -Wall -Wextra -Wpedantic -Werror while-sentinel.c -o lessonOn Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.
Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.
Example
#include <stdio.h>
int main(void) {
int remaining = 3;
while (remaining > 0) {
printf("Remaining: %d\n", remaining);
--remaining;
}
int attempts = 0;
do {
++attempts;
} while (attempts < 1);
printf("Checks: %d\n", attempts);
return 0;
}
Expected result
Remaining: 3
Remaining: 2
Remaining: 1
Checks: 1
The decrement creates progress for the first loop. The second loop increments attempts before checking whether another iteration is needed. Its final semicolon is required syntax for do-while. An interactive retry loop should have a policy for cancellation and invalid input, rather than assuming that a user will eventually supply a valid line.
For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.