Recursion
Ex: main()
{
--
main();
--
}
Recursion can be classified into two types as:
1. Direct recursion
2. Indirect recursion
1. Direct recursion: A function calls itself is known as direct recursion.
Ex: void sum()
{
--
sum();
--
}
2. Indirect recursion: A function calls another function, which initiates to call of the initial function is known as indirect recursion.
Ex: void sum()
{
call();
}
void call()
{
sum();
}
/* Example program for GCD using recursion */
#include<stdio.h>
#include<conio.h>
int rgcd(int,int);
main()
{
int m,n;
clrscr();
printf("\n Enter m,n values:\t");
scanf("%d%d",&m,&n);
printf("\n GCD = %d",rgcd(m,n));
getch();
}
int rgcd(int m,int n)
{
if(n==0)
return m;
else
return rgcd(n,m%n);
}
Recursion Advantages:
i. It is easily, simple and understandable.
ii. Using recursion we can avoid unnecessary calling of functions.
iii. The recursion is very flexible in data structure
iv. Using recursion, the length of the program can be reduced.
Recursion Disadvantages:
i. It requires extra storage space. The recursive calls and automatic variables are stored on the stack.
ii. For every recursive calls separate memory is allocated to automatic variables with the same name.
iii. If the programmer forgets to specify the exit condition in the recursive function, the program will execute out of memory.
iv. The recursion function is not efficient in execution speed and time.
No comments:
Post a Comment