tutor.org.in

Free preview · Reading · 1 h

Correctness: invariants and testing

Programming & Algorithms · Programming foundations

In this lesson

  • State a loop invariant
  • Write unit tests including edge cases

Explanation

A loop invariant is a statement true before and after every iteration; it explains why a loop gives the right answer. Tests make the reasoning concrete: typical, boundary and adversarial cases.

Worked example

In a running-maximum loop the invariant is “best equals the largest of the items seen so far”; it holds initially and after each step, so at the end best is the maximum.

Practice

Write invariants and tests for functions that reverse a list in place and remove duplicates from a sorted list.

Continue in the learning spaceEnrol to open every lesson, track your progress, hand in work for faculty review and ask your tutor.Enrol — One-to-One