AP CSP Day 60: Sorting Algorithms
Share
Practice Question
What is displayed after the following code runs?
nums ← [5, 10, 15, 20, 25]
i ← LENGTH(nums)
REPEAT UNTIL i < 1
{
IF nums[i] MOD 10 = 0
{
REMOVE(nums, i)
}
i ← i - 1
}
DISPLAY(nums)
DISPLAY(LENGTH(nums))The loop traverses backward from i=5 to 1. i=5: nums[5]=25, 25 MOD 10=5 (not 0, skip). i=4: nums[4]=20, 20 MOD 10=0 (remove). nums=[5,10,15,25]. i=3: nums[3]=15, 15 MOD 10=5 (skip). i=2: nums[2]=10, 10 MOD 10=0 (remove). nums=[5,15,25]. i=1: nums[1]=5, 5 MOD 10=5 (skip). i=0: stop. Result: [5,15,25], length 3.
B) 10 is divisible by 10 and is removed. C) 20 is divisible by 10 and is removed. D) 25 is not divisible by 10 (25 MOD 10 = 5), so it remains.
Students confuse divisibility by 10 with having 0 as a digit. 25 MOD 10 = 5 (not divisible by 10). Also, backward traversal is specifically used here to avoid index-shifting problems when removing elements.
Backward traversal is the standard technique for removing elements during iteration. When you remove an element, earlier indices are unaffected, so decrementing i still visits every element correctly.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help