#include<iostream.h>
#include<conio.h>
int fact(int a);
main()
{
clrscr();
int x,n,y;
cin>>x;
y=fact(x);
cout<<"\n Answer="<<y;
getch();
}
{
int f=1;
if(a==1)
{
return 1;
}
else
{
f=a*fact(a-1);
return f;
}
}
------------------------------------------------
Define Recursion
Simply put, recursion is when a function calls itself. That is, in the course of the function definitiSimply put, recursion is when a function calls itself. That is, in the course of the function definition there is a call to that very same function. At first this may seem like a never ending loop, or like a dog chasing its tail. It can never catch it. So too it seems our function will never finish. This might be true is some cases, but in practice we can check to see if a certain condition is true and in that case exit (return from) our function. The case in which we end our recursion is called a base case . Additionally, just as in a loop, we must change some value and incremently advance closer to our base case.
Consider this function.
void myFunction( int counter)
{
if(counter == 0)
return;
else
{
cout <<counter<<endl;
myFunction(--counter);
return;
}
}
This recursion is not infinite, assuming the function is passed a positive integer value. What will the output be?
Consider this function:
void myFunction( int counter)
{
if(counter == 0)
return;
else
{
cout<<"hello"<<counter<<endl;
myFunction(--counter);
cout<<counter<<endl;
return;
}
}
If the function is called with the value 4, what will the output be? Explain.
The above recursion is essentially a loop like a for loop or a while loop. When do we prefer recursion to an iterative loop? We use recursion when we can see that our problem can be reduced to a simpler problem that can be solved after further reduction.
Every recursion should have the following characteristics.
- --->A simple base case which we have a solution for and a return value. Sometimes there are more than one base cases.
- ----->A way of getting our problem closer to the base case. I.e. a way to chop out part of the problem to get a somewhat simpler problem.
- --->A recursive call which passes the simpler problem back into the function.
- view source:- http://danzig.jct.ac.il/cpp/recursion.html
No comments:
Post a Comment