Iteration Examples (Contd.)
Recursion
The Algorithm below is used to calculate the factorial of a number, n, that is inputted. When the function is first called n is given to the first iteration.
If n was initially 3 then it will be tested for 0 or 1 (FALSE) so line 05 will be executed and the first iteration of the function "paused", n in this function will be equal to n-1 from the last function (2). As 2 is still not 0 or 1 line 05 will be executed again and factorial will be called again. In this iteration of the function n = 1 so the function will return 1. Now the Recursion will go back to its previous iterations and evaluate line 05 in iteration 2 which will be 2 x 1 (the returned value) this will then be returned to the first iteration so that line 05 will equal 3 x 2 which is 6.
It is important to think of each function called as being completely seperate as each parameter and/or variables are different and can contain different values completely.
Comments
No comments have yet been made