Loops: while, do-while & for

C · Lesson 12 of 32 7 min read Updated

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.

C
#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;
}
Output
Sum of digits: 14

number % 10 is the last digit and number / 10 removes it. Tracing the loop by hand shows exactly what happens:

IterationDigit addedsumnumber after
111472
22347
37104
44140

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 (...).

C
#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;
}
Output
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.

C
#include <stdio.h>

int main(void)
{
    for (int i = 1; i <= 10; i++) {
        printf("7 x %2d = %2d\n", i, 7 * i);
    }
    return 0;
}
Output
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).

C
#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;
}
Output
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:

C
#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;
}
Output
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.

C
#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;
}
Output
*
**
***
****

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?

SituationLoop
You know how many times to repeat, or you count through itemsfor
You repeat while a condition holds, and it may be false at the startwhile
The body must run at least oncedo-while
You stop in the middle when something happenswhile (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++) runs n + 1 times. Count the rounds by hand for a small n.
  • 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 while loop that never changes its variable runs forever. Press Ctrl+C in 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 double as 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

  • while checks the condition before each iteration; the body may run zero times.
  • do-while checks after each iteration, so the body runs at least once; it ends with while (...);.
  • for (init; condition; update) is best for counting; declare the counter inside it.
  • break leaves the nearest loop; continue jumps 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
C
#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;
}
Output
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?

2. What is special about a do-while loop?

3. What does continue do inside a for loop?

4. Why does for (unsigned i = 3; i >= 0; i--) never stop?

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