C while Loop
In this page:
What is a while Loop?
A while loop checks its condition before every iteration, including the very first one -- if the condition starts out false, the loop body never runs at all, unlike a do-while loop which always runs once regardless.
Example: What is a while Loop?
#include <stdio.h>
int main() {
int x = 10;
while (x < 5) {
printf("never runs");
}
printf("Loop skipped since condition was false");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Counting Up
Using a counter variable that increases each pass, a while loop can print an ascending sequence of numbers -- initializing the counter before the loop and incrementing it inside the body on each iteration.
Example: Counting Up
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Counting Down
By initializing a counter at a high value and decreasing it each iteration instead of increasing it, the same while structure counts downward -- useful for countdowns or processing a range in reverse.
Example: Counting Down
#include <stdio.h>
int main() {
int i = 5;
while (i >= 1) {
printf("%d ", i);
i--;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Sum of First N Numbers
Accumulating a running total inside a while loop -- adding the current counter value to a separate sum variable on each pass -- is the standard pattern for computing something like the sum of the first N integers.
Example: Sum of First N Numbers
#include <stdio.h>
int main() {
int i = 1, sum = 0;
while (i <= 5) {
sum += i;
i++;
}
printf("%d", sum);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Infinite Loop Prevention
If the loop's condition never becomes false -- typically because you forgot to update the variable it depends on -- the loop runs forever, freezing the program; always double check that every code path inside the loop moves the condition toward becoming false.
Example: Infinite Loop Prevention
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: