C while Loop

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
Pre-test loop

What You’ll Learn

The while loop repeats code while a condition stays true. Unlike for, you manage the setup and update yourself—ideal when you do not know how many iterations you need upfront, such as reading user input until they quit.

01

Syntax

while (cond).

02

Pre-test

Check first.

03

Counting

Update inside.

04

Input

Until exit.

05

while(1)

Menu loops.

06

Nested

Inner/outer.

Definition and Usage

A while loop is a pre-test loop: C evaluates the condition before each iteration. If the condition is false, the body is skipped entirely—even on the first pass. When true, the body runs, then control returns to the condition check.

Use while when repetition depends on something that changes during the program—user typing numbers, reading characters until end-of-file, or waiting for a flag. Use for when counting with a clear start, stop, and step fits naturally in one line.

💡
Beginner Tip

Every while loop needs two things outside the header: initialize variables before the loop, and update them inside the body so the condition can eventually become false.

📝 Syntax

General form of the C while loop:

C
while (condition) {
    // statements to repeat
}

Equivalent counting pattern

This while loop does the same work as for (int i = 1; i <= 5; i++):

C
int i = 1;              /* initialization before loop */
while (i <= 5) {        /* condition */
    printf("%d\n", i);
    i++;                /* update inside body */
}

Compile

C
gcc program.c -std=c11 -o program

⚡ Quick Reference

PatternExample
Basic whilewhile (i <= n) { ... i++; }
Sentinel inputwhile (num != 0) { ... scanf ... }
Infinite + breakwhile (1) { if (done) break; }
Exit loop earlybreak; inside body
Skip iterationcontinue; inside body
Pre-test
check, then run

while

Init
before while

You write it

Update
inside body

You write it

vs for
unknown count

Prefer while

Examples Gallery

Compile with gcc example.c -std=c11 -o example. Each program shows a different while loop pattern.

📚 Getting Started

Initialize a variable, test the condition, update inside the body.

Example 1 — Print Numbers 1 to 5

A counting loop written with while instead of for.

C
#include <stdio.h>

int main(void) {
    int i = 1;

    while (i <= 5) {
        printf("%d\n", i);
        i++;
    }

    return 0;
}

How It Works

i starts at 1. Each pass prints i and increments it. When i becomes 6, i <= 5 is false and the loop ends.

Example 2 — Count Down to Blastoff

Decrement until the condition fails—a natural while pattern.

C
#include <stdio.h>

int main(void) {
    int n = 5;

    while (n > 0) {
        printf("%d...\n", n);
        n--;
    }

    printf("Blastoff!\n");
    return 0;
}

How It Works

The loop runs while n > 0. Each iteration prints and decrements. Code after the loop runs once the condition is false.

📈 Practical Patterns

Input-driven loops, nesting, and controlled exit.

Example 3 — Read Until User Enters 0

Repeat while input is not the sentinel exit value.

C
#include <stdio.h>

int main(void) {
    int number;

    printf("Enter a number (0 to exit): ");
    if (scanf("%d", &number) != 1) {
        return 1;
    }

    while (number != 0) {
        printf("You entered: %d\n", number);
        printf("Enter a number (0 to exit): ");
        if (scanf("%d", &number) != 1) {
            break;
        }
    }

    printf("Exited the loop.\n");
    return 0;
}

How It Works

Read once before the loop (pre-test), then read again at the bottom of each iteration. This is the classic pattern when you do not know how many numbers the user will type.

Example 4 — Nested while Loops

Outer and inner loops each maintain their own counter.

C
#include <stdio.h>

int main(void) {
    int i = 1;

    while (i <= 3) {
        int j = 1;

        while (j <= 2) {
            printf("i = %d, j = %d\n", i, j);
            j++;
        }

        i++;
    }

    return 0;
}

How It Works

For each i, the inner loop runs j from 1 to 2. Total iterations: 3 × 2 = 6. Reset j = 1 at the start of each outer pass.

Example 5 — Menu Loop with break

while (1) runs forever until break exits on choice 0.

C
#include <stdio.h>

