cppbeginner10 minutes

Calculate the Factorial of a Number in C++

Learn how to write a function that calculates the factorial of a given non-negative integer using C++.

Challenge prompt

Write a function named factorial that takes a single integer parameter n and returns the factorial of n. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. If n is 0, the factorial is 1. Your function should handle input values from 0 to 12.

Guidance

  • Remember that factorial of 0 is defined as 1.
  • Use a loop or recursion to multiply the numbers from 1 to n.
  • Check for valid input (non-negative integers).

Hints

  • Consider using a for loop that multiplies the numbers from 1 through n.
  • Think about what the result should be if n is 0.
  • You can use an integer type to store the intermediate results.

Starter code

int factorial(int n) {
    // Your code here
    return 1;
}

int main() {
    int number = 5;
    int result = factorial(number);
    std::cout << "Factorial of " << number << " is " << result << std::endl;
    return 0;
}

Expected output

Factorial of 5 is 120

Core concepts

functionsloopscontrol flow

Challenge a Friend

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