cppbeginner10 minutes

Refactor Messy Loop and Conditionals in C++

Improve the readability and maintainability of a C++ function that calculates the sum of even numbers in a vector. Keep its behavior exactly the same while cleaning up the code.

Challenge prompt

You are given a function that calculates the sum of all even numbers in a vector of integers. The current code works correctly but is hard to read and uses unnecessary variables and convoluted logic. Refactor the function to make it simpler, clearer, and more idiomatic without changing its output or behavior.

Guidance

  • Focus on simplifying loops and conditionals without altering the logic.
  • Eliminate unnecessary variables and redundant code.
  • Use meaningful variable names and consistent formatting.

Hints

  • Check if the loop can be replaced or simplified with range-based for loops.
  • Use the modulus operator (%) for checking even numbers.
  • Consider accumulating the sum directly during iteration, avoiding extra assignments.

Starter code

int sumEvenNumbers(const std::vector<int>& numbers) {
    int i = 0;
    int sum = 0;
    while(i < (int)numbers.size()) {
        int current = numbers[i];
        if(current % 2 == 0) {
            sum = sum + current;
        } else {
            sum = sum + 0;
        }
        i = i + 1;
    }
    return sum;
}

Expected output

For input vector {1, 2, 3, 4, 5, 6}, the function should return 12.

Core concepts

loopsconditionalsfunctionscode readability

Challenge a Friend

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