Learn C++ · lesson 20 of 61 · about 8 minutes
break, continue and Range-for
Walk a corridor of traps tile by tile: visit every character with range-for, skip the safe tiles with continue, and stop at a pit with break.
What you'll learn
- Exit early with break
- Skip with continue
- Loop over every character or item with range-for
The trapped corridor
The next corridor is typed as a line of tiles, like ..#.X..: a . is safe, a # is a spike trap that costs 5 health, and an X is a pit where the hero has to stop. The program has to walk the tiles in order, deal with each one, and stop early at a pit.
Controlling loops
breakleaves the loopcontinueskips to the next lapfor (char c : text)visits every item in a collection, one at a time, without an index
Skip and stop
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
if (i > 7) break;
std::cout << i << " ";
}
std::cout << "\n";
}Output
1 3 5 7Range-for over a string
#include <iostream>
#include <string>
int main() {
std::string word = "education";
int vowels = 0;
for (char c : word) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') vowels++;
}
std::cout << vowels << " vowels\n";
}Output
5 vowelsWalking the corridor
#include <iostream>
#include <string>
int main() {
int health = 100;
std::string corridor = "..#.#X..";
int steps = 0;
for (char tile : corridor) {
if (tile == 'X') {
std::cout << "A pit! You stop.\n";
break;
}
steps++;
if (tile != '#') {
continue;
}
health -= 5;
std::cout << "Spikes! Health: " << health << "\n";
}
std::cout << "You walked " << steps << " steps.\n";
}Output
Spikes! Health: 95
Spikes! Health: 90
A pit! You stop.
You walked 5 steps.Tip
Range-for works on strings now and on vectors, maps and sets later. Prefer it whenever you don't need the index.
Now 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.