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
Set up the loop variable, write the condition, update inside the body.
Initialize every variable used in the condition before the loop.
Write while (condition) { ... } with a boolean expression.
Update those variables inside the body so the condition can become false.
Compile with gcc file.c -std=c11 -o out.
Piece
Required?
Role
Initialization
Yes (you write it)
Before while — starting values
Condition
Yes
Checked before each iteration
Update
Yes (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
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)
Trace
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.
Code
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;
}
Output
1
2
3
4
5
How It Works
Initialize.i = 1 before the loop so the first check has a value.
Test.i <= 5 is checked; if true, the body runs.
Body. Print i, then i++ so the next check can fail.
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;
}
Output (sample run)
Enter a number (0 to exit): 7
You entered: 7
Enter a number (0 to exit): 3
You entered: 3
Enter a number (0 to exit): 0
Exited the loop.
How It Works
Prime the pump. Read once before while so the pre-test has a real value.
Loop while not sentinel. Process the number only when it is not 0.
Read again inside. The next input updates number for the next test.
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;
}
Always-true condition.while (1) never stops on its own.
Show a menu. Prompt and read choice each pass.
Exit path. Choice 0 (or bad input) calls break.
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.
Analysis
Performance Notes
Approach
Cost
Best for
while / for (same work)
Same asymptotic cost
Pick the clearer form
Tight body, few branches
Very cheap per iteration
Counting, scanning arrays
I/O or scanf each pass
Dominated by I/O
Interactive / 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.
Remember
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.