http://www.tutorialdost.com/C-Programming-Tutorial/15-C-Recursion.aspx
Recursion in C
When a function calls itself from its body is called Recursion.
Advantages
- Reduce unnecessary calling of function.
- Through Recursion one can Solve problems in easy way while its iterative solution is very big and complex.
Disdvantages
- Recursive solution is always logical and it is very difficult to trace.(debug and understand).
- In recursive we must have an if statement somewhere to force the function to return without the recursive call being executed, otherwise the function will never return.
- Recursion takes a lot of stack space, usually not considerable when the program is small and running on a PC.
- Recursion uses more processor time.
Example : C program to calculate factorial using recursion
#include<stdio.h>
long Factorial(int);
void main()
{
int num;
long fact;
printf("\n\tEnter any positive number : ");
scanf("%d",&num);
fact = Factorial(num);
printf("\n\tThe Factorial of %d is %ld",num,fact);
}
long Factorial(int num)
{
if (num == 1)
return 1;
else
return num*Factorial(num-1);
}
Output :
Enter any positive number :
The Factorial of 10 is 3628800
No comments:
Post a Comment