calculate factorial
Here is the code to calculate factorial in C++:
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Factorial of " << num << " is " << factorial(num) << endl;
return 0;
}
Explanation:
The code begins with the inclusion of the
iostream
header file, which allows us to use the input/output stream objects likecin
andcout
.The
factorial
function is defined, which takes an integern
as an argument and returns an integer value. This function calculates the factorial recursively.Inside the
factorial
function, there is a base case that checks ifn
is equal to 0. If it is, the function returns 1, which is the factorial of 0.If
n
is not equal to 0, the function recursively calls itself with the argumentn - 1
and multiplies the current value ofn
with the result of the recursive call.In the
main
function, an integer variablenum
is declared to store the user input.The user is prompted to enter a number using
cout
andcin
is used to take the input and store it in thenum
variable.The
factorial
function is called with thenum
variable as an argument, and the result is printed usingcout
. The<<
operator is used to concatenate the strings and variables together.Finally, the
main
function returns 0, indicating successful execution of the program.