🖨️ Printing Instructions: Press Ctrl/Cmd + P and select "Save as PDF".
1

Correctness & Loop Invariants

2

Learning Goals

3

Introduction to Correctness

4

Does it work?

5

Formal Verification

6

Preconditions vs Postconditions

7

Contracts

8

Loop Invariants

9

The Loop Invariant Concept

10

Three Properties

11

Example 1: Summing an Array

12
function Sum(A[0..n-1])
  sum = 0
  i = 0
  while i < n:
    sum = sum + A[i]
    i = i + 1
  return sum
13

Defining the Invariant

14

Proof: Initialization

15

Proof: Maintenance

16

Proof: Termination

17

Example 2: Finding Maximum

18
function FindMax(A[0..n-1])
  max_val = -infinity
  for i = 0 to n-1:
    if A[i] > max_val:
      max_val = A[i]
  return max_val
19

Invariant for Max

20

Initialization

21

Maintenance

22

Termination

23

Example 3: Insertion Sort

24

Insertion Sort Concept

25
for j = 1 to n-1:
  key = A[j]
  i = j - 1
  while i >= 0 and A[i] > key:
    A[i+1] = A[i]
    i = i - 1
  A[i+1] = key
26

Outer Loop Invariant

27

Initialization

28

Maintenance Step (Tricky)

29

Termination

30

Interactive: Insertion Sort

31

Inner Loop Correctness

32

Proving the Inner Loop

33

Correctness of Recursion

34

Mathematical Induction

35

Example: Factorial

36

Common Bugs

37

Off-by-one Errors

38

Infinite Loops

39

Practice: Find Bug 1

40
function BadSum(A, n)
  sum = 0
  i = 1          // Bug here?
  while i < n:
    sum = sum + A[i]
    i = i + 1
  return sum
41

Analysis of Bug 1

42

Practice: Find Bug 2

43
function BinarySearch(A, x)
  ... 
  if x < A[mid]:
     high = mid   // Bug here?
  else:
     low = mid
44

Analysis of Bug 2

45

Writing Your Own Proofs

46

Template for Assignment

47

Common Pitfalls & Anti-Patterns

48

Watch Out For...

49

Interactive Practice

50

Activity 1: Sum Array

51

Solution 1

52

Activity 2: Max Finding

53

Solution 2

54

Activity 3: Selection Sort

55

Solution 3

56

Activity 4: Binary Search

57

Solution 4

58

Interactive: Binary Search

59

Activity 5: Termination

60

Solution 5

61

Activity 6: Bubble Sort

62

Solution 6

63

All Interactive Demos

64

Supplementary Resources