Recursive Functions
Recursive Functions
RECURSIVE FUNCTIONS
Recursion
When function call itself repeatedly ,until some specified condition is
met then this process is called recursion.
It is useful for writing repetitive problems where each action is
stated in terms of previous result.
The need of recursion arises if logic of the problem is such that the
solution of the problem depends upon the repetition of certain set
of statements with different input values an with a condition.
2 Main conditions
int rec(int a)
void main()
{
{
int b;
int rec(int);
if(a<=1)
int n, fact;
{
cout<<“enter the no.”;
return(1);
cin>>n;
}
fact=rec(n);
else
cout<<“factorial is”<<fact;
{
getch();
b=a*rec(a-1);
}
return(b);
}}
• Output:
Enter a number=3
Factorial0f 3=6
Stack representation
.
. 3*2*fact(1)
3*fact(2) 3*fact(2)
fact(3) fact(3)
fact(3)
3*2*1
3*2*fact(1)
3*fact(2)
fact(3)
Fibonacci using recursion
int main()
{
int fib(int);
int n;
cout<<“enter the number of terms=“;
cin>>n;
for(int i=1;i<=n;i++)
cout<<fib(i)<<“ “;
getch();
return o;
}
int fib(int m)
{
if(m==1|| m==2)
return(1);
else
return(fib(m-1)+fib(m-2));
}
Advantages of recursion
1. It make program code compact which is easier to
write and understand.
2. It is used with the data structures such as
linklist,stack,queues etc.
3. It is useful if a solution to a problem is in repetitive
form.
4. The compact code in a recursion simplifies the
compilation as less number of lines need to be
compiled.
Disadvantages
• The book talks about file scope, I’m calling it global scope.
Block Scope
int main(void) {
int y;
{
int a = y;
cout << a << endl;
}
cout << a << endl;
}