ITPEC IP April 2024 Question 9
The program performs circular left shifting on the array elements. For example, after circular left shifting, the initial array {1, 2, 3, 4, 5} becomes {2, 3, 4, 5, 1}. Which of the following is an appropriate combination of pieces of code to be inserted in A and B in the program?
Explanation
A: i - 1, B: array[the number of elements of array] — every element moves one place to the left, and the saved first element goes into the last position.
tmp keeps the first element, 1. The loop runs for i = 2 to 5, and each pass must copy array[i] into the position just before it, array[:
The last position, index 5 (the number of elements), must now receive the saved value: array[5] ← tmp gives {2, 3, 4, 5, 1}.
Answer (d)
Why not others:
- •(a) and (b) —
array[copies to the right: i = 2 writes 2 intoi + 1] ← array[i] array[3], each later pass carries that 2 on, giving {1, 2, 2, 2, 2}, and i = 5 writes toarray[6], beyond the end of the array - •(c) — A is right, but B writes 1 into index 4, overwriting the 5 and leaving the last position unchanged: {2, 3, 4, 1, 5}
Key rule: To shift elements left, save the element that falls off the front first, then copy from low indices to high so no value is overwritten before it has been moved.
Algorithm and Programming · AI-written, may contain errors
This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official IP past-paper collection or Report an issue.