Recursion

can anyone tell how recursive function do i dont really understand it
i have complicate hw plz
A recursive function is one that calls itself to solve some subset of the problem. An example would be this factorial routine:
1
2
3
4
int factorial(int n){
	if(n==1)return 1;
	return x*factorial(n-1);
}

This routine creates n call frames, each with n reduced by one, then multiplies the numbers together to get the factorial.
closed account (3pj6b7Xj)
Recursion is when you use them same function within itself, for example...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int addnumbers(int value1, int value2);

int main()
{
int a = 36;
int b = 11;
int result = addnumbers(a,b);
return 0;
}

int addnumbers(int value1, int value2)
{
int sum = value1+value2;
int newstuff = addnumbers(sum,100);

return newstuff;
}


Did you see what happened? The same function called itself within itself to do yet more math. that is called recursion but you have to be careful with that as I believe it goes into a stack, too much recursion and you can have some pretty nasty stuff happen. I actually avoid recursion, I don't like it at all.
mrfaosfx, your function will never return, because it always calls itself. It will just end the program with a stack overflow. When using recursion, you must be aware of how many stack frames will be created, and how big they will be.
Last edited on
closed account (3pj6b7Xj)
aw man, you blew the surprise, I wanted the poster to figure that little bomb i put in there, lol...I knew somebody would pick it up quick, I did that specially to point out the issues of recursion if your not careful, and innocent little program may appear fine but in reality, it may not be ;-)
Topic archived. No new replies allowed.