This is a question from a past exam paper.
Why does the loop invariant say i<=n
when the loop test says i<n
.
Is an appropriate answer: It says i<=n
as i
will equal n
on the failing condition of the while loop. Therefore the 6th iteration of i
will equal the n
value 6 on the failing condition. However, the while loop itself states i<n
as i
starts at 0 and will finish looping once i
is equal to 5.
private int n =6;
public int fact(){
int i = 0;
int f = 1;
/**loop invariant
* 0<=i<=n
* f=i!
*/
while(i<n){//loop test
i=i+1;
f=f*i;
}
return f;
}