

Using a Loop Invariant to Help Think About a Program - ingve
http://www.drdobbs.com/cpp/using-a-loop-invariant-to-help-think-abo/240169056

======
mjcohen
If you are trying to prove (formally or informally) that a program is correct,
loop invariants allow you to prove that loops do what you want.
Contrapositively, if you can't write a loop invariant, you probably do not
really understand what the loop is doing.

I have had Dijkstra's book for many years, and love it. It's a great read, and
it should be reprinted or put into the public domain.

~~~
NhanH
May I ask which Dijkstra's book you are referring to?

~~~
MaysonL
Probably _A Discipline of Programming_

[http://www.alibris.com/A-Discipline-of-Programming-
Edward-W-...](http://www.alibris.com/A-Discipline-of-Programming-Edward-W-
Dijkstra/book/1741815)

------
27182818284
Interestingly, I had never heard the phrase "loop invariant" despite having
taken math courses on proofs and a lower-level (300-level, quicksort, etc)
algorithms course.

I'm curious. Is this like a "supper vs dinner" or "pop vs soda" variation that
depends on the region your university is located?

~~~
dill_day
I wouldn't guess so, for example it's used in the CLRS textbook. What did you
call it instead?

~~~
27182818284
I don't remember it ever being named. It isn't the same as the "inductive
step" when learning proofs by induction, is it?

~~~
casion
I understand your confusion, because the author didn't properly cover what
he's talking about. It appears to be written to teach people who already know
the material.

In the previous article, the closest thing to an explanation or definition of
a loop invariant is, "We can make it less so by writing down a specific claim
that applies to our particular loop. Such a claim is called a loop invariant."
Not a very good description, and he doesn't try to do any better elsewhere.

I ended up having to do a bunch of googling after reading the articles to
piece together what is trying to be explained, since I had never heard of loop
invariants in that terminology either.

Simply put, a loop invariant is a condition or set of conditions that is true
through the loop. This makes it akin to inductive proofs. The loop invariant
must prove true for n and n+1 for it to be true for the entirety of the loop.
Noting how similar this is to inductive reasoning, you can apply an inductive
proof to a loop invariant to prove it.

The easiest way I've seen to explain it is in the body of the executing loop
you ask yourself, "What has the loop done so far." An answer to that question
should yield a loop invariant.

------
ksikka
Relevant course notes from a course at Carnegie Mellon -
[http://www.cs.cmu.edu/~fp/courses/15122-s11/recitations/reci...](http://www.cs.cmu.edu/~fp/courses/15122-s11/recitations/recitation02.html#invariants)

