cppintermediate10 minutes

Predict the Output of Nested Loops and Conditionals in C++

Analyze the following C++ code with nested loops, conditionals, and array manipulation, then determine and predict what the output will be when the program runs.

Challenge prompt

Given the C++ code snippet below, predict the exact output printed to the console. Pay careful attention to the nested loops, the conditional checks inside the inner loop, and how the array 'results' is modified. Explain your reasoning about loop iterations and the conditional logic used to modify the 'results' array. Code snippet: #include <iostream> using namespace std; int main() { int results[5] = {0, 1, 2, 3, 4}; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if ((i + j) % 3 == 0) { results[i] += j; } else if ((i * j) % 4 == 0) { results[i] -= j; } } } for (int i = 0; i < 5; i++) { cout << results[i] << " "; } cout << endl; return 0; }

Guidance

  • Carefully track each iteration of both loops and note how 'results[i]' is updated with each condition.
  • Remember that the conditions in the if-else statements are mutually exclusive: only one block executes per inner loop iteration.
  • Focus on the arithmetic operations and think about how the index sums and products relate to the modulus conditions.

Hints

  • Try to break down iterations for a single index 'i' to understand the transformation of 'results[i]'.
  • Consider writing down the values of i + j and i * j for each j in inner loop to verify which condition triggers.

Starter code

#include <iostream>

using namespace std;

int main() {
    int results[5] = {0, 1, 2, 3, 4};
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            if ((i + j) % 3 == 0) {
                results[i] += j;
            } else if ((i * j) % 4 == 0) {
                results[i] -= j;
            }
        }
    }
    for (int i = 0; i < 5; i++) {
        cout << results[i] << " ";
    }
    cout << endl;
    return 0;
}

Expected output

7 9 10 10 9

Core concepts

nested loopsconditionalsmodulus operatorarray manipulation

Challenge a Friend

Send this duel to someone else and see if they can solve it.