CS120
Lab #11
Due at the end of lab.
You will earn full points for this lab if you answer all questions.
Do not be concerned if you got a "wrong" answer.
Just answer all the questions and enjoy learning about the topic.
For this lab we will explore recursion. A function that calls itself is recursive.
Sometimes it is easier or more elegant to solve a problem using recursion rather than iteration.
A recursive function must contain a base case and a recursive case. The base case
is what is used to determine when to terminate recursion. If the base case is omitted or is incorrect,
a recursive function will call itself without terminating, and an aberrant situation such as a segmentation
violation will result.
The recursive case of a recursive function is used to continue the recursion and continue making progress toward the solution.
A program containing a recursive function is here.
Review this code and answer the following questions. Record your answers in a file that you can submit in Canvas.
- What is the base case in the factorial function? Write the line or lines of code that you think compose the base case.
- How many times will the factorial function be called when the argument n is 5? After you have made a guess, copy the contents of the code into a file and modify the factorial function to print a line of text at the very start of the function (before the base case). Then compile and run your code to see how many times it is called when n is 5. You can tell how many times the function is called by counting the number of times that the line of text that you added is printed out.
- What do you think would happen if you changed the predicate in the if statement inside the factorial function to (n <= 2)? Explain your answer. You might try modifying the code to change the predicate, recompiling, and observing what happens.
- What do you think would happen if you swapped the operands to the multiplication operator (the * symbol) inside the factorial function? Explain your answer. You might try modifying the code to swap the operands and observing what happens.
Turn in: Submit the file with your answers to Canvas.