Recursion in C++


Prev Tutorial Next Tutorial

Recursion in C++

When method is call within same method is called Recursion. The method which call same method is called recursive method. In other words when a method call itself then that method is called Recursive method.

Recursive method are very useful to solve many mathematical problems like to calculate factorial of a number, generating Fibonacci series, etc.

Advantage of Recursion

  • method calling related information will be maintained by recursion.
  • Stack evaluation will be take place by using recursion.
  • In fix prefix, post-fix notation will be evaluated by using recursion.

Disadvantage of Recursion

  • It is a very slow process due to stack overlapping.
  • Recursive programs can create stack overflow.
  • Recursive method can create as loops.

Find the Factorial of any number using recursion

Example Recursion in C++

#include<iostream.h>
#include<conio.h>

void main()
{
int fact(int);
int i,f,num;
clrscr();
cout<<"Enter any number: ";
cin>>num;
f=fact(num);
cout<<"Factorial: "<<f;
getch();
}

int fact(int n)
{
if(a<0)
return(-1);
if(a==0)
return(1);
else
{
return(n*fact(n-1));
}
}

Output

Enter any number: 5
Factorial: 120
Recursion

Find the Table of any number using recursion

Example

#include<iostream.h>
#include<conio.h>

void main()
{
int table(int,int);
int n,i;      // local variable
clrscr();
cout<<"Enter any num : ";
cin>>n;
for(i=1;i< =10;i++)
{
cout<<n<<"*"<<i<<= <<table(n,i)<<endl;
}
getch();
}
int table(n,i)
{
int t;
if(i==1)
{
return(n);
}
else
{
t=(table(n,i-1)+n);
return(t);
//return(table(n,i-1)+n);
}
}

Output

Enter any number: 5
5*1= 5
5*2= 10
5*3= 15
5*4= 20
5*5= 25
5*6= 30
5*7= 35
5*8= 40
5*9= 45
5*10= 50

Prev Tutorial Next Tutorial

Advertisements




Facebook Likes

Advertisements