Activity 21.6.1.
We want to write a function that counts the number of 0βs in a vector of integers using recursion.
(a)
What are the inputs and outputs for this function?
- Input: a vector of integers, Output: the number of 0βs in the vector
- Input: a vector of integers, Output: the sum of the integers in the vector
- Input: a vector of integers, Output: the maximum integer in the vector
(b)
What is the best base case for this function?
- If the vector is empty, return 0.
- If the vector has only one element, return 1 if it is 0, otherwise return 0
- This is simple in that it only involves checking a single element. But it is still more work than it could be.
- If none of the elements is 0, return 0.
- That is not an easy job. It still involves looking at the entire vector!
(c)
How could a recursive case for this function break down the problem into a smaller version that is one step closer to the base case?
Remember, we want to take most of the work and hand it off to βsomeone elseβ (a recursive call).
- Remove the last element from the vector.
- Change the last element to 0.
- Our base case involves an empty vector. This does not get us closer.
- Check if there are 0βs left to decide if we need to recurse again.
- A recursive function case should have one simple job. In this case it should look at just one element. The reset areβsomeone elseββs problem.
(d)
When the recursive case gets an answer to the simpler problem, what do we do with that answer?
- Return the count from the recursive call and add 1 if the last element (that we removed) is 0.
- Return the count from the recursive call.
- That does not include our part of the task - dealing with the last element.
- Return the count from the recursive call and add 0 if the last element (that we removed) is 0.
- Each we see should increase the total by 1.