I was trying to write a loop invariant and post condition for this code:
sum = 0;
for (i = 0; i < 10; ++i)
++sum;
sum = 10 is the obvious post condition here. But a friend told me that i = sum is also a loop invariant and sum = 12 is also a post condition. I checked the following:
- loop invariant is initially true: that's true for
i = sumsince both are 0 initially - loop invariant is preserved: assume
i < 10andi = sumthen after one iteration it's still true that++i = ++sum - loop invariant implies post condition: assume
i >= 10andi = sumthensum = 12is also true
But obviously sum doesn't equal to 12 here. So what's wrong with my reasoning here?
Take a slightly different invariant
i == sum && i <= 10. Together withi >= 10you get theni = sum = 10.Btw. in your original reasoning you cannot conclude that
sum = 12is true but only thatsum >= 10. The latter is correct, just not strong enough to prove the desired result.