C While Loop
A while loop repeats a block of C code as long as a condition is true. It is the right tool when you do not know in advance exactly how many times the loop should run: keep reading values until a sentinel appears, keep asking for valid input, or keep processing while work remains. Understanding while loops is essential because many real programs are driven by conditions, not fixed counts.
Overview: How It Works
A while loop is a pre-test loop. Before each possible repetition, C evaluates the condition inside while (...). If the condition compares equal to zero, it is false and the loop body is skipped. If the condition is nonzero, it is true and the body runs once. After the body finishes, execution jumps back to the condition and tests again.
This means a while loop may run zero times. If the condition is false the first time it is checked, C never enters the body. That behavior is useful when there may be no items to process, but it can surprise beginners who expected the body to run at least once. If a loop must run once before testing, C has a separate do...while loop, covered separately.
The condition is any scalar expression, most commonly a comparison such as count < 5, value != 0, or scanf("%d", &n) == 1. C uses its normal truth rule: zero is false, and any nonzero value is true. Comparisons produce 0 or 1, but ordinary integers also work. For clarity, write the condition so it reads like a question.
Internally, a while loop does not create special storage. Variables used by the condition live wherever they were declared, usually on the stack when they are local variables. Each iteration reads the current values of those variables. If the body changes a variable used by the condition, the next test sees the changed value. If the body never makes the condition false, the loop is infinite unless a statement such as break, return, or program termination stops it.
A while loop is often compared with a for loop. Use for when initialization, condition, and update form one clear counting pattern. Use while when the stopping condition is the main idea and the update may happen in different places, such as after reading input or after finding a match.
Syntax
while (condition) {
statements;
}
| Part | Meaning |
|---|---|
while |
The keyword that starts a pre-test repetition statement. |
condition |
An expression tested before each iteration. Zero stops the loop; nonzero continues it. |
{ statements; } |
The loop body. These statements run once for each true condition test. |
| Update | Usually a statement inside the body that changes something involved in the condition. |
Braces are not required for a one-statement body, but they are strongly recommended. They prevent mistakes when a second statement is added later and make the loop boundary obvious.
Examples
Example 1: Counting With a While Loop
#include <stdio.h>
int main(void)
{
int count = 1;
while (count <= 5) {
printf("Count: %d\n", count);
count++;
}
printf("Done\n");
return 0;
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done
The variable count starts at 1. The condition count <= 5 is true for values 1 through 5. The body prints the current value, then count++ increases it. When count becomes 6, the next test is false and execution continues after the loop.
Example 2: Processing Until a Sentinel Value
#include <stdio.h>
int main(void)
{
int values[] = {8, 12, 5, 0, 99};
int index = 0;
int total = 0;
while (values[index] != 0) {
total += values[index];
index++;
}
printf("Values used: %d\n", index);
printf("Total: %d\n", total);
return 0;
}
Output:
Values used: 3
Total: 25
Here 0 is a sentinel value: it marks the end of meaningful data. The loop adds 8, 12, and 5, then stops when it reaches 0. The value 99 is never processed because it appears after the sentinel. This pattern is common with input streams, arrays that use a marker value, and protocols that have an explicit end command.
Example 3: Repeating Until Input Is Valid
#include <stdio.h>
int main(void)
{
int attempts[] = {-3, 0, 7};
int index = 0;
int number = attempts[index];
while (number <= 0) {
printf("Rejected: %d\n", number);
index++;
number = attempts[index];
}
printf("Accepted: %d\n", number);
return 0;
}
Output:
Rejected: -3
Rejected: 0
Accepted: 7
This example simulates repeated input attempts using an array so the program compiles and produces fixed output. The loop keeps rejecting numbers while number <= 0. When number becomes 7, the condition is false and the program prints the accepted value. With real user input, the same idea is used to keep asking until the input satisfies the program’s rules.
Example 4: Searching While Work Remains
#include <stdio.h>
int main(void)
{
int numbers[] = {4, 9, 15, 22, 31};
int length = 5;
int target = 22;
int index = 0;
while (index < length && numbers[index] != target) {
index++;
}
if (index < length) {
printf("Found %d at index %d\n", target, index);
} else {
printf("Not found\n");
}
return 0;
}
Output:
Found 22 at index 3
The loop has two conditions joined with &&: there must still be elements left, and the current element must not be the target. C evaluates && from left to right and stops early when the left side is false, so numbers[index] is not read after index reaches length. That order prevents an out-of-bounds array access.
How It Works Step by Step
- Execution reaches the
whilestatement. - C evaluates the condition using the current variable values.
- If the condition is zero, C skips the body and continues after the loop.
- If the condition is nonzero, C enters the body and runs its statements in order.
- When the closing brace is reached, control jumps back to the condition.
- The condition is evaluated again, so any changes made in the body can affect whether the loop continues.
For the counting example, the test sequence is 1 <= 5, 2 <= 5, 3 <= 5, 4 <= 5, 5 <= 5, then 6 <= 5. Only the first five tests enter the body. The sixth test ends the loop.
Common Mistakes
Forgetting to Update the Condition
If nothing in the loop changes the condition, the loop may never end. For example, a counting loop that prints count but never increments it will keep printing the same value. The corrected version updates count inside the body:
#include <stdio.h>
int main(void)
{
int count = 1;
while (count <= 3) {
printf("%d\n", count);
count++;
}
return 0;
}
Output:
1
2
3
Accidentally Adding a Semicolon After the Condition
A semicolon immediately after while (condition) creates an empty loop body. The block that follows is no longer controlled by the loop. This can cause an infinite loop or make the following block run only once after the loop ends. Write while (condition) { ... }, with no semicolon before the opening brace.
Using = Instead of ==
The expression while (running = 1) assigns 1 to running, and the assignment expression itself has value 1. That condition is always true. Use == for comparison, or write clearer boolean-style conditions such as while (running) when running is already meant to be a truth value.
Reading Past the End of an Array
When looping over an array, always test the index before using it. In a combined condition, put the bounds check first: index < length && numbers[index] != target. Reversing the order can read invalid memory when index equals length.
Best Practices
- Use
whilewhen the loop is controlled by a condition rather than a simple fixed count. - Initialize every variable used by the condition before the loop starts.
- Make sure each normal path through the body can move the loop toward termination.
- Use braces around the loop body, even when it contains only one statement.
- Keep the condition readable. If it becomes too complex, compute part of it in a well-named variable.
- For array loops, check bounds before reading the element at the current index.
- Use
breakfor exceptional early exits, but prefer a clear loop condition for the normal stopping rule. - Avoid modifying the same condition variable in several hidden places; it makes loop behavior hard to reason about.
Practice Exercises
- Write a program that starts at
10and uses awhileloop to print a countdown to1. - Create an integer array ending with sentinel value
-1. Use awhileloop to count how many positive values appear before the sentinel. - Write a loop that searches an array for the first even number. Print the index if one is found, or
No even numberotherwise.
Summary
- A
whileloop repeats while its condition is nonzero. - The condition is checked before every iteration, so the body can run zero times.
- Variables in the condition must be initialized before the loop and updated when needed inside the body.
- Infinite loops usually happen because the condition never becomes false or because of an accidental assignment or semicolon.
whileis best for sentinel loops, validation loops, searches, and other condition-controlled repetition.- When indexing arrays, combine a bounds check with the loop condition and place the bounds check first.
