• edited by
4,510 views
17 17 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$

2 Answers

Best answer
28 28 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 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:
Position:
Show:

Related questions

25 25 votes
4 answers 4 answers
5.8k
5.8k views
Misbah Ghaya asked Oct 10, 2015
5,751 views
Consider the program where $a, b$ are integers with $b 0$.x:=a; y:=b; z:=0; while y 0 do if odd (x) then z:= z + x; y:= y - 1; else y:= y % 2; x:= 2 * x; fiInvariant of...
16 16 votes
2 2 answers
2.5k
2.5k views
Arjun asked Oct 10, 2015
2,529 views
Consider the following computation rules. Parallel-outermost rule: Replace all the outermost occurrences of F (i.e., all occurrences of F which do not occur as arguments ...
13 13 votes
2 answers 2 answers
6.4k
6.4k views
Arjun asked Dec 18, 2018
6,355 views
Consider the following program fragment:var x, y: integer; x := 1; y := 0; while y < x do begin x := 2*x; y := y+1 end;For the above fragment , which of the following is ...
21 21 votes
5 answers 5 answers
4.4k
4.4k views
go_editor asked Dec 23, 2016
4,400 views
Consider the following psuedocode fragment, where $y$ is an integer that has been initialized.int i=1 int j=1 while (i<10): j=j*i i=i+1 if (i==y): break end if end whileC...