Step 4 of 7
break and continue
Sometimes you need to change a loop's flow from inside the body:
breakleaves the loop immediately. Execution continues after the loop.continueskips the rest of this pass. In aforloop the update still runs, then the condition is checked as usual.
#include <stdio.h>
int main(void) {
int x;
int count = 0;
while (scanf("%d", &x) == 1) {
if (x == -1) {
break;
}
if (x % 2 != 0) {
continue;
}
count++;
printf("even: %d\n", x);
}
printf("%d even numbers\n", count);
return 0;
}
4 7 10 3 -1 8
even: 4
even: 10
2 even numbers
The 8 after -1 is never read, because break ended the loop.
Reading until the input runs out
while (scanf("%d", &x) == 1) is a standard C idiom: it reads one number per pass and stops when a read fails, which happens at the end of the input or at something that isn't a number. It works for any amount of input without knowing the count in advance.
Sentinel values
Using a special value like 0 or -1 to mean "stop" is called a sentinel. It's handy for simple formats, but it means the sentinel itself can never be real data.
break only exits the innermost loop it's in. That matters once you nest loops.
Your turn: read numbers until you see 0. Ignore negative numbers. Print the sum of the positive ones. Use break for the 0 and continue for negatives.