Learn C · lesson 19 of 60 · about 8 minutes
break and continue
Read the machine's event log one character at a time: walk a string to its end, skip the normal entries with continue, and stop at a crash with break.
What you'll learn
- Exit a loop with break
- Skip an iteration with continue
- Walk a string to its '\0'
The event log
The machine keeps a log of what happened, typed as a line of letters like ..W.X..: a . is a normal entry, a W is a warning that adds 1 to the report's warnings, and an X marks a crash, so nothing after it can be trusted. The program has to read the entries in order, deal with each one, and stop early at a crash.
Two ways to change a loop's flow
breakleaves the loop completelycontinueskips the rest of this lap and starts the next one
Both work in while, do-while and for loops.
Skip evens, stop after 7
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
if (i > 7) {
break;
}
printf("%d ", i);
}
printf("\n");
return 0;
}Output
1 3 5 7Walking a string
A C string is an array of chars with a '\0' at the end, so for (int i = 0; text[i] != '\0'; i++) visits every character and stops at the end. C has no range-for: for (char c : text) is C++, and gcc stops at the colon.
Counting vowels
#include <stdio.h>
int main(void) {
char word[] = "education";
int vowels = 0;
for (int i = 0; word[i] != '\0'; i++) {
char c = word[i];
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
}
}
printf("%d vowels\n", vowels);
return 0;
}Output
5 vowelsReading the log
#include <stdio.h>
int main(void) {
int warnings = 1;
char events[] = "..W.WX..";
int entries = 0;
for (int i = 0; events[i] != '\0'; i++) {
if (events[i] == 'X') {
printf("Crash in the log. Stopping here.\n");
break;
}
entries++;
if (events[i] != 'W') {
continue;
}
warnings += 1;
printf("Warning in the log! Warnings: %d\n", warnings);
}
printf("Read %d log entries.\n", entries);
return 0;
}Output
Warning in the log! Warnings: 2
Warning in the log! Warnings: 3
Crash in the log. Stopping here.
Read 5 log entries.Searching: stop at the first match
#include <stdio.h>
int main(void) {
int found = -1;
for (int n = 20; n <= 30; n++) {
if (n % 7 == 0) {
found = n;
break;
}
}
printf("First multiple of 7: %d\n", found);
return 0;
}Output
First multiple of 7: 21Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.