Proof of Correctness: factorial.c

prev     next

Step9: f use to be (y-1)!, but it was just multiplied by y.

int factorial(int x) {
int f, y;
  // PRE-CONDITION: x >= 0              
 
  y = 1;
  // y = 1  
  
  f = 1;
  // y = 1 and f = 1
  
  // INVARIANT: f = (y-1)! and y <= x + 1    
  
  while (y <= x) {
    
    // f = (y-1)! and y <= x   
    
    f = f * y;
    
    // f = y! and y <= x       
    
    y = y + 1;
    
  
  } // end while
 
  // INVARIANT: f = (y-1)! and y <= x + 1 and EXIT: y > x
  // f = (y-1)! and y = x + 1      
  // POST-CONDITION: f = x!        

  return f;
}