Comparison of Looping Statements in C: for, while, and do-while
1. General Explanation
For Loop
Used when the number of iterations is known. Syntax:
for(initialization; condition; update) {
// Loop body
}
While Loop
Runs as long as the condition is true, suitable for uncertain iteration counts.
while(condition) {
// Loop body
}
Do-While Loop
Executes at least once before checking the condition.
do {
// Loop body
} while(condition);
2. Comparison
Loop Type Execution Condition Use Case
For Condition checked before Known number of iterations
each iteration
While Condition checked before Unknown number of
each iteration iterations
Do-While Condition checked after At least one execution
execution required
Key Difference: `do-while` executes at least once, while `while` may not execute at all if the
condition is false initially.
3. Practical Examples
For Loop Example:
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
printf("%d ", i);
}
return 0;
}
While Loop Example:
#include <stdio.h>
int main() {
int i = 1;
while(i <= 5) {
printf("%d ", i);
i++;
}
return 0;
}
Do-While Loop Example:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d ", i);
i++;
} while(i <= 5);
return 0;
}