Nested Loops
A loop can contain another loop. This is called a nested loop. In each iteration of the outer loop, the inner loop runs all the way through. Let's list every lunch a canteen offers: every meal with every drink.
std::vector<std::string> meals = {"pizza", "pasta"};
std::vector<std::string> drinks = {"water", "juice", "tea"};
for (std::string meal : meals) {
for (std::string drink : drinks) {
std::cout << meal << " " << drink << std::endl;
}
}This prints:
pizza water
pizza juice
pizza tea
pasta water
pasta juice
pasta teaThe outer loop takes "pizza", and the inner loop goes through all three drinks. Only then does the outer loop take "pasta", and the inner loop goes through all the drinks again. The inner block runs 2 × 3 = 6 times. Give the variables of the two loops different names (here meal and drink), so that you know which is which.
Nested loops are also handy for tables. Here, both loops count with an index. The inner loop prints one row on one line, and std::endl after it ends the row:
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 5; column++) {
std::cout << row * column << " ";
}
std::cout << std::endl;
}1 2 3 4 5
2 4 6 8 10
3 6 9 12 15 Look at where std::cout << std::endl; is: after the closing brace of the inner loop, but still inside the outer loop. It runs each time the inner loop has printed a whole row. Inside the inner loop, it would put every number on its own line. After the outer loop, it would put all the numbers on one long line.
Instructions
- 1
A travel agency offers a trip to each city in
citieswith each activity inactivities. Write a loop overcitiesand, nested inside it, a loop overactivities. Print every pair on its own line: the city, one space and the activity. The output has 12 such lines and starts withPrague Tennis,Prague Shopping,Prague Sightseeing,Brno Tennis… - 2
Below that, print a multiplication table from 1 to 5: five rows with five numbers each, separated by spaces. The first row is
1 2 3 4 5, the second one2 4 6 8 10and the last one5 10 15 20 25. Use two nestedforloops with an index, and end each row withstd::endlin the outer loop.