Proving correctness for programs

The normal method for proving program correctness depends on the type of program that you are looking at. For simple tail-recursive programs - that is, those which are basically
a few simple steps followed by recursive calls, the proof is often a simple inductive proof.
For example, suppose we look at the following program whose purpose is to calculate
n! for non-negative n and for n small enough that n! is representable by ordinary
int variables.

    int fact(int n)
    {
        if(n<=1) return(1);
        else return(n*fact(n-1));
    }

The proof works as follows:

(Basis) The program calculates n! properly for n=0 or n=1 since 0!=1!=1.
(Induction) Suppose that n! is representable by ordinary int variables and that for k<n fact(k) returns k! (Not that since n! is increasing, if n is representable, so isk! for k<n.)
Then fact(n) returns n*fact(n-1) and since n-1<n, fact(n-1)=(n-1)! so we see that fact(n) returns n*(n-1)!=n*(n-1)*(n-2)*...*1 (by the definition of factorial) and this is, in fact,
n!. QED (QED is an acronym for latin Quid Errat Demonstratum which means, essentially, it is properly demonstrated. Mathematicians love using it at the end of proofs. So do computer scientists.)

Let us try another. Note that Fn , the nth Fibonnacci number is defined by the recurrence relationship F0=F1=1 and Fn=Fn-1+Fn-2 . Suppose the following is a program to compute the nth Fibonnacci number:

    int Fib(int n)
    {
        if(n<=1) return(1);
        else return(Fib(n-1)+Fib(n-2));
    }

Let us prove that Fib(n) returns Fn when n is nonnegative and such that Fn can be represented in an int.

(Basis) True for n=0 or n=1 since in both cases it returns 1 and F0=F1=1.
(Induction) Suppose n is such that Fn can be represented in an int and n>1. Inductively suppose that for k<n, the function Fib works correctly - i.e., Fib(k)=Fk for k<n. Then let us compute Fib(n). It will return Fib(n-1)+Fib(n-2) and by the inductive hypothesis, this is Fn-1+Fn-2 since n-1<n and n-2<n. But, by definition, Fn=Fn-1+Fn-2 so Fib(n) returns Fn and we have shown the result by induction. QED

Next

Lynn Ziegler, lziegler@cs.csbsju.edu

 

 
 
 
 
 
 
 
 
 

W3C Wilbur Checked!Another HTML Validation Site