Nested Loops

In this lesson, we'll look at nested loops in C++. A nested loop is a loop inside another loop. It's often used when working with multiple vectors or when working with nested vectors.

Example: We want to print all possible pairs of numbers from two vectors:

std::vector numbers1 = {1, 2};
std::vector numbers2 = {3, 4};
for(const int number1 : numbers1) {
    for(const int number2 : numbers2) {
        std::cout << number1 << " " << number2 << std::endl;
    }
}

Prints:

1 3
1 4
2 3
2 4

In this example, we go through all numbers in the vector numbers1 and for each number in this vector, we go through all numbers in the vector numbers2. For each combination of numbers, we print the pair.

We can also use a classic for loop:

for(int i = 0; i < numbers1.size(); i++) {
    for(int j = 0; j < numbers2.size(); j++) {
        std::cout << numbers1[i] << " " << numbers2[j] << std::endl;
    }
}

Instructions

Use a for loop to iterate through cities, a nested for loop to iterate through activities and print each pair of values.

Put a space between each pair.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/9

Nested Loops | Start Coder