C course menu
while and do-while Loops in C with Examples
Learn the C while loop and do-while loop: syntax, loops that repeat until a condition changes, digit processing, input validation with do-while, reading until end of input with getchar and EOF, and the difference between while and do-while.
On this page
Use while when you do not know in advance how many repetitions you need: repeat while a condition holds. do-while is the same, except it always runs the body at least once.
while#
int savings = 1000, months = 0;
while (savings < 2000) {
savings = savings * 110 / 100; /* grows 10% a month, in whole rupees */
months++;
}
printf("%d months, savings %d\n", months, savings);8 months, savings 2142The condition is checked before each repetition, so if it is false at the start, the body never runs.
Working with digits#
Taking digits off a number with % 10 and / 10 is a classic while loop:
int n = 12345, reversed = 0, digit_sum = 0;
while (n > 0) {
int digit = n % 10;
reversed = reversed * 10 + digit;
digit_sum += digit;
n /= 10;
}
printf("%d %d\n", reversed, digit_sum);54321 15do-while#
do-while checks the condition after the body, so the body runs at least once. It suits input that must be repeated until it is valid:
#include <stdio.h>
int main(void) {
int age;
do {
printf("Enter your age (0-110): ");
if (scanf("%d", &age) != 1) return 1;
} while (age < 0 || age > 110);
printf("Thank you, age %d recorded\n", age);
return 0;
}Enter your age (0-110): -5
Enter your age (0-110): 120
Enter your age (0-110): 42
Thank you, age 42 recordedNote the semicolon after while (...) at the end of a do-while.
Reading until the end of input#
getchar() returns the next character, or the special value EOF when there is no more input. Its result must be stored in an int, not a char, so that EOF can be told apart from real characters:
#include <stdio.h>
#include <ctype.h>
int main(void) {
int c, letters = 0, others = 0;
while ((c = getchar()) != EOF) {
if (isalpha(c)) letters++;
else if (c != '\n') others++;
}
printf("letters: %d, other characters: %d\n", letters, others);
return 0;
}Hello C
letters: 6, other characters: 1When typing at the keyboard, end the input with Ctrl+D (Linux and macOS) or Ctrl+Z then Enter (Windows).
while or for?#
These two loops are equivalent; choose the one that reads more naturally:
int i = 0;
while (i < 3) {
printf("%d ", i);
i++;
}
for (int j = 0; j < 3; j++) {
printf("%d ", j);
}
printf("\n");0 1 2 0 1 2 Counting loops read better as for; "until something happens" loops read better as while.
Practice#
Practice exercise
Using a while loop, find how many times you must halve 1000 (with integer division) before it reaches 1, and print each value along the way.
Show solution
#include <stdio.h>
int main(void) {
int n = 1000, steps = 0;
while (n > 1) {
n /= 2;
steps++;
printf("%d ", n);
}
printf("\n%d steps\n", steps);
return 0;
}500 250 125 62 31 15 7 3 1
9 stepsKey takeaway#
Finished this lesson?