Loops in C
Loops in C are used to execute a block of code multiple times based on a condition.
"Loops are the backbone of automation in programming, reducing code redundancy and improving efficiency."
What Are Loops?
Loops allow us to execute a block of code multiple times until a certain condition is met. C supports three types of loops:
Types of Loops in C
| Loop Type | Description | Example |
|---|---|---|
for loop |
Executes a block of code a fixed number of times. | for (i = 1; i <= 5; i++) |
while loop |
Executes a block of code as long as the condition is true. | while (i <= 5) |
do-while loop |
Executes the code block at least once, then repeats while the condition is true. | do { ... } while (i <= 5); |
1. for Loop
The for loop is used when the number of iterations is known beforehand.
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
2. while Loop
The while loop is used when the number of iterations is not known in advance.
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("Iteration %d\n", i);
i++;
}
return 0;
}
3. do-while Loop
The do-while loop ensures that the code runs at least once before checking the condition.
#include <stdio.h>
int main() {
int i = 1;
do {
printf("Iteration %d\n", i);
i++;
} while (i <= 5);
return 0;
}
Loop Control Statements
Loop control statements alter the flow of a loop:
break: Terminates the loop immediately.continue: Skips the current iteration and moves to the next.
Example: Using break
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit loop when i equals 5
}
printf("Iteration %d\n", i);
}
return 0;
}
Example: Using continue
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip iteration when i equals 3
}
printf("Iteration %d\n", i);
}
return 0;
}
Comparison of Loops
| Feature | for Loop | while Loop | do-while Loop |
|---|---|---|---|
| Usage | When the number of iterations is known | When the number of iterations is unknown | When the loop must execute at least once |
| Condition Check | Before entering the loop | Before entering the loop | After executing the loop body |
| Guaranteed Execution | No | No | Yes |
Best Practices for Using Loops
- Use
forloops when the number of iterations is known. - Use
whileloops when the number of iterations depends on a condition. - Use
do-whileloops when the loop must run at least once. - Avoid infinite loops by ensuring loop conditions change.
- Use
breakandcontinuewisely to control loop execution.
Conclusion
Loops are essential for automating repetitive tasks in C programming. Understanding different loop types helps in writing efficient and clean code! 🚀