we can develop the functions in two ways
1. iterative method
2. recursive method
Iterative functions – are loop based imperative repetitions of a process (in contrast to recursion which has a more declarative approach).
Q: Is the recursive version usually faster?
A: No -- it's usually slower (due to the overhead of maintaining the stack)
Q: Does the recursive version usually use less memory?
A: No -- it usually uses more memory (for the stack).
Q: Then why use recursion??
A: Sometimes it is much simpler to write the recursive version (but we'll need to wait until we've discussed trees to see really good examples...)
The recursive version is
* a little shorter,
* a little clearer (closer to the mathematical definition),
* a little slower
#include<stdio.h>
#include<conio.h>
int fact(int n)
{
if(n==0)
return 1;
else
return(n*fact(n-1));
}
void main()
{
int n;
clrscr();
printf("enter n value\n");
scanf("%d",&n);
printf("factorial function is%d\n",fact(n));
getch();
}
Functions


No comments:
Post a Comment