Recursion in Programming - Explained




We'll take an example of multiplying two numbers without using multiplication operator. This can be done in typical way of iteration.

For eg: If we are asked to multiply x and y, we'll keep adding x to x for y times

See the following code:


def iterMul(x, y):
    result = 0
    while y > 0:
        result += x #same as result = result + x
        y -= 1 #same as y = y - 1
    return result


Output:
>>> iterMul(3,7)
21


Recursion does the same thing, but in a bit different way.
We call the function itself in our function.
How to think of it?
How does recursive function work

But still, this doesn't make things clear. It'll get clear with an example.

See the following code (don't worry if you don't get it, see the example below it):

def recurMul(x, y):
    if y == 1:
        return x
    else:
        return x + recurMul(x, y-1)


Output:
>>> recurMul(7,3)
21
  • recurMul(7,3) returns 7+recurMul(7,2)
    • Checks if y=1, here y=2, So recurMul(7,2) returns 7+recurMul(7,1)
    • So our ans is 7+7+recurMul(7,1)
      • Checks if y=1, yes y=1, so returns x, and x = 7
      • So our answer is 7+7+7 which sums up to give 21
So, thats how recursion works. Note the color of 7 in the above explanation in order to feel which 7 is added to which 7.

Note:
This is a part of what I learn in an online Open Course Ware offered by MIT on edX
Its for my personal reference & also for those who have missed the course.
You too can enroll yourself on edX (if they are still offering the course MITx 6.00x)