Thuta Learning
C
BasicProgrammingBeginner

While Loop

CLesson 1320 min

What you'll walk away with

  • Write a while loop with a clear initialisation, condition and progress step
  • Predict how many times a while loop runs, including zero times
  • Choose do...while when the body must run at least once
  • Recognise and fix infinite loops caused by a missing update or a stray semicolon

Explain it simply

Explain it simply

Think of a while loop as a guard at a gate who asks the same question every time you arrive. If the answer is true, the guard lets the body run and then you come back to the gate to be asked again. The moment the answer is false, the program walks past the loop and carries on with the next line.

Reach for while when you cannot say in advance how many passes you need: halve a number until it reaches 1, read until a file ends, retry until a connection works. The data itself, not a fixed count, decides when to stop.

Problem → Why → Solution

The problem: a program that never finishes

The classic while-loop bug is a program that never finishes. Nothing crashes and no error is printed; the terminal keeps scrolling the same line, or sits silent until you press Ctrl+C. In the first loop below, the counter is printed but never changed, so i < 5 stays true forever. The second loop has a stray semicolon after the condition, which makes the loop body an empty statement; the braces underneath would only run after the loop ends, and it never does.

stuck.c
#include <stdio.h>

int main(void) {
    int i = 0;
    while (i < 5) {
        printf("%d\n", i);      /* prints 0 forever: i never changes */
    }

    int j = 0;
    while (j < 5);              /* this ; IS the loop body */
    {
        j++;                    /* never reached */
    }
    return 0;
}

Why does it never stop?

A while loop stops only when its condition becomes false, and C never changes the condition for you. If nothing in the body moves the loop variable toward the exit, the same test keeps giving the same answer. Both loops are valid C, so the compiler accepts them. In a layout like this one, GCC with -Wall can flag the stray semicolon with a -Wmisleading-indentation warning ("this 'while' clause does not guard..."), one more reason to always compile with warnings on.

Core concept: initialise, test, progress

Every while loop that ends correctly has three parts, even though only one of them sits inside the parentheses. Initialisation happens before the loop: int i = 0; gives the condition something to test. The condition is tested before each pass, including the very first one. Progress happens inside the body: i++, n /= 10 or reading the next item changes a value the condition depends on. Forget any one of the three and the loop either never starts, never stops, or works on garbage.

Because the test comes first, a while loop can run zero times. If i starts at 10, while (i < 5) skips the body completely and execution continues after the closing brace. That is usually exactly what you want: an empty file needs no processing, and a number that is already 1 needs no steps.

In C the condition can be any scalar expression, and only zero counts as false. while (n) is shorthand for while (n != 0), and while (1) is a loop with no built-in exit at all, which you leave with break (covered in the Break/Continue lesson) or return. A pointer condition works the same way: while (p) runs until p becomes a null pointer, a pattern you will meet in linked lists.

Choose while over for when the number of passes depends on the data. The digit counter in the example does not know in advance whether the number has one digit or nine; it simply divides by 10 until nothing is left. When you do know the count, such as "print 5 rows", the for loop in the next lesson keeps all three parts on one line and reads better.

text
One pass of while (i < 5)
-------------------------
        +------------------+
        | int i = 0;       |   initialise (runs once)
        +--------+---------+
                 |
                 v
        +------------------+   false
   +--->|     i < 5 ?      |---------> first statement after the loop
   |    +--------+---------+
   |             | true
   |             v
   |    +------------------+
   |    | printf(...)      |   body
   |    | i++;             |   progress
   |    +--------+---------+
   |             |
   +-------------+
Mental model: ask, act, move, ask again
  1. Set the loop variable once
  2. Test the condition before each pass
  3. Run the body, then make progress
  4. False test: jump past the loop

If nothing in the body can change the condition's answer, the loop cannot end.

General pattern

c
initialise;
while (condition) {
    statements;
    update;             /* move toward condition == false */
}

do {
    statements;
} while (condition);    /* body always runs at least once */

while tests the condition before running the body; do...while runs the body first and tests afterwards. A do...while needs a semicolon after its closing parenthesis, while a plain while must not have one there.

Example: a counter and a digit counter

The first loop is a plain counter from 0 to 4 that prints one number per line. The second shows where while really shines: the value 40210 itself decides how many passes happen, one pass per digit.

while_loop.c
#include <stdio.h>

int main(void) {
    int i = 0;                  /* 1. start value */

    while (i < 5) {             /* 2. tested before every pass */
        printf("%d\n", i);
        i++;                    /* 3. progress toward i < 5 being false */
    }

    int n = 40210;
    int digits = 0;

    while (n > 0) {             /* how many passes? the data decides */
        n /= 10;                /* drop the last digit */
        digits++;
    }
    printf("40210 has %d digits\n", digits);
    return 0;
}

