133k views
4 votes
Daija is creating a budget, and evaluating his purchases over the last month. Consider the following code segment which attempts to find the sum of all purchases made in the last month, stored in purchaseList. n ← 1 sum ← 0 REPEAT UNTIL () sum ← sum + purchaseList[n] n ← n + 1 What code can replace missing code to assign the total of all values in purchaseList to sum?

1) n = LENGTH (purchaseList)
2) n ≥ LENGTH (purchaseList)
3) n > LENGTH (purchaseList)

User Joe Yan
by
7.1k points

1 Answer

4 votes

Final answer:

The correct code to stop the summing of items in the purchase list is (3) n > LENGTH (purchaseList). Using this condition, the REPEAT UNTIL loop will terminate correctly after the last element has been summed, preventing an out-of-bounds error.

Step-by-step explanation:

The code needed to replace the missing part in the REPEAT UNTIL loop to determine when to stop adding items from purchaseList to the sum is (3) n > LENGTH (purchaseList). This condition will ensure that the loop continues to execute until it has accessed and added every element within the purchaseList array to the sum. After the last element has been added, n will be incremented to a number that is one greater than the length of the list, making the condition true and causing the loop to terminate.

To assign the total of all values in purchaseList to sum, the missing code should be n = LENGTH (purchaseList). By using the function LENGTH(purchaseList), the code will determine the number of elements in the list and assign that value to n. This will ensure that the loop iterates through all the elements in purchaseList and adds them to the sum. Using options (1) n = LENGTH (purchaseList) or (2) n ≥ LENGTH (purchaseList) would result in an off-by-one error where the loop would either not include the last purchase in the sum or would go out of the array's bounds.

User Jed Schmidt
by
8.4k points