cppintermediate10 minutes

Predict the Output of a Complex Nested Loop with Conditional Logic in C++

Analyze the given C++ code that uses nested loops with conditional statements to manipulate variables. Predict the output without running the code.

Challenge prompt

Examine the following C++ program carefully. The program uses nested loops and conditional if-else statements to update values of variables 'a' and 'b'. Predict the output of the program when executed. Provide a detailed explanation of your reasoning.

Guidance

  • Trace the values of 'a' and 'b' after each iteration of the inner and outer loops.
  • Pay special attention to the conditional statements and how they affect the increments or decrements of the variables.

Hints

  • Focus on how many times the inner loop runs and under what conditions the values of 'a' and 'b' change.
  • Remember that post-increment and pre-increment operators can affect the value in subtle ways.

Starter code

#include <iostream>

int main() {
    int a = 0, b = 0;
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 4; j++) {
            if (i % 2 == 0) {
                a += j;
                b += i;
            } else {
                if (j % 2 == 0) {
                    a -= i;
                } else {
                    b += j;
                }
            }
        }
    }
    std::cout << "a = " << a << ", b = " << b << std::endl;
    return 0;
}

Expected output

a = 2, b = 28

Core concepts

nested loopsconditional statementsvariable manipulationarithmetic operations

Challenge a Friend

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