Example #1: Consider the task of computing the sum of the first \( n \) positive integers using a loop. The pseudocode of this task is:
sum = 0;
for (i = 1; i <= n; i++)
sum = sum + i;
We claim that the loop invariant is: "At the start of the $i$th iteration, sum
contains the value \( \sum_{k=1}^{i-1} k \) (= the sum of the first $i$ positive integers seen so far.)" This invariant is indeed true because:
sum
is $0$, so the invariant holds because the sum of zero elements is $0$.sum
, which maintains the invariant correctly.