Loops: while, do-while & for
Computers are good at doing the same thing many times without getting bored. A loop repeats a block of code while a condition stays true: add up 60 students' marks, print a multiplication table, keep asking until the input is valid.
C has three loops: while, do-while and for. In this lesson you will learn all three, control them with break and continue, put loops inside loops, and avoid the bugs that make loops run once too often or never stop.
The while loop
A while loop checks its condition before each round. If the condition is true, the body runs, and then the condition is checked again. Each round is called an iteration.
#include <stdio.h>
int main(void)
{
int number = 4721;
int sum = 0;
while (number > 0) {
sum += number % 10; // add the last digit
number /= 10; // remove the last digit
}
printf("Sum of digits: %d\n", sum);
return 0;
}Sum of digits: 14
number % 10 is the last digit and number / 10 removes it. Tracing the loop by hand shows exactly what happens:
| Iteration | Digit added | sum | number after |
|---|---|---|---|
| 1 | 1 | 1 | 472 |
| 2 | 2 | 3 | 47 |
| 3 | 7 | 10 | 4 |
| 4 | 4 | 14 | 0 |
When number reaches 0, the condition is false and the loop ends. Something inside the body must eventually make the condition false; otherwise the loop runs forever.
The do-while loop
A do-while loop checks its condition after each round, so the body always runs at least once. Notice the semicolon after the closing while (...).
#include <stdio.h>
int main(void)
{
int n = 0;
int count_while = 0;
int temp = n;
while (temp != 0) {
count_while++;
temp /= 10;
}
int count_do = 0;
temp = n;
do {
count_do++;
temp /= 10;
} while (temp != 0);
printf("while loop says %d has %d digits\n", n, count_while);
printf("do-while says %d has %d digits\n", n, count_do);
return 0;
}while loop says 0 has 0 digits do-while says 0 has 1 digits
Both loops count digits correctly for numbers like 4721, but only the do-while version is right for 0, which has one digit. Use do-while when the body must run once before you can test anything, such as showing a menu and then asking whether to show it again.
The for loop
A for loop puts the three parts of a counting loop on one line: the initialisation, the condition and the update.
#include <stdio.h>
int main(void)
{
for (int i = 1; i <= 10; i++) {
printf("7 x %2d = %2d\n", i, 7 * i);
}
return 0;
}7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
The steps run in this order: int i = 1 once at the start; then the condition i <= 10 is checked; if true, the body runs; then the update i++ runs; then the condition is checked again, and so on. The variable i is declared inside the for, so it exists only inside the loop. The %2d keeps the columns lined up.
To loop over something with n items, the usual C pattern starts at 0 and uses <: for (int i = 0; i < n; i++). You will use this form with arrays all the time.
break and continue
break leaves the loop immediately. continue skips the rest of the current iteration and moves on to the next one (in a for loop, the update still runs).
#include <stdio.h>
int main(void)
{
for (int roll = 1; roll <= 20; roll++) {
if (roll % 3 == 0) {
continue; // these roll numbers sit in another room
}
if (roll > 8) {
break; // this room has seats only up to roll 8
}
printf("Roll %d: room A\n", roll);
}
return 0;
}Roll 1: room A Roll 2: room A Roll 4: room A Roll 5: room A Roll 7: room A Roll 8: room A
Rolls 3 and 6 are skipped by continue. Roll 9 is also skipped, and at roll 10 the break ends the loop, even though the condition roll <= 20 is still true.
Loops that run until something happens
Sometimes you do not know in advance how many rounds you need. A common pattern is an "infinite" loop, while (true) or for (;;), with a break inside:
#include <stdio.h>
int main(void)
{
int balance = 1000;
int day = 0;
while (true) {
day++;
balance -= 150; // Farhan spends Rs 150 a day
if (balance < 150) {
break; // not enough for another day
}
}
printf("Money runs low on day %d, Rs %d left\n", day, balance);
return 0;
}Money runs low on day 6, Rs 100 left
After six days of spending Rs 150, Rs 100 remains, which is less than one more day's spending, so the loop stops.
Nested loops
A loop inside another loop is a nested loop. For every single iteration of the outer loop, the inner loop runs completely.
#include <stdio.h>
int main(void)
{
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= row; col++) {
printf("*");
}
printf("\n");
}
return 0;
}* ** *** ****
In row 1 the inner loop prints one star, in row 2 two stars, and so on. A break inside the inner loop leaves only the inner loop, not both.
Which loop should you use?
| Situation | Loop |
|---|---|
| You know how many times to repeat, or you count through items | for |
| You repeat while a condition holds, and it may be false at the start | while |
| The body must run at least once | do-while |
| You stop in the middle when something happens | while (true) with break |
C also has a goto statement that jumps to a label. It is legal, but it makes code hard to follow, so avoid it in everyday code.
Common mistakes
- Off-by-one errors.
for (int i = 0; i <= n; i++)runsn + 1times. Count the rounds by hand for a smalln. - A semicolon after the loop header.
for (int i = 0; i < 5; i++);has an empty body; the block below runs only once, afterwards. - Forgetting the update. A
whileloop that never changes its variable runs forever. PressCtrl+Cin the terminal to stop it. - Counting down with
unsigned.for (unsigned i = 5; i >= 0; i--)never ends, because an unsigned value is never negative. - Using
doubleas a loop counter. Adding 0.1 ten times may not give exactly 1.0. Count with integers and calculate the decimal value inside the loop.
Key points
whilechecks the condition before each iteration; the body may run zero times.do-whilechecks after each iteration, so the body runs at least once; it ends withwhile (...);.for (init; condition; update)is best for counting; declare the counter inside it.breakleaves the nearest loop;continuejumps to the next iteration.- In nested loops, the inner loop runs completely for each outer iteration.
- Trace loops by hand with a small table to catch off-by-one and infinite-loop bugs.
Exercise
Isha saves Rs 500 in her first month and Rs 100 more each month than the month before (Rs 600, then Rs 700 and so on). Write a program that uses a loop to find how many months she needs to save at least Rs 10,000, and prints the number of months and the total saved.
Show solution
#include <stdio.h>
int main(void)
{
int target = 10000;
int saving = 500;
int total = 0;
int months = 0;
while (total < target) {
total += saving;
saving += 100;
months++;
}
printf("Months needed: %d\n", months);
printf("Total saved: Rs %d\n", total);
return 0;
}Months needed: 11 Total saved: Rs 11000
After 10 months she has Rs 9,500, which is still short; the 11th month adds Rs 1,500, giving Rs 11,000. A while loop fits because the number of months is not known in advance.
Quick Quiz
1. How many times does for (int i = 0; i < 5; i++) run its body?
i takes the values 0, 1, 2, 3 and 4, which is five iterations.
2. What is special about a do-while loop?
The condition is checked after the body, so the first iteration always happens.
3. What does continue do inside a for loop?
continue jumps to the next iteration; break is the statement that leaves the loop.
4. Why does for (unsigned i = 3; i >= 0; i--) never stop?
When i is 0 and decreases, it wraps around to a huge positive value instead of becoming -1.
Learn C with a mentor
Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
