- Write a C++ program to find the factorial of a given number using recursion?
Lucky KaushikBegginer
C++ prgramming
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our W3Make Forum to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
In this program, we first need to understand that factorial of a number is a number which is the product of all the numbers from 1 to the number itself and the factorial of 1 is 0. Now, to find using recursion, we would have to start multiplying the numbers from n to factorial of n-1 then n-1 to factorial of n-2 and so on until we reach 1.
So, to answer your question you can use the following code:
#include <iostream>
using namespace std;
long long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n – 1);
}
}
int main() {
int number;
cout << “Enter a positive integer: “;
cin >> number;
long long result = factorial(number);
cout << “Factorial of ” << number << ” = ” << result << endl;
return 0;
}
I hope I was able to answer your question.
# factorial of a number is the product of all positive integers less than or equal to that number.
#include <iostream>
using namespace std;
unsigned long long factorial(unsigned int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n – 1);
}
int main() {
unsigned int number;
cout << “Enter a positive integer: “;
cin >> number;
unsigned long long result = factorial(number);
cout << “Factorial of ” << number << ” = ” << result << endl;
return 0;
}
In this program, the factorial function is defined to calculate the factorial of a given number n. It checks if n is 0 or 1, in which case it returns 1 (since the factorial of 0 and 1 is 1). Otherwise, it recursively calls itself with n – 1 and multiplies the result with n.
In the main function, the user is prompted to enter a positive integer. The factorial function is then called with the provided number, and the result is displayed on the console.
Imp: This program assumes that the input number is a positive integer. It uses the unsigned long long data type to handle larger factorial values, as they can grow quickly.
code for a function that takes an integer n as input and returns n! as output in C++
int factorial(int n)
{
if (n == 0) //this is the base case in factorial, since 0!=1
{ return 1; }
return n * factorial(n – 1);
//This is the recursive call, where n! = n * (n-1)! here the function is called again with (n-1) as a parameter, this goes on until we reach zero and 1 is returned and finally, everything in the stack returned after each recursive call is multiplied up to n to give n!
}