Loop Invariants

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:

  1. Before the loop starts, sum is $0$, so the invariant holds because the sum of zero elements is $0$.
  2. Each time through the loop, we add the current value of \( i \) to sum, which maintains the invariant correctly.
  3. When the loop finishes, we have \( i = n + 1 \), so the sum is \( \sum_{k=1}^{n} k = \frac{n(n+1)}{2} \), which is the correct result.