C While and Do-While Loops
A loop repeats a block of code. Loops let a program count, add up many numbers or keep asking until the answer is right, without writing the same line again and again.
while
A while loop checks its condition before each round and repeats as long as it is true.
#include <stdio.h>
int main(void) {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
printf("\n");
return 0;
}1 2 3 4 5
Three things make a loop work: a variable is set before the loop (i = 1), the condition uses it (i <= 5), and the body changes it (i++). If the body never changes the condition, the loop never ends. In the editor, press Stop or Ctrl+C to stop such a program.
Reading until the user stops
while is natural when you do not know how many rounds there will be, for example reading numbers until the user types 0:
#include <stdio.h>
int main(void) {
int number, total = 0, count = 0;
printf("Type numbers, 0 to stop:\n");
scanf("%d", &number);
while (number != 0) {
total += number;
count++;
scanf("%d", &number);
}
printf("%d numbers, total %d\n", count, total);
return 0;
}4 10 7 0
Type numbers, 0 to stop: 3 numbers, total 21
do-while
A do-while loop checks its condition after each round, so the body always runs at least once. It suits menus and input that must be read before it can be checked. Note the semicolon after the condition.
#include <stdio.h>
int main(void) {
int guess;
do {
printf("Guess the number (1-5): ");
scanf("%d", &guess);
} while (guess != 3);
printf("Right!\n");
return 0;
}5 1 3
Guess the number (1-5): Guess the number (1-5): Guess the number (1-5): Right!
Counting down
#include <stdio.h>
int main(void) {
int n = 5;
while (n > 0) {
printf("%d... ", n);
n--;
}
printf("Lift off!\n");
return 0;
}5... 4... 3... 2... 1... Lift off!
Which loop should I use?
- for: when you know how many rounds, such as counting from 1 to 10 or visiting every element of an array (next topic).
- while: when you repeat until something happens, such as reading input until the user types 0.
- do-while: when the body must run at least once, such as showing a menu before the user chooses.
All three can do the same job; choosing the one that matches your intention makes the code easier to read.
Practice exercises
- Print the even numbers from 2 to 20 with a
whileloop. - Read numbers until the user types a negative one, then print the largest number read.
- Use
do-whileto ask for a password (a number) until the user types 1234. - Write a loop that never ends, run it, and stop it with the Stop button.