In C programming, loops allow you to repeat a block of code multiple times. The three main types of loops are for, while and do while. Each has a specific use case depending on the structure of your code.
1. For loop:
for loop is generally used when you know the number of iterations ahead of time.
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
return 0;
}
```
This will print numbers from 0 to 4. Here, the loop runs 5 times, as it starts with i = 0 and increments until i<5 is false.
2. While loop:
while loop runs as long as the condition is true. It's more flexible than a for loop when the number of iterations isn’t known beforehand.
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {printf("%d\n", i);
i++;
}
return 0;
}
```
This will also print numbers from 0 to 4, but the condition is checked before each iteration.
3. Do-while loop:
do while loop ensures that the block of code runs at least once before checking the condition.
#include <stdio.h>
int main() {
int i = 0;
do {
printf ("%d\n", i);
i++;
} while (i < 5);
return 0;
}
The condition is checked after each iteration, so the code inside the loop runs at least once.
Common Pitfalls:
* Infinite Loops: Ensure that your loop conditions eventually become false, or you'll run into infinite loops.
* Off-by-One Errors:** Be careful with boundary conditions (<, =) especially in `for` loops.