c++ program on factorial of a number in short
Question
c++ program on factorial of a number in short
Solution
Sure, here is a simple C++ program to calculate the factorial of a number:
#include<iostream>
using namespace std;
int factorial(int n) {
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}
int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;
cout << "Factorial of " << num << " = " << factorial(num);
return 0;
}
Here's how it works:
-
The
factorialfunction is a recursive function that multiplies the number by the factorial of the number minus one, until it gets to 1 (since the factorial of 1 is 1). -
In the
mainfunction, we ask the user to enter a number. -
We then call the
factorialfunction with the user's number, and print out the result.
Similar Questions
write an iterative code for factorial in c
Write a program to calculate the factorial of N.
Write a C program, using functions where the function calculates the factorial of a given integer, and the main() program does I/O and calling of factorial function.
Write a program that takes a positive integer as input and calculates its factorial using a for loop. The factorial of a number is the product of all positive integers up to that number.
00:47Write a program to find a factorial of a number
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.