4

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;
}
Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
nsc010
  • 395
  • 3
  • 5
  • 12

3 Answers3

1

A loop invariant is a condition that must be true during every iteration of a loop. In this example, we are considering what are the possible values of the variable i. When the loop starts, the value of i is 0. On the last iteration of the loop, i is incremented to n at the beginning of the loop and then another calculation is done. Therefore, the value of i satisfies the condition 0<=i<=n during the execution of this loop.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
1

Because Post-Condition is i==n when the loop is left. Pre-Condition when entering the loop is i==0. Inside the loop i is counting up towards n. So the invariant is 0 <= i <= n.

I omitted the invariant parts for f in my exlanation. This is not really sufficient since the invariant must capture the correctness and the meaning of the loop.

private int n = 6;

public int fact(){
    int i = 0;
    int f = 1;

    /* loop invariant: 0 <= i <= n && f == i! */
    /* PRE: i == 0 && f == i! */
    while (i < n) {
        i = i + 1;
        f = f * i;
    }
    /* POST: i == n && f == i! */

    return f;
}
Fabian Barney
  • 14,219
  • 5
  • 40
  • 60
0

On the final iteration of the loop, i starts at five and then gets incremented to 6. i<n wouldn't hold upon completion of the final iteration. Remember, loop invariants musts hold at the beginning (the conditional) and the end (after the last statement) of each iteration.

Also note that it must be 0 <= i<=n rather than 0 < i<=n, since 0<i wouldn't hold at the end of the first iteration.

Phillip Schmidt
  • 8,805
  • 3
  • 43
  • 67