C Loops: for, while, do-while – Complete Guide
Loops in C are used to execute a block of code repeatedly as long as a given condition is true. C supports three primary types of loops:
forloop – when you know how many times to loopwhileloop – when you don’t know how many times to loopdo-whileloop – when the loop must run at least once
C for Loop
Syntax:
for (initialization; condition; update) {
// Code block to execute
}
Example:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Count: %d\n", i);
}
return 0;
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5C while Loop
Syntax:
while (condition) {
// Code block
}
Example:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("Count: %d\n", i);
i++;
}
return 0;
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5C do-while Loop
This loop always executes at least once, even if the condition is false on the first check.
Syntax:
do {
// Code block
} while (condition);
Example:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("Count: %d\n", i);
i++;
} while (i <= 5);
return 0;
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5Loop Comparison Table
| Loop Type | Condition Checked | Guaranteed One Execution | Best For |
|---|---|---|---|
for | Before loop | No | Known number of iterations |
while | Before loop | No | Unknown number, pre-condition |
do-while | After loop | Yes | At least one execution needed |
Best Practices
| Tip | Benefit |
|---|---|
| Avoid infinite loops | Use proper conditions |
Use break and continue wisely | Improve control and logic clarity |
| Comment complex loops | Improves code readability |
Common Mistakes
| Mistake | Explanation |
|---|---|
| Forgetting to update loop counter | Leads to infinite loop |
Using = instead of == | Assignment instead of comparison |
Skipping {} for multi-line loops | Only the first line is considered |
Real-Life Example: Sum of Numbers
#include <stdio.h>
int main() {
int sum = 0, i = 1;
while (i <= 100) {
sum += i;
i++;
}
printf("Sum = %d\n", sum);
return 0;
}
Output:
Sum = 5050