Consider the C program fragment below which is meant to divide by using repeated subtractions. The variables , , and are all unsigned int.
while (r >= y) {
r=r-y;
q=q+1;
}
Which of the following conditions on the variables and before the execution of the fragment will ensure that the loop terminated in a state satisfying the condition ?
View worked solution
Answer: C
To ensure that the loop terminates in a state satisfying the relation , we can use the concept of loop invariants.
Let us define the loop invariant as .
- Initialization: For the invariant to hold before the loop starts, we must initialize the variables such that . If we set and , the relation becomes: which is always true.
- Maintenance: During each iteration of the loop, let the new values of and be and respectively, where and . Substituting these into the invariant expression: Since the invariant holds before the iteration (), it also holds after the iteration ().
- Termination: For the loop to terminate, the loop condition must eventually become false. Since is decremented by in each step, we must have to ensure strictly decreases and the loop terminates. If , the loop would run infinitely.
Combining these requirements, we need before the execution of the loop.
Free practice · Your answers on this page are not saved.
