C while Loop

Beginner
7 min read
Updated: Oct 2026
3 examples
Live preview

What Is a while Loop?

A while loop is a pre-test loop: C checks the condition before each pass. If it is false, the body is skipped (even on the first try). You initialize variables before the loop and update them inside so the condition can become false.

Remember
while (condition) {
    /* body */
}

/* init before  →  test → body → update → test again */

pre-test  → body may run 0 times
for       → known count / clear counter
do-while  → body runs at least once
UsePrefer
Unknown count / input-drivenwhile (this page)
Clear start, stop, stepfor loop
Run body at least oncedo-while

How to Use while in C

Set up the loop variable, write the condition, update inside the body.

  1. Initialize every variable used in the condition before the loop.
  2. Write while (condition) { ... } with a boolean expression.
  3. Update those variables inside the body so the condition can become false.
  4. Compile with gcc file.c -std=c11 -o out.
PieceRequired?Role
InitializationYes (you write it)Before while — starting values
ConditionYesChecked before each iteration
UpdateYes (you write it)Inside body — moves toward exit

Pseudocode

Pseudocode
initialize variables used in the condition

while condition is true:
    do the work
    update variables   // so condition can become false

continue after the loop

Cheat Sheet

Keep these patterns handy while writing loops.

TopicDetail
Syntaxwhile (cond) { ... }
KindPre-test (0+ iterations)
Counti = 1; while (i <= n) { ...; i++; }
Sentinelwhile (num != 0) { ... }
Forever + exitwhile (1) { if (done) break; }
Early exitbreak / continue
vs forUse while when count is unknown

Live Preview

Simulate a counting while in the browser. Same idea as the C examples below (compile those with gcc).

Browser simulation of a while loop (same idea as the C examples below).

Result
i = 1
while (i <= 5) {
  print i; i++
}
→ 1 2 3 4 5
(5 iterations)

Worked Walkthrough — Count 1 to 3

Trace a tiny counting loop step by step. This is the same pattern as Example 1 below.

Trace
i = 1

check i <= 3?  true  → print 1, i becomes 2
check i <= 3?  true  → print 2, i becomes 3
check i <= 3?  true  → print 3, i becomes 4
check i <= 3?  false → stop

Output: 1 2 3
If i started at 4, the body would never run.

C Examples

Compile every example with gcc file.c -std=c11 -o out. See also for and do-while.

Example 1 — Print Numbers 1 to 5

A counting loop with init before while and update inside. Same idea as for (i = 1; i <= 5; i++).

C
#include <stdio.h>

int main(void) {
    int i = 1;

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

    return 0;
}

How It Works

  1. Initialize. i = 1 before the loop so the first check has a value.
  2. Test. i <= 5 is checked; if true, the body runs.
  3. Body. Print i, then i++ so the next check can fail.
  4. Stop. When i becomes 6, the condition is false and control continues after the loop.

Example 2 — Read Until User Enters 0

Classic sentinel loop: keep going until a special exit value. Check scanf so bad input does not spin forever.

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

  1. Prime the pump. Read once before while so the pre-test has a real value.
  2. Loop while not sentinel. Process the number only when it is not 0.
  3. Read again inside. The next input updates number for the next test.
  4. Exit cleanly. Entering 0 fails the condition; bad scanf uses break.

Example 3 — Menu with while (1) and break

An infinite loop with a deliberate exit. See break for early exit details.

C
#include <stdio.h>

int main(void) {
    int choice;

    while (1) {
        printf("\n1) Hello\n0) Quit\nChoice: ");
        if (scanf("%d", &choice) != 1) {
            break;
        }
        if (choice == 0) {
            break;
        }
        if (choice == 1) {
            printf("Hello!\n");
        } else {
            printf("Unknown option.\n");
        }
    }

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

How It Works

  1. Always-true condition. while (1) never stops on its own.
  2. Show a menu. Prompt and read choice each pass.
  3. Exit path. Choice 0 (or bad input) calls break.
  4. After the loop. Goodbye. prints once you leave the loop.

Edge Cases & Pitfalls

Check these before shipping loop-heavy code.

update

Forgot the update

Missing i++ (or equivalent) keeps the condition true forever. Always change what the condition depends on.

init

Uninitialized condition variable

Using i before assigning it is undefined behavior. Initialize before while.

assign

= instead of ==

while (x = 1) assigns and is always true. Use == for comparison (or while (x != 0)).

empty

Empty body by mistake

while (i < n); with a trailing semicolon is an empty loop—often infinite if i never changes.

Performance Notes

ApproachCostBest for
while / for (same work)Same asymptotic costPick the clearer form
Tight body, few branchesVery cheap per iterationCounting, scanning arrays
I/O or scanf each passDominated by I/OInteractive / file loops

Compilers treat equivalent for and while loops similarly. Prefer clarity. Infinite loops without an exit waste CPU—always provide break or a failing condition.

Key Takeaways

  • Pre-test: condition first—body may run zero times.
  • Your job: init before, update inside.
  • When: unknown count, input, or event-driven exit.
  • Safety: every while (1) needs a clear break path.

One line: while checks first—initialize before, update inside, stop when the condition fails.

Frequently Asked Questions

A while loop repeats a block while 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 initialize before the loop and update inside the body. Prefer while when the stop point depends on runtime input or an unknown count.
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 until you exit with break, return, or exit. Common for menus. Always provide a clear exit path.
Usually the condition never becomes false—you forgot to update a variable inside the body (e.g. missing i++), or you compare the wrong value. Trace every variable used in the condition.
Yes. A typical pattern reads input, processes it, then reads again until a sentinel (like 0). Check the scanf return value to handle bad input or EOF.

Next: do-while Loop

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

do-while 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.

9 people found this page helpful