Monday, 4 March 2013

3.2.2 Recursion

Recursion, in programming, is the ability for a function to call its self. Practically this means that a recursive function mentions its self within its own function. For example say we have a function called "Factorial" it finds the factorial of a number and we put in 3. Firstly we check that is has a base case that will stop it forming an endless loop. In this case it's that "if n = 1 then Result = 1" this means that once it hits one it stops opposed to continuing for ever and causing a stack overflow error. Next we input 3 and this happens "
"Factorial(3)
Factorial = 3 * Factorial(2)"

As you can see it references its self so next we look at Factorial(2)

"Factorial(2)
Factorial = 2 * Factorial(1)"

so now we're onto Factorial(1) Thankfully due to the clause about n = 1 we don't go any further and it outputs 1, so then it goes up to the next level and times 2 by 1, this results 2 which it then raises again to times 3 by 2 outputting 6 and giving us our answer. This is the principal of recursion.