Back 

Recursion questions and answers

Questions

Q1. Define ‘the factorial of a number’.
Q2. What is factorial 5?
Q3. What is factorial 7?
Q4. How many values does a function traditionally return?
Q5. Can functions in Python return more than one value?
Q6. Define ‘recursion’.
Q7. What is the stack used for with respect to calling a function?
Q8. Is the stack in RAM or ROM?
Q9. Explain your answer to Q8 above.
Q10. What might happen to the stack if you recursively call a function too many times?

Answers

Q1. The factorial of a number is the number multiplied by all of the integers from itself down to one.
Q2. Factorial 5 = 120
Q3. Factorial 7 = 5040
Q4. A function traditionally returns 1 value.
Q5. Functions in Python can return more than one value.
Q6. Recursion is when a function calls itself.
Q7. When you call a function, the CPU stops and jumps to the function. So that the CPU can return to what it was doing after the function has been completed, you have to save the contents of the CPU’s registers. You push the contents of the registers in the CPU onto the stack, along with the function’s return address and any arguments needed by the function. When the function starts, it pops off any arguments it needs and carries out the function. When the function is completed, it pops the return address and the register contents from the stack and carries on from before. The stack is also used to return any value generated by the function.
Q8. The stack is held in RAM.
Q9. You need to be able to read to memory and change values held in memory. ROM is read only but RAM is read / write.
Q10. Each time you recursively call a function, you have to save the contents of the CPU on the stack. If you do this too many times, the stack will eventually fill up because it is a fixed size. You will therefore get a stack overflow error.

Back