Wednesday, 2 March 2016

Week 7 - Recursion

Last week we started learning about recursion during the lectures. Recursion is a programming technique where a function calls itself during execution. This method is useful because it allows the programmer to avoid repeating the same line of codes. It is important to have different an if/else statement in the function that uses recursion. There must be at least one case telling the function when to stop repeating itself, otherwise, there would be an infinite loop.



The above picture shows an example in which recursion can be used. The factorial of 6 (6!) can be achieved through a function using recursion. In this case, recursion would be needed to find the product of all numbers from 1 to 6. Another example where recursion could be used is in the Fibonacci sequence. In order to accomplish that, the recursive function would need to call itself to add the two previous numbers in the sequence to find the current number.

Since recursion is a fairly new topic to me I am having difficulty implementing it in a program. I'm sure we will cover recursion more in the next few lectures, during the lab, and within the next assignment. I find that it is easier for me to trace a recursive program and figure out the end result than to write the whole function myself. However, I'm hoping to learn this concept soon as it is an essential tool when programming.

No comments:

Post a Comment