What is recursion?
Function calling it shelf is called recursion.
Program:
#include <iostream>
using namespace std;
int factorial (int n)
{
if (n < 1)
return 1;
return n * factorial (n - 1); //recursively calling factorial function till n > 1
}
int main ()
{
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Factorial of " << n <<" is " << factorial (n); //function call
return 0;
}
Output:
Enter a positive integer: 5
Factorial of 5 is 120
C++ Program to Find Factorial of a Given Number Using Recursion
Reviewed by Beast Coder
on
February 22, 2021
Rating:

No comments: