cppbeginner10 minutes

Fix the Off-By-One Error in a Loop to Sum Integers

A simple C++ function intended to sum integers from 1 to n contains a bug causing incorrect results. Identify and fix the off-by-one error.

Challenge prompt

The following C++ function aims to compute the sum of all integers from 1 up to and including n. However, the returned result is incorrect due to a bug in the loop. Fix the bug so that the function returns the correct sum.

Guidance

  • Check the loop boundaries carefully to ensure the loop processes all values from 1 to n inclusive.
  • Consider how the loop counter advances and when the summation occurs.
  • Make sure the loop does not skip the final number or run an extra iteration.

Hints

  • Does the loop condition let i reach the value n?
  • Try printing i inside the loop to verify which values are being summed.
  • Remember, the sum of numbers from 1 to n is n*(n+1)/2; use this to check your answer.

Starter code

int sumUpToN(int n) {
    int sum = 0;
    for (int i = 1; i < n; ++i) {
        sum += i;
    }
    return sum;
}

Expected output

sumUpToN(5) should return 15

Core concepts

loopsconditionalsoff-by-one errorsbasic arithmetic operations

Challenge a Friend

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