Loops
Loops in C
C provides three loop constructs.
for loop All three parts (init; condition; update) are optional:
c
for (int i = 0; i < n; i++) { … }while loop Condition tested before the body:
c
while (condition) { … }do-while loop Body executes at least once:
c
do { … } while (condition);Nested loops Common for multi-dimensional iteration. Outer loop rows, inner loop columns.
break and continue
breakexits the innermost loop (or switch).continueskips to the next iteration of the innermost loop.
Key points:
- Omitting the for-loop condition creates an infinite loop:
for (;;) { }. - Loop variables declared inside
for (int i = …)require C99 or later. - Be careful of off-by-one errors:
i < nvsi <= n.
Code Examples
for, while, do-whilec
#include <stdio.h>
int main(void) {
// for loop — sum 1 to 5
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
printf("Sum: %d\n", sum);
// while — find smallest power of 2 >= 50
int n = 1;
while (n < 50) n *= 2;
printf("Power of 2 >= 50: %d\n", n);
// do-while
int x = 1;
do {
printf("%d ", x);
x *= 2;
} while (x <= 16);
printf("\n");
return 0;
}do-while always runs the body once. The while loop condition is checked before each iteration.
Nested loops and break/continuec
#include <stdio.h>
int main(void) {
// Multiplication table (3x3)
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%2d ", i * j);
}
printf("\n");
}
// continue: skip even numbers
printf("Odd 1-10: ");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
printf("%d ", i);
}
printf("\n");
return 0;
}Nested loops iterate over a 2D grid. continue skips even numbers — execution jumps to i++ and the next iteration.
Quick Quiz
1. What does `for (;;) { }` represent in C?
2. Which loop guarantees at least one execution of the body?
Was this lesson helpful?