RECURSION IN C++

Maha



Recursion

  •  Recursion is a situation where a function calls itself, i.e., one of the statements in the function definition makes a call to the same function in which it is present.
  • It like an infinite looping condition but just as a loop has a conditional check to take the program control out of the loop .
  • A recursive function also possesses a base case which returns the program control from the current instance of the function to call back to the calling function.
For example, in a serious of recursive calls ,to compute the factorial of a number, the base case would be a situation where factorial of 0 is to be computed.

Syntax:

int recursion(n)
{
if(n==0)
{
return;
}
return(n-1);
}

Program:

#include <iostream>
using namespace std;
int factorial(int n
{
 if (n == 0) 
{
 return 1;
 } 
else
{
 return n * factorial(n - 1);
 }
}
int main() 
{
 int n;
 cout << "Enter a non-negative integer: ";
 cin >> n;
 if (n < 0)
{
cout << "Error: invalid input." << endl;
return 1;
}
int result = factorial(n);
cout << "The factorial of " << n << " is " << result << "." << endl;
return 0;
}

Output: 

Enter a non-negative integer: 10
The f
factorial of 10 is 3628800.


Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send