The following procedure is intended to return the number of times the value val
appears in the list myList
. The procedure does not work as intended.
Line 01: PROCEDURE countNumOccurrences(myList, val) Line 02: { Line 03: FOR EACH item IN myList Line 04: { Line 05: count ← 0 Line 06: IF (item = val) Line 07: { Line 08: count ← count + 1 Line 09: } Line 10: } Line 11: RETURN(count) Line 12: }
Which of the following changes can be made so that the procedure will work as intended?
Correct Answer: ?????
This problem is testing your understanding of how to fix a simple algorithm so that it correctly counts how many times a given value (val
) appears in a list (myList
).
The algorithm has the goal of looping through every item in the list and checking if the item matches the value val
. If it does, it should increase the count
by 1.
However, there's a problem with where the variable count
is set to 0. It’s currently set inside the loop, which means count
resets to 0 every time it checks a new item. This means the algorithm will only ever count at most 1 occurrence.
By moving the count = 0
line before the loop, the algorithm will initialize count
to 0 once at the start, and then it will properly add 1 each time it finds val
in myList
. This allows the procedure to correctly accumulate the total number of times val
appears.
Key Takeaway: When you're writing loops that accumulate a result, make sure your accumulator (in this case, count
) is initialized outside of the loop. That way, it doesn't reset every time the loop runs.