Code breakdown

  1. Initialiseint i = 0; /* 1. start value */

    i gets the value 0 before the loop starts. Without this line i would hold an indeterminate value and nobody could predict how many passes run.

  2. Testwhile (i < 5) { /* 2. tested before every pass */

    The condition is checked before each pass. After the fifth pass i is 5, 5 < 5 is false and the loop stops, which is why 5 itself is never printed.

  3. Progressi++; /* 3. progress toward i < 5 being false */

    This is the only line that moves i toward 5. Delete it and the program prints 0 forever.

  4. Data-driven conditionwhile (n > 0) { /* how many passes? the data decides */

    Nothing in the code says "five passes". The loop keeps going while n still has digits left and stops when n reaches 0.

  5. Integer division as progressn /= 10; /* drop the last digit */

    Integer division throws away the fraction, so n goes 40210, 4021, 402, 40, 4, 0. The trailing zero is counted too, because the loop only divides and never looks at the digit's value.

You should see
0
1
2
3
4
40210 has 5 digits

do...while: run first, test afterwards

The digit counter in the example hides an edge case. Run it with n = 0 and 0 > 0 is false immediately, so it would claim "0 has 0 digits", yet the number 0 is written with one digit. A do...while loop runs its body before the first test, which fits these "at least once" situations exactly.

do_while.c
#include <stdio.h>

int main(void) {
    int n = 0;
    int digits = 0;

    do {
        n /= 10;
        digits++;
    } while (n > 0);            /* tested AFTER the body */

    printf("0 has %d digit\n", digits);
    return 0;
}

You will see do...while in menus, which must be shown at least once, and in "try once, retry on failure" code. When there is a case where running the body would be wrong, such as an empty list, stick with a plain while.

Loops that read until the input runs out

Loops that read from the keyboard or a file need two exits. One is a sentinel, an agreed value such as 0 or "quit" that means "I am done". The other is end-of-file (EOF), when the input stream itself runs out. scanf() returns the number of items it successfully read, or EOF when input has ended, so testing that return value directly in the loop condition is the habit to build. The User Input lesson covers reading input in detail.

sum_until_zero.c
#include <stdio.h>

int main(void) {
    int value;
    int total = 0;

    /* stops on the sentinel 0, on EOF, and on input that is not a number */
    while (scanf("%d", &value) == 1 && value != 0) {
        total += value;
    }
    printf("total: %d\n", total);
    return 0;
}

In real projects

Where this shows up in real projects

Loops whose length depends on the data appear in almost every C program: reading a file until fgetc() returns EOF, walking a linked list with while (node != NULL), a server waiting for the next request with while (running) until a shutdown signal flips the flag, a game redrawing the screen sixty times a second inside while (!quit).

In production code, every loop that waits on the outside world (network, hardware, a user) gets a second exit: a maximum attempt count such as attempts < max_attempts, a timeout, or an error check. That way an unplugged cable cannot freeze the program forever. Microcontroller firmware is the exception that proves the rule: the while (1) inside its main() is deliberate, because the device should run until the power goes off, so there the endless loop is the design rather than a bug.

Common mistakes

Common mistakes

1. Forgetting the update, or hiding it inside an if

A missing i++, or one that lives inside a branch such as if (i % 2 == 0) { i++; }, traps the loop as soon as an odd value appears. After writing any loop, ask yourself: which line changes the condition's variable, and is that line reached on every pass?

2. A semicolon after while (...)

while (i < 5); ends the loop statement right there and repeats an empty body. The block in braces below is no longer part of the loop. Keeping the opening { on the same line as the condition makes this slip much easier to see.

3. Retrying input without consuming the bad characters

while (scanf("%d", &age) != 1) { printf("Try again\n"); } spins forever when the user types letters: scanf leaves the rejected characters in the input buffer, so the next call fails on exactly the same characters. When input ends, scanf returns EOF, which is also not 1, so the loop keeps going there too. Discard the rest of the bad line, and stop on EOF.

4. Using <= where you meant <

Starting from i = 0, while (i <= 5) runs six times, not five. Trace the last value of i on paper when the loop finishes; most counting mistakes show up that way.

Best practices

Best practices

  • Write the initialise, condition and progress parts before you write the body.
  • Give every loop that waits on input, the network or hardware a limit: an attempt count or a timeout.
  • Compile with gcc -Wall -Wextra, which can turn layout slips like a stray semicolon into warnings.
  • When the number of passes is known up front, prefer a for loop; keep while for loops whose end is decided by the data.

Mini challenge

Mini challenge: the 3n + 1 walk

Start from n = 7 and apply the 3n + 1 rule until n reaches 1: halve even numbers, turn odd numbers into 3n + 1. Print every value on one line and count the steps. Nobody can tell in advance how many steps a starting number needs, which makes this a perfect job for while.

  • Use a while loop whose condition is n != 1
  • Inside the body, use if/else to apply the even rule or the odd rule
  • Print every value on one line separated by spaces, starting with 7
  • Count each step and print the total after the loop
collatz.c
#include <stdio.h>

int main(void) {
    int n = 7;
    // TODO: declare a step counter

    printf("%d", n);
    // TODO: loop while n is not 1
    //   even n -> n / 2, odd n -> 3 * n + 1
    //   print " %d" for the new value and count the step

    // TODO: print "Reached 1 after <steps> steps"
    return 0;
}

Expected: The program prints these two lines: 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 Reached 1 after 16 steps

Show hint

n % 2 == 0 tests for an even number. Print the starting value before the loop and each new value inside it, so the loop only prints what it has just computed.

Show solution
collatz.c
#include <stdio.h>

int main(void) {
    int n = 7;
    int steps = 0;

    printf("%d", n);
    while (n != 1) {
        if (n % 2 == 0) {
            n = n / 2;
        } else {
            n = 3 * n + 1;
        }
        printf(" %d", n);
        steps++;
    }
    printf("\nReached 1 after %d steps\n", steps);
    return 0;
}

Quick quiz 1 / 3

What does this print? int n = 10; while (n > 0) { n -= 3; } printf("%d", n);

Quick quiz 2 / 3

int i = 0; while (i < 3); { printf("%d", i); i++; } — what happens?

Quick quiz 3 / 3

int k = 10; while (k < 5) { k++; } — how many times does the body run?

What to remember

  • A while loop tests its condition before every pass, so it can run zero times.
  • A correct loop needs all three parts: initialise, test and progress; without progress it never ends.
  • do...while runs the body first and tests afterwards, which suits work that must happen at least once.
  • Loops that wait on input need exits for the sentinel, for EOF and for invalid input.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.