Recursion
Recursion
- Function repeatedly call itself is called recursion.
- Recursion is most important concept of object oriented programming.
- We can reduce the size of program using recursion
- Recursion solve some problem easily
Examples:
- Tower of Hanoi
- Fibonacci Series
- Factorial
Let"s take the code for Fibonacci series
CODE:
#include <iostream>
using namespace std;
int main()
{
int a= 0, b = 1, nextTerm = 0, n; //a and b are terms
cout << "Enter a positive number: ";
cin >> n;
// displays the first two terms 0 and 1
cout << "Fibonacci Series: " << a << ", " << b << ", ";
nextTerm = a + b;
while(nextTerm <= n)
{
cout << nextTerm << ", ";
a = b;
a = nextTerm;
nextTerm = a + b;
}
return 0;
}
OUTPUT:
Let"s take the code for Factorial
CODE:
#include<iostream>
using namespace std;
int factorial(int n);
int main()
{
int n;
cout << "W.A.P. to find factorial of given number using recursion.\n\n\n";
cout << "Enter a positive integer: ";
cin >> n;
cout << "Factorial of " << n << " = " << factorial(n);
return 0;
}
int factorial(int n)
{
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}
OUTPUT:
0 Comments