# Recursion my own example

I created my own recursion example and commented it out. It might help someone.

COPY AND PASTE IT TO A NEW PROJECT AND YOU WILL SEE FOR YOURSELF WHAT IS HAPENING

[code]// this function gets called from main and with value 2 being passes to this paramether named countVar
// now we can use it inside this function and do whatever we want with it.
void methodToCall (int countVar)
{
// The “true” part of the if statement only runs once when the program comes to an end
// this is where it should end
// but not until all frames removed from the stack
// the top frame would be with the countVar value of 0;
// it gets removed, but now it must continue where it stopped
// printf(“Now lets continue where we left before and the value of countVar is %d\n”,countVar);
//
if (countVar == 0){ // “true part of the if statement"
printf(”\nThat is it, it is the end of the program countVar value is %d\n", countVar);
printf(“Lets clear the stack and remove frame by frame starting with the top frame\n”);
} else {
printf(“The value of countVar is %d lets deduct 1 from countVar and call this method again \n”, countVar);
int oneLessVar = countVar -1;
methodToCall(oneLessVar);
// this is where it stopped so now it needs to finish this function before we can remove the frame from the stack.
printf("\nNow lets continue where we left before and the value of countVar is %d\n",countVar);

``````}
// this runs when if loop has finished its job
printf("Frame with countVar with the value of %d is removed\n", countVar);
``````

}

int main(int argc, const char * argv[])
{
// this is where it all starts
methodToCall(2);
return 0;
}[/code]

So can I check if I understand this correctly…

The function calls itself and each time the value of countVar is stored in its own frame of the stack. So once the value of CountVal reaches zero we have frames with the values of countVal (2,1 and 0). Now the program needs to resume execution from its last position which was line 29 (methodToCall(oneLessVar);

So it moves onto the printf statement. I assume this is returning the function methodToCall so as to release the frames from the stack. So now when we use the variable countVar it returns the value of the current frame and then releases it from memory. This is why when we use a breakpoint we can see the compiler checking methodToCall(oneFewer), then the printf and then over again until all frames are released from the stack. (I’m not sure why the compiler checks line 29 here, not sure how or if the one fewer parameter for methodToCall is affecting the value of countVal).

If you could clear this up for me I would be grateful!, Thanks in advance

Rory.