Loops – How to Prove a While Loop Calculates n^2

loops

I'm studying for my exam of logic later this week and I have to prove that this while loop:

i := 0
s := 0
while i < n do
    i := i + 1
    s := s + (2*i -1)

calculates n^2. This question is made up of 2 subquestions. We have to prove that 0 ≤ i ≤ n ∧ s = i^2 is a loop invariant for this while loop. I managed to prove that, but the second subquestion is that I have to prove that this loop calculates n^2, but I don't really know how to start. The course is a bit confusing about this part of the question.

Best Answer

The loop calculates 1 + 3 + 5 + 7 + ... + (2n-1). The easiest way to visualise that this sums to n^2 is enter image description here