while Loop in C
The while loop runs as long as a condition is true. Best used when you do NOT know in advance how many times to repeat.
c
#include <stdio.h>
int main() {
// ── Basic while loop ──────────────────────────
int i = 1;
printf("while loop: ");
while (i <= 5) {
printf("%d ", i);
i++; // MUST update or infinite loop!
}
printf("\n");
// ── do-while: runs at LEAST once ──────────────
int n;
printf("\nEnter number to check (0 to stop):\n");
do {
scanf("%d", &n);
if (n != 0) {
if (n % 2 == 0) printf("%d is EVEN\n", n);
else printf("%d is ODD\n", n);
}
} while (n != 0);
printf("Program ended.\n");
return 0;
}▶ Output
while loop: 1 2 3 4 5 Enter number to check (0 to stop): 4 4 is EVEN 7 7 is ODD 0 Program ended.
while vs do-while vs for
| Loop | Condition checked | Minimum runs | Best for |
|---|---|---|---|
| for | Before body | 0 (may not run) | Known number of iterations |
| while | Before body | 0 (may not run) | Unknown iterations, check first |
| do-while | After body | 1 (runs at least once) | Input validation, menu programs |
Real Example: Digit Sum Calculator
c
int num, sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
while (num > 0) {
sum += num % 10; // add last digit
num /= 10; // remove last digit
}
printf("Digit sum = %d\n", sum);▶ Output
Enter a number: 1234 Digit sum = 10
⚠ Warning: Infinite loop disaster: if you forget to update the counter (
i++), the loop runs forever! Press Ctrl+C to stop an infinite loop in terminal.