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 Output
Enter 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
factorial
that calculates the factorial of a number. - In the
main
function, it prompts the user to enter a positive integer. - It then calls the
factorial
function with the entered number and prints the result.
Similar Questions
find the output of given code.#include <stdio.h>int main(){int a,b=110,c=20;printf("%d",a=b-=c*=5);return 0;}
Write a Python program using a while loop to calculate and display the factorial of a user-inputnumber. Ensure your program handles invalid inputs gracefully.
Write a TCL proc to find the factorial of a number where the number is passed as an argument.
The output of the code will be ____. int i=5; printf(“%d %d %d”, i, i++, ++i); in c
What will be the output of following program?main( ){int k, num = 30 ;k = ( num > 5 ? ( num <= 10 ? 100 : 200 ) : 500 ) ;printf ( "\n%d", num ) ;}
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.