Write a C++ program to find the factorial of a given integer using recursion.sample input and outputEnter a positive integer: 5 Factorial of 5 is: 120
Question
Write a C++ program to find the factorial of a given integer using recursion.sample input and outputEnter a positive integer: 5 Factorial of 5 is: 120
Solution
Sure, here is a simple C++ program that calculates the factorial of a number using recursion:
#include<iostream>
using namespace std;
// Function to calculate factorial
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 << " is: " << factorial(num) << endl;
return 0;
}
This program works as follows:
- It first includes the necessary libraries.
- It then defines a recursive function
factorialthat calculates the factorial of a number. - In the
mainfunction, it prompts the user to enter a positive integer. - It then calls the
factorialfunction with the entered number and prints the result.
Similar Questions
Write a program to calculate the factorial of N.
Write a C++ Program to find Factorial of a number using classinputEnter a number: 5outputBelow is the input and output of the provided C++ program to find the factorial of a number using a class:Input:Enter a number: 5 Output:Factorial of 5 is: 120
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.
c++ program on factorial of a number in short
write an iterative code for factorial in c
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.