While Loop
The while loop in C is used to repeat a block of code as long as a condition is true. It is helpful when you don't know in advance how many times the loop should run.
Syntax
while (condition) {
// Code to be executed repeatedly
}
The loop continues executing the code block as long as the condition evaluates to true (non-zero). Once the condition becomes false (zero), the loop terminates and the program continues with the next statement after the loop.
How It Works
- Check condition: The condition is evaluated first
- Execute code: If condition is true, execute the code block
- Repeat: Go back to step 1
- Exit: If condition is false, exit the loop
Basic Example
Let's start with a simple example that prints numbers from 1 to 5:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++; // Don't forget to update the counter!
}
return 0;
}
Output: 1 2 3 4 5
Important Points
1. Initialize Before the Loop
Always initialize your loop variable before entering the while loop:
int count = 0; // Initialize first
while (count < 3) {
printf("Hello World!\n");
count++;
}
2. Update Inside the Loop
Make sure to modify the condition variable inside the loop to avoid infinite loops:
int num = 10;
while (num > 0) {
printf("%d ", num);
num--; // This ensures the loop will eventually end
}
3. Avoid Infinite Loops
An infinite loop occurs when the condition never becomes false:
// ⚠️ DANGER: Infinite loop!
int x = 1;
while (x > 0) {
printf("This will run forever!\n");
// x is never modified, so x > 0 is always true
}
Common Use Cases
Counting Down
int countdown = 5;
while (countdown > 0) {
printf("%d...\n", countdown);
countdown--;
}
printf("Done!\n");
Input Validation
int number;
printf("Enter a positive number: ");
scanf("%d", &number);
while (number <= 0) {
printf("Invalid! Please enter a positive number: ");
scanf("%d", &number);
}
printf("Thank you! You entered: %d\n", number);
Sum Calculation
int sum = 0;
int i = 1;
while (i <= 10) {
sum += i;
i++;
}
printf("Sum of numbers 1 to 10 is: %d\n", sum);
While vs Other Loops
| Feature | While Loop | For Loop |
|---|---|---|
| Best for | Unknown number of iterations | Known number of iterations |
| Initialization | Before loop | In loop header |
| Condition check | At the beginning | At the beginning |
| Update | Inside loop body | In loop header |
Tips for Success
- Always initialize your loop variables before the while statement
- Always update the condition variable inside the loop
- Test your condition carefully to ensure it will eventually become false
- Use meaningful variable names to make your code readable
- Add comments for complex loop logic
Remember: A while loop is like asking "Are we there yet?" on a road trip - it keeps checking until the answer changes from "No" to "Yes"!