Learning Recursion with flow control diagrams.

                                                                            RECURSION 

Recursion is the process in which function calls itself.While calling itself all or some arguments passed to the function changes.But this process of varying arguments can go on forever so we need a base case where arguments of function meet a condition and that is basically the stopping condition.

We will see diagrams of control transfer in recursion to make things clearer.

Now suppose we want to break any number into only 1's.So before diving into code we will have to write mathematically the expression for this,which will also become our pseudo code.

MATHEMATICAL DEFINITION:-

IF(N>1)
F(N)=F(N-1)+1  
ELSE
F(N)=N;

So the code will look like:

Now suppose we call the our recursive function with argument 5 and see the recursive function in action.



Now one important thing to notice is when the function which satisfies the base case returns ,it transfers control to the calling function but that calling function does not immediately returns it further goes on to check whether something more is left to do.
Not clear what that says Don't worry we will see code in action:

Consider following code:-


 The output of this code:-
So this code prints the string forward and backward as well. How this happens see the next figure:-
        

So when a recursive function when resumes it does not goes off just like the base case ,it checks further if there is more to execute or not.

Check this example:-
So we want to write a recursive function that can be expressed as sum of 3 and 4 and order matters.
order matters means say for 7 ,3+4 is different from 4+3.
Code:-
Output of code for n=7.



Try to draw for n=10 like above diagram.
Hope it clears something!









Comments