Learn C · lesson 17 of 60 · about 8 minutes
while and do-while
Clean up the disk while space is short and there are temp files left: repeat code while a condition is true, and run a body at least once with do-while.
What you'll learn
- Write a while loop
- Write a do-while loop
- Avoid infinite loops
Cleaning up
The report can say the disk is nearly full, but it can't do anything about it yet. The machine keeps temp files it doesn't need, and deleting one frees 300 KiB. The report should keep deleting while space is short and there are files left, but nobody knows in advance how many that will take. That's the job of a while loop.
Check, then run
while (cond) { ... } checks the condition before every lap. Something in the body must eventually make it false. do { ... } while (cond); runs the body first, so it always runs at least once.
Counting down
#include <stdio.h>
int main(void) {
int fuel = 3;
while (fuel > 0) {
printf("Fuel: %d\n", fuel);
fuel--;
}
printf("Empty\n");
return 0;
}Output
Fuel: 3
Fuel: 2
Fuel: 1
EmptyStep through it: deleting temp files
#include <stdio.h>
int main(void) {
int free_kib = 1500;
int temp_files = 3;
while (free_kib < 2048 && temp_files > 0) {
temp_files--;
free_kib += 300;
printf("Free: %d KiB, temp files left: %d\n", free_kib, temp_files);
}
printf("Clean-up finished.\n");
return 0;
}Output
Free: 1800 KiB, temp files left: 2
Free: 2100 KiB, temp files left: 1
Clean-up finished.Ask until valid
#include <stdio.h>
int main(void) {
int n;
do {
printf("Pick 1-3: ");
scanf("%d", &n);
} while (n < 1 || n > 3);
printf("\nYou picked %d\n", n);
return 0;
}Output
Pick 1-3: Pick 1-3: Pick 1-3:
You picked 2while or do-while?
Use while when the body might not need to run at all: a disk with plenty of space shouldn't lose any files. Use do-while when the body has to run before there's anything to check, like asking a question before you can test the answer.
Tip
Check every way out of a loop. The clean-up loop ends when there's enough space or no temp files are left, and each lap moves at least one of them closer.
Now try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.