Unit 4 Cycle 1 Day 9: Shifting Elements
Share
Shifting Elements
Section 4.3 — Common Array Algorithms
Key Concept
Shifting elements in an array moves elements left or right by one position. A left shift copies each element to the position before it: arr[i] = arr[i + 1]. The last element needs special handling (often set to 0 or a default). A right shift moves elements the opposite direction. The AP exam tests the order of operations: for a left shift, iterate forward; for a right shift, iterate backward. Shifting in the wrong direction overwrites elements before they are moved, causing data loss.
Consider the following code segment.
What is printed?
Answer: (A) 20 50 50
Each element shifts left: arr[0]=20, arr[1]=30, arr[2]=40, arr[3]=50. arr[4] is unchanged (50). Result: 20 50 50.
Why Not the Others?
(B) The shift moves all elements left. arr[0] becomes 20, not 10.
(C) arr[3] gets arr[4]=50 during the shift, not staying at 40.
(D) arr[4] is never assigned a new value. It stays 50, not 0.
Common Mistake
Left shift: arr[i] = arr[i+1] copies each element one position left. The last element is duplicated because nothing overwrites it.
AP Exam Tip
Shifting left leaves the last element duplicated. Shifting right leaves the first element duplicated. To truly remove, you would also decrease a logical size counter.