Loop Design Example

Finally, we have to set the loop invariant so that when the loop terminates, we have the correct result. Based on what have been discussed so far, the loop invariant must be true before and after each iteration of the loop. At every iteration of the loop, the variable sum must be equals to the sum of all integers from 0 to count (the counter variable). count is also incremented through each iteration so that we are eventually adding all integers to sum. This also ensures that as we go through each iteration of the loop, count would be approaching n, ensuring loop termination.

sum = sum + count;
count = count + 1;

Once we have defined the pre-condition, post-condition, loop variant and loop invariant, we can write out the code for the problem.

int count = 0;
int sum = 0;

while (count <= n) {
   sum += count;
   count++;
}

<< Back
Fook Yuen Sin - Team 1