Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2016/imperative-programming-resit/4/c/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2016 Imperative programming (resit) 4 c Solution by
Codex 0 2026-10-31
Save the last entry and shift in decreasing index order, so no source is overwritten before being used:The loop invariant is
PROCEDURE RightOne;
VAR saved: T; i: INTEGER;
BEGIN
saved := a[N-1]; i := N-1;
WHILE i > 0 DO
a[i] := a[i-1]; i := i-1
END;
a[0] := saved
END RightOne;saved = A[N-1], for , and for . The decreasing loop variant is . At exit the untouched saved value fills index zero. The result is , again with reads, writes, and one extra value of type T. Applying this after part (b) restores every original entry. New to topics? Read the docs here!