Write program to calculate factorial of number in C++

 #include <iostream>


using namespace std;


// function to find the factorial of a number

int factorial(int n) {

    // base case

    if (n == 0) {

        return 1;

    }

    // recursive case

    else {

        return n * factorial(n-1);

    }

}


int main() {

    int n;

    cout << "Enter a number: ";

    cin >> n;

    cout << "Factorial of " << n << " is " << factorial(n) << endl;

    return 0;

}


In this code, we define a function factorial that takes an integer argument n and returns the factorial of n. The base case of the recursion is when n is equal to 0, in which case the function returns 1. Otherwise, the function recursively calls itself with n-1 as the argument and multiplies the result by n to get the factorial of n. In the main function, we simply read in a number from the user and call the factorial function to print out the result.

Post a Comment

0 Comments