C — Array traversal with for, break, and continue
A C for loop can visit an array one index at a time. continue skips the rest of the current pass, and break ends the loop immediately.
A simple example
Print the numbers 1 to 3
- Start with Start at 1
- Do this Visit 1, 2, 3
- Result 1 → 2 → 3
#include <stdio.h>
int main(void) {
for (int n = 1; n <= 3; n++) {
printf("%d\n", n);
}
}
1 2 3
Stop at the end of a batch
The array still has its full type inside main, so dividing its byte size by the size of its first element gives its length. That formula does not work on an array parameter, which is adjusted to a pointer.
A scanner sends 4, then an invalid reading of −1, then the batch marker 0. Add 4, skip the invalid reading and stop at the marker. The later 7 belongs to the next batch.
Run the example
C17. Run these commands from the directory containing the example. Use a Unix-style shell.
cc -std=c17 lesson.c -o lesson
./lesson
#include <stdio.h>
int main(void) {
int readings[] = {4, -1, 0, 7};
int total = 0;
for (size_t i = 0; i < sizeof readings / sizeof readings[0]; ++i) {
if (readings[i] == 0) break;
if (readings[i] < 0) continue;
total += readings[i];
}
printf("%d\n", total);
return 0;
}
4
Start the total at zero. Add 4, skip −1, and stop at 0. The final 7 belongs to a different batch, so the result is 4.
Try it yourself
What changes if the input is 4, −1, 7, 0?
Check your answer
Both positive readings arrive before the sentinel. Their sum is 11. An empty sequence yields 0.