Tuesday, March 17, 2015

Post #12 - recursive function

Jumping a bit to recursive functions here.
What's a recursive function? It's a function that calls itself from within its own declaration.
For example the recursive function below calls itself twice in the 4th line of the function body.

Once the if statement becomes true, return 4 is there as a termination to any function call made to it (because calling functions forever in a program takes up memory). The two function calls each decrement the initial integer passed to them, a, by 1 and by 2.

If a = 3, the function call would immediately return 4 and the rest of the body would not execute. For numbers > 3, such as 4, the else statement goes into effect and returns a + the function call to H(a - 1)+ call to H(a - 2); or 4 + H(3) + H(2).  H(3)and H(2) both trigger the if statement at the beginning of the function, and they both return 4. So the returning integer if 4 was entered is 4 + 4 + 4, or 12.

int H(int a)
{
if(a <= 3)
return 4;
else
return a + H(a - 1) + H(a - 2);
}

No comments:

Post a Comment