C/C++ Arena

Step 4 of 7

break and continue

Sometimes you need to change a loop's flow from inside the body:

#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 task

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.

Challenge 2

Read scores until you see -1. A score above 100 is invalid, so skip it. Print how many valid scores there were and their total. Input 50 200 60 40 -1 prints 3 scores, total 150. Use break and continue.

Challenge 3

Read numbers and find the first non-negative one that is divisible by 7. Skip negative numbers with continue, and stop with break as soon as you find one. Print found N at position P, where P counts every number read (starting at 1). If the input runs out first, print none. Input 3 -14 10 21 7 prints found 21 at position 4.

Previous: Accumulating a total Next: do-while