Loop Invariant Condition With Examples by GeeksforGeeks

What is a loop invariant?
A loop invariant is a condition among program variables that is necessarily true immediately before and after each iteration of a loop.

What are the three moments when a loop invariant be true?
The three moments when a loop invariant must be true are:

  1. Before the loop starts.
  2. Before each iteration of the loop.
  3. After the loop terminates.

Can a loop invariant be false during the body of a loop?
Yes, a loop invariant can be false during the body of a loop.

What should you write if the loop invariant is not obvious?
If the loop invariant is not obvious, you should write a comment.

What are the three things you need to show with a loop invariant?
The three things you need to show with a loop invariant are:

  1. Initialization - It's true prior to the first iteration.
  2. Maintenance - It's true before and after an iteration.
  3. Termination - The loop terminates and the loop invariant gives us a useful property to show the algorithm is correct.

...