Three loop forms, plus break, continue and (rarely) goto. Pick for when you count, while when you wait for a condition, do-while when the body must run at least once.
The three loops
#include <stdio.h>
int main(void) {
for (int i = 0; i < 5; i++) /* init; condition; step */
printf("%d ", i);
printf("\n");
int n = 1234, digits = 0;
while (n != 0) { /* test before each iteration */
n /= 10;
digits++;
}
printf("digits = %d\n", digits);
int k = 100;
do { /* body runs at least once */
printf("k = %d\n", k);
} while (k < 10);
return 0;
}0 1 2 3 4
digits = 4
k = 100break and continue
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; /* skip even numbers */
if (i > 7) break; /* leave the loop entirely */
printf("%d ", i);
}
printf("\n");
return 0;
}1 3 5 7Nested loops and patterns
#include <stdio.h>
int main(void) {
int n = 4;
for (int row = 1; row <= n; row++) {
for (int s = 0; s < n - row; s++) putchar('.');
for (int star = 0; star < 2 * row - 1; star++) putchar('*');
putchar('\n');
}
return 0;
}...*
..***
.*****
*******Breaking out of nested loops: goto
#include <stdio.h>
int main(void) {
int grid[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int target = 5;
for (int r = 0; r < 3; r++)
for (int c = 0; c < 3; c++)
if (grid[r][c] == target) {
printf("found at (%d,%d)\n", r, c);
goto done; /* one of the few acceptable uses */
}
printf("not found\n");
done:
return 0;
}found at (1,1)Loop idioms
| Idiom | Code |
|---|---|
| Infinite loop | for (;;) { … } or while (1) { … } |
| Iterate an array | for (size_t i = 0; i < n; i++) |
Count down with size_t | for (size_t i = n; i-- > 0; ) (avoids the unsigned wrap trap) |
| Read until EOF | while ((c = getchar()) != EOF) |
| Two indexes | for (int i = 0, j = n - 1; i < j; i++, j--) |
#include <stdio.h>
int main(void) {
int a[] = {1, 2, 3, 4, 5};
size_t n = sizeof a / sizeof a[0];
for (size_t i = n; i-- > 0; ) /* safe reverse loop with unsigned index */
printf("%d ", a[i]);
printf("\n");
for (int i = 0, j = (int)n - 1; i < j; i++, j--) { /* reverse in place */
int t = a[i]; a[i] = a[j]; a[j] = t;
}
for (size_t i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}5 4 3 2 1
5 4 3 2 1What is the difference between while and do-while?
Why is for (unsigned i = n - 1; i >= 0; i--) an infinite loop?