Docsity

Loop Invariants - Discrete Math - Lecture Slides, Slides of Discrete Mathematics

Partial preview of the text

Download Loop Invariants - Discrete Math - Lecture Slides and more Slides Discrete Mathematics in PDF only on Docsity!

Discrete aths

  • Objectives
    • to show the use of induction for proving properties of code involving loops
      • use induction to prove that functions work
    • introduce pre- and post- conditions, loop termination

2. Loop Invariants

Overview

1. What is a Loop Invariant?

2. Three simple examples

  • they involve while loops

3. Selection Sort

4. Further Information

  • A loop invariant is typically written as an

inductive statement S(n), where n is some

changing element of the loop. For

example:

  • the loop counter/index
  • a loop variable which changes on each iteration

2.1. Example 1

int square(int val) { int result = 0; int counter = 0; while (counter < val) { result += val; counter++; } return result; }

Problem: does this function work?

The Loop Invariant

  • To make the proof clearer, let countern and

resultn be the values of counter and result

after passing round the loop n times.

  • Loop invariant S(n):

resultn = val * countern

  • is this true in the loop for all n >= 0?

Basis

  • S(0) is when the loop has not yet been

executed.

  • result 0 = counter 0 = 0
  • So:

result 0 = val * counter 0

  • which means that S(0) is true.
  • Substitute the rhs of (1) for the 1st operand of

the rhs of (2):

resultk+1 = (val * counter (^) k) + val = val * (counterk + 1) = val * counterk+1 (by using (3))

  • this is S(k+1), which is therefore true.

continued Docsity.com

  • For the loop, we now know:
    • S(0) is true
    • S(k) --> S(k+1) is true
  • That means S(n) is true for all n >= 0
    • for all n >= 0, the loop invariant is true: resultn = val * countern

2.2. Example 2

int exp(int b, int m) // return b m { int res = 1; while (m > 0) { res = res * b; m = m - 1; } return res; }

Problem: does this function work?

Pre- and Post-conditions

  • We assume b and m are non-negative

integers

  • the preconditions for this function
  • exp() always returns bm
  • the postcondition
  • we will use the loop invariant to show that this is true

Basis

  • S(0) is when the loop has not yet been

executed.

  • res 0 = 1; m 0 = m
  • So:

1 * bm^ = bm

  • which means that S(0) is true.

Induction

  • We assume that S(k) is true for some

k >= 0, which means that:

res (^) k * bmk^ = bm^ (1)

  • After one more pass through the loop:

res (^) k+1 = res (^) k * b (2) mk+1 = mk - 1 (3)

continued Docsity.com

  • S(k+1) is:

res k+1 * bmk+1^ = bm^ (4)

  • So we have shown S(k+1) is true by

using S(k).

continued Docsity.com

  • For the loop, we now know:
    • S(0) is true
    • S(k) --> S(k+1) is true
  • That means S(n) is true for all n >= 0
    • for all n >= 0, the loop invariant is true: res (^) n * bmn^ = bm