In C, there are three main types of loops: for, while, and do-while. Here's how each works with clear examples.
1. for loop (most common when you know the number of iterations)
C
#include <stdio.h>
int main() {
// Print numbers from 0 to 9
for (int i = 0; i < 10; i++) {
printf("%d\n", i);
}
return 0;
}Structure:
C
for (initialization; condition; update) {
// code to repeat
}- initialization: Runs once at the start (e.g., int i = 0)
- condition: Checked before each iteration (loop runs while true)
- update: Runs after each iteration (e.g., i++)
You can also have infinite loops:
C
for (;;) {
// runs forever (or until break)
}2. while loop (checks condition before entering)
C
#include <stdio.h>
int main() {
int i = 0;
while (i < 10) {
printf("%d\n", i);
i++;
}
return 0;
}Structure:
C
while (condition) {
// code to repeat
}The body runs only if the condition is true at the start.
Infinite while:
C
while (1) {
// runs forever
}3. do-while loop (checks condition after executing body at least once)
C
#include <stdio.h>
int main() {
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 10);
return 0;
}Structure:
C
do {
// code to repeat
} while (condition);Note the semicolon ; at the end.
This guarantees the loop body runs at least once, even if the condition is initially false.
Loop control statements
- break;: Immediately exits the loop
- continue;: Skips the rest of the current iteration and goes to the next
C
for (int i = 0; i < 10; i++) {
if (i == 5) continue; // skip 5
if (i == 8) break; // stop at 8
printf("%d\n", i);
}Nested loops
You can put loops inside loops (e.g., for 2D arrays):
C
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("(%d,%d) ", i, j);
}
printf("\n");
}Choose the loop type based on your needs:
- Use for when you know the exact number of iterations.
- Use while when the end condition is more complex.
- Use do-while when the body must run at least once (e.g., menu prompts).