built in factorial function in c++
The factorial function in C++ is not built-in, but you can write your own implementation. Here is an example of how you can implement the factorial function in C++:
#include <iostream>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num = 5;
int result = factorial(num);
std::cout << "The factorial of " << num << " is " << result << std::endl;
return 0;
}
Explanation:
- The factorial
function takes an integer n
as input and returns the factorial of n
.
- The base case of the factorial function is when n
is 0 or 1, in which case the factorial is 1.
- If n
is greater than 1, the function recursively calls itself with n-1
and multiplies the result by n
.
- In the main
function, we declare a variable num
and assign it a value of 5.
- We then call the factorial
function with num
as the argument and store the result in the result
variable.
- Finally, we print the result to the console.
Please note that the factorial function implemented here assumes that the input n
is a non-negative integer.