cppbeginner10 minutes

Predict the Output of a Simple Loop and Conditional in C++

Analyze the given C++ code involving a loop and conditional statements, and predict the exact output it produces when run.

Challenge prompt

Consider the following C++ code snippet. What will be the output when this code runs? int main() { for (int i = 1; i <= 5; i++) { if (i % 2 == 0) { std::cout << i << " is even\n"; } else { std::cout << i << " is odd\n"; } } return 0; } Write down the exact text output the program prints.

Guidance

  • Carefully check the loop's start and end conditions to know which numbers it processes.
  • Remember how the modulo operator (%) determines if a number is even or odd.
  • Each iteration prints one line; count how many lines will be output.

Hints

  • The loop variable 'i' starts at 1 and increases by 1 until it reaches 5.
  • If 'i % 2 == 0' evaluates to true, the number is even; otherwise, it's odd.

Starter code

int main() {
    for (int i = 1; i <= 5; i++) {
        if (i % 2 == 0) {
            std::cout << i << " is even\n";
        } else {
            std::cout << i << " is odd\n";
        }
    }
    return 0;
}

Expected output

1 is odd 2 is even 3 is odd 4 is even 5 is odd

Core concepts

loopsconditionalsmodulo operator

Challenge a Friend

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