edited by
2,749 views
16 votes
16 votes

Consider the following program for summing the entries of the array $b$: array $[0 .. N-1]$ of integers, where $N$ is a positive integer. (The symbol '$<>$' denotes 'not equal to').

var      
    i, s: integer;
Program
    i:= 0;
    s:= 0;
[*] while i <> N do
        s := s + b[i];
        i := i + 1;
    od

Which of the following gives the invariant that holds at the beginning of each loop, that is, each time the program arrives at point $[*]$ ?

  1. $s = \sum\limits^{N}_{j=0}b[j] \;\&\; 0 \leq i \leq N$
  2. $s = \sum\limits^{i=1}_{j=0}b[j] \;\&\; 0 \leq i < N$
  3. $s = \sum\limits^{i}_{j=0}b[j] \;\&\; 0 < i \leq N$
  4. $s = \sum\limits^{N}_{j=1}b[j] \;\&\; 0 \leq  i < N$
  5. $s = \sum\limits^{i-1}_{j=0}b[j] \;\&\; 0 \leq  i \leq N$
edited by

2 Answers

Best answer
26 votes
26 votes

Whenever we encounter the $[*]$, the variable $s$ holds the sum of all elements $b[0]$ to $b[i-1]$.

When we first enter the loop, $i=0$, and $s$ doesn't have any elements summed up.

When we last enter the loop, $i = (N-1)$ and $s$ contains the sum of elements $b[0]$ through $b[N-2]$.

We leave the loop when $i=N$, and $s$ gets the sum of elements $b[0]$ to $b[N-1]$

The only option that matches this behavior is option E.

$$s = \sum\limits^{i-1}_{j=0}b[j] \;\&\; 0 \leq  i \leq N$$

edited by
5 votes
5 votes
I think we can even ans the question without doing a single iteration.

see when we reach first time [*] at that time i=0,s=0

the only option matches with this behaviour is Option E. Remaining all options are storing atleast one elements sum in s.
Answer:

Related questions

12 votes
12 votes
2 answers
3