Beruflich Dokumente
Kultur Dokumente
Asis Panda
6/22/2009
Recursion
Finally i got what i was seraching for...The total insight on Recursion...
Let us begin.
Let us perform a recursive programming for finding the multiplication of two numbers.
NOTE: I chose this task as it is a bit ahead in class of the factorial recursion and behind the
Fibonacci series generation....
THEORY
Basic of multiplication is that we want to add a relatively larger series of same number.
i.e. 2+2+2+2+2+2+2+2+2+2
So we multiply.
Note: I took 10X2 and not 2X10 because it fits in to my recursive program which is coming
ahead. Theres absolutely no problem and the program needs just a minor change if you wanna
do it the other way round. For now let’s go on with what I say…
As in factorial we shred the number by factor of 1 in each run of the function similarly we will
have two numbers to multiply , let us suppose3 and 2.
3X2
= 2 X 2 +2
=1 X 2 + 2 + 2
=0 X 2 +2 + 2 + 2
=2+2+2
=6
Now we need to convert this mathematical idea into an expression which on running each step
shall give us the corresponding mathematical steps
Mul= (a-1)*b+b;
But its not the expression which can be put into our recurvie function.
Now let us look at the core concept of recursion and the insight of the operation.
Look at the following code as it does the multiplication operation …and I’l tell u why and how !
if(a==0)
return 0;
else
return mul;
The line A is the master line which does our multiplication operation.
The Downward Move
mul=recur(a-1,b)+b;
It calls the recur function each time decreasing the value of 3 in 3x2 and adding a 2 to the same.
=recur(2,2)+2
=recur(1,2)+2+2
=recur(0,2)+2+2+2
=0+2+2+2
Isn't it same as
3X2
= 2 X 2 +2
=1 X 2 + 2 + 2
=0 X 2 +2 + 2 + 2
=2+2+2
=6
In the STACK memory of the computer ram each step of the above lines are stacked one by one.
The line mul=recur(a-1,b)+b; stacks each iteration in stackes untill the value of a decreases to 0.
when 0 is hit it is returned which acts as an exit criteria and indicates the program execution to
de-stack the stack(unloading of the stack).