int main(void) {
    int choice;

    while (1) {
        printf("\n1) Say hello\n2) Double a number\n0) Quit\nChoice: ");
        if (scanf("%d", &choice) != 1) {
            break;
        }

        if (choice == 0) {
            break;
        } else if (choice == 1) {
            printf("Hello!\n");
        } else if (choice == 2) {
            int x;
            printf("Enter number: ");
            if (scanf("%d", &x) == 1) {
                printf("Double = %d\n", x * 2);
            }
        } else {
            printf("Unknown option.\n");
        }
    }

    printf("Goodbye.\n");
    return 0;
}

How It Works

while (1) keeps the menu alive. break provides a clean exit when the user chooses 0. This is safer than a truly infinite loop with no exit path.

🚀 Common Use Cases

  • User input — repeat until valid data or a quit command.
  • File readingwhile ((c = getchar()) != EOF) style loops.
  • Game loops — update and render until the player quits.
  • Waiting — poll a condition until hardware or network is ready.
  • Parsing — consume tokens while more data remains.
  • Menuswhile (1) with break on exit option.

🧠 How the while Loop Works

1

Initialize

Set variables before while (you do this manually).

Setup
2

Test condition

If false, jump past the loop entirely.

Pre-test
3

Run body

Execute statements; update loop variables here.

Repeat
=

Loop back

Return to step 2 until condition is false.

📝 Notes

  • If the condition starts false, the body never runs—unlike do-while.
  • Always update variables that affect the condition inside the loop.
  • while (1) is intentional infinity; pair it with break or return.
  • Check scanf return value when input errors or EOF should stop the loop.
  • continue skips to the next condition test; break leaves the loop.
  • Any non-zero value is true in C; only 0 is false.

⚡ Optimization

Hoist invariant work out of the loop—do not recompute values that never change on each iteration. For tight numeric loops, a for header can be clearer to the compiler and reader than an equivalent while. For I/O-bound loops (reading input or files), performance is dominated by I/O, not the loop form you choose.

Conclusion

The C while loop is your tool for repetition when the stop condition depends on runtime behavior. Initialize before the loop, update inside, and make sure the condition can become false.

Compare with the for loop for counted work, then learn do-while when the body must run at least once.

💡 Best Practices

✅ Do

  • Initialize loop variables before while
  • Update condition variables inside the body
  • Use break to exit while (1) menus
  • Keep conditions readable and boolean in intent
  • Check scanf / fgets return values

❌ Don’t

  • Forget to change variables the condition depends on
  • Use while (1) without any exit path
  • Put semicolon after while (cond); by mistake
  • Nest so deeply that logic becomes hard to follow
  • Use while when for expresses the count clearly

Key Takeaways

Knowledge Unlocked

Five things to remember about the C while loop

Pre-test repetition for unknown iteration counts.

5
Core concepts
🔢 02

Init + update

Your job.

Syntax
03

Input loops

Until sentinel.

Pattern
🔄 04

while(1)

+ break.

Menus
05

Infinite bug

Missing update.

Pitfall

❓ Frequently Asked Questions

A while loop repeats a block of code as long as a condition is true. Syntax: while (condition) { ... }. The condition is checked before each iteration, so the body may run zero times if the condition starts false.
for bundles initialization, condition, and update in the header. while only has a condition—you declare and update variables separately. Use while when repetitions depend on runtime input or an unknown stop point (e.g. read until EOF).
The condition is tested before the body runs. If it is false on the first check, the body never executes. do-while is post-test: the body runs at least once. while is pre-test.
The condition 1 is always true, so the loop runs forever unless you break out with break, return, or exit. Common for menu loops and event-driven programs. Always include a clear exit path.
Usually the condition never becomes false because you forgot to update a variable inside the body (e.g. missing i++), or you compare the wrong value. Trace which variables the condition uses and ensure they change each iteration.
Yes. A typical pattern reads input, processes it, then reads again at the bottom of the loop until a sentinel value (like 0) is entered. Check scanf return value when you need to handle bad input or EOF.
Did you know?

Placing a semicolon right after while (condition); creates an empty loop body—the statements below look indented but run only once after the loop finishes (or forever if the condition never changes). This is one of C’s most common beginner bugs.

Continue to the do-while Loop

Learn the post-test loop that always runs its body at least once.

do-while loop tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful