Loops are used to perform a task over and over until a specific condition is met. C provides three core structures for iteration, each suited for slightly different scenarios.
1. The while Loop
The while loop is the simplest and most fundamental loop. It tests the condition before executing the loop body. If the condition is initially false, the loop body is never executed.
Syntax:
while (condition) {
// Loop body: Code that executes repeatedly
// Must include a statement to eventually make the condition false
}
Example
int count = 1;
while (count <= 5) {
printf("Count: %d\n", count);
count++; // Increment the counter
}
// Output: 1, 2, 3, 4, 5
2. The do-while Loop
The do-while loop is similar to the while loop, but it guarantees that the loop body executes at least once before the condition is checked.
Syntax:
do {
// Loop body: Code executes at least once
} while (condition); // Note the semicolon here
Example
This is often used for user input when you need to run the input prompt once, regardless of the condition.
int num;
do {
printf("Enter a positive number: ");
scanf("%d", &num);
} while (num <= 0);
// The loop runs once, then checks if the number is positive.
3. The for Loop
The for loop is ideal for situations where you know exactly how many times you need to loop (e.g., iterating over an array or a fixed range). It consolidates the initialization, condition check, and iteration steps into a single line.
Syntax:
for (initialization; condition; update) {
// Loop body
}
Example
int i;
for (i = 0; i < 3; i++) {
printf("Iteration: %d\n", i);
}
// Output: 0, 1, 2
4. Choosing the Right Loop
| Loop Type | Best Used When… | Key Feature |
for | The number of iterations is known or easily determined beforehand (e.g., counting from 1 to 10). | Concise structure; loop control logic is centralized. |
while | The loop must continue indefinitely until an external condition is met (e.g., reading data until end-of-file). | Condition is checked first; may run zero times. |
do-while | You must execute the code at least once (e.g., getting guaranteed user input). | Loop body executes at least once. |
