cppbeginner10 minutes

Fix the Off-By-One Error in Loop Summation

Debug a simple function in C++ that aims to sum integers from 1 to n but produces incorrect results due to an off-by-one error in the loop.

Challenge prompt

The provided C++ function sumUpTo attempts to calculate the sum of all integers from 1 up to a given number n (inclusive). However, the function currently returns incorrect outputs. Identify and correct the bug in the loop to ensure the function returns the correct summation.

Guidance

  • Check the loop boundaries carefully — is the loop iterating the correct number of times?
  • Remember that loops usually start at zero or one depending on the problem; verify that your loop aligns with the summation requirement.
  • Test the function with small values of n such as 1, 2, and 3 to verify correctness.

Hints

  • The existing loop stops one iteration too early, so adjust the loop condition.
  • Consider whether the comparison operator '<' or '<=' is appropriate in the for loop condition.

Starter code

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

Expected output

sumUpTo(3) should return 6 (1 + 2 + 3 = 6)

Core concepts

loopsfor loopoff-by-one errorbasic arithmetic

Challenge a Friend

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