C Loops: for, while, do-while – Complete Guide
Loops in C programming allow you to execute a block of code multiple times without writing it again and again. They are essential for automation and efficient coding.
In this guide, you will learn for loop, while loop, and do-while loop in C with simple explanations and examples.
What are Loops in C?
Loops are used to repeat a set of instructions until a condition is met.
Benefits:
- Reduce code repetition
- Save time
- Improve efficiency
for Loop in C
The for loop is used when you know how many times you want to run the loop.
Syntax
for (initialization; condition; increment/decrement) {
// code
}When to Use for Loop?
- Fixed number of iterations
- Counting tasks
Types of Loops in C
C provides three types of loops:
| Loop Type | Description |
|---|---|
| for loop | Used when number of iterations is known |
| while loop | Used when condition-based looping is needed |
| do-while | Executes at least once |
#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