cppbeginner10 minutes

Fix the Bug in a C++ Function to Calculate Factorial

Identify and fix the bug in a simple C++ function intended to calculate the factorial of a given number. The function currently produces incorrect output for some inputs.

Challenge prompt

The following C++ function is supposed to calculate the factorial of a non-negative integer n (where n! = n * (n-1) * ... * 1 and 0! = 1). However, when tested, it produces incorrect results for inputs greater than 1. Find and fix the bug in the function so that it correctly calculates the factorial.

Guidance

  • Carefully check the initialization of variables used for the factorial calculation.
  • Review the loop structure to ensure it iterates over the correct range.
  • Remember the factorial of 0 is 1 by definition.

Hints

  • Is the variable holding the factorial value initialized correctly before the loop starts?
  • Check whether the loop boundaries include all the numbers needed for the factorial calculation.

Starter code

int factorial(int n) {
    int result = 0;
    for (int i = 1; i < n; ++i) {
        result = result * i;
    }
    return result;
}

Expected output

factorial(0) -> 1 factorial(1) -> 1 factorial(5) -> 120

Core concepts

variables initializationfor loopbasic arithmetic operationsfunction return

Challenge a Friend

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