Lesson 1 - Part B



Recursion

In computing, recursion is a method of using function which call itself in order to solve smaller part of a problem. I know, this definition is confusing but I will try to use analogies to let you have a deeper understanding of recursion.

Think of the multiplication of two real numbers( numbers equal or above 0). Let's say we are going to multiple 3 by 5. Obviously, the answer is 15 but how do we calculate the value computationally? We keep on adding 3 to 3 for 5 times right? Or even 5 to 5 for 3 times.

Still don't get it? Look at the diagram below.

(3 * 5) = (3 * (5-1)) + 3 = (3 * 4) + 3 = (3 * (4-1)) + 3 +3 = (3 * 3) + 3 + 3

= (3 * (3-1)) + 3 + 3 + 3) = (3 * 2) + 3 + 3 + 3 = (3 *(2-1) + 3 + 3 + 3 +3)

= (3 * 1) + 3 + 3 + 3 + 3 = 3 + 3 + 3 + 3+3 = 15

See the pattern in the equation above? Initially, we minus 1 from 5 and add 3. Then we minus 1 from 4 and add 3 and so on. If multiplication is a function that take in two integers, then we can define the function as shown below.


Mountain View

Every recursion problem must have a base case. This is to ensure that recursion will stop at a certain level. In this case, the base case is when the second parameter of the function multiply is 1. Here's a more detailed diagram on the recursion algorithm.

multiply ( 3, 5) → multiply (3,4) + 3 → multily (3, 3 ) + 6 → multiply (3,2) + 9 →multiply (3,1 ) + 12

multiply (3, 1) will return 3 as shown in the function above. So,

multiply (3,1) + 12 → 3 + 12 → 15.


Do you get recursion now?

No? Never mind, let me give you another example.

Do you know what is factorial ? Factorial is the product of all positive integers less or equal to n. The symbol for factorial is '!'. So, 4! is equal to 4 * 3 * 2 * 1. We can use recusive function to find the value of n!.



factorial(n) :

if n less or equal to 1 :

return 1

else :

return ( n * factorial (n-1))


Let's say we input n as 5. Then the sequence to solve the problem is,

factorial(5) → 5 * factorial(4) → 5 * 4 * factorial(3) → 5 * 4 * 3 * factorial(2) → 5 * 4 * 3 * 2 * factorial(1) → 5 * 4 * 3 * 2 * 1 → 120

As you can see, the base case is when n is 1 or less. This is proven as the recursion stop when the n is 1.

There are three conditions to use a recursion algorithm.

1) There is a base case.

2) Work toward the base case.

3) The function calls itself.



I had already explained the need for a base case. I will now explain about the second condition. Look at both of the recursion algorithms above. The recursion caused the inputs to be closer to the base case each time the function is called. This is important as we do would not want an function which work away from the base case each time it calls itself. This is bad as we would never be able to solve the problem!

The main reason to use recursion is to make the code more readable and simpler as we allowed the function to call itself.



Go to Lesson 1 Part C

Back to Lesson 1 Part A

Back to Index