edited by
3,708 views
12 votes
12 votes

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 a loop invariant ?

  1. $x=y+1$
  2. $x=(y+1)^2$
  3. $x=(y+1)2^y$
  4. $x=2^y$
  5. None of the above, since the loop does not terminate
edited by

2 Answers

Best answer
17 votes
17 votes

loop invariant is any condition which is true for the start of the loop, for every iteration of the loop and for the exit of the loop.

Before 1st iterations values of $(x,y)$ are $(1,0)$

After 1st iteration values of $x$ and $y$ are $(2,1)$

After 2nd iteration values of $x$ and $y$ are $(4,2)$

After 3rd iteration values of $x$ and $y$ are $(8,3)$

$\vdots$

After nth iteration values of $x$ and $y$ are $(2^n,n)$

This loop will not terminate and that means we need not worry about the condition when loop exits $(p\to q$ is TRUE if $p$ is false) So $E$ is false

$D$ is the right option

selected by
0 votes
0 votes

Best way to solve is by Dry run

See the pattern yourself

 

Answer:

Related questions

2.6k
views
3 answers
12 votes
Arjun asked Dec 18, 2018
2,572 views
Given the following pseudocode for function $\text{printx()}$ below, how many times is $x$ printed if we execute $\text{printx(5)}?$void printx(int n) { if(n==0){ printf...
2.0k
views
2 answers
5 votes
Arjun asked Dec 18, 2018
2,043 views
Consider the following program fragment:var a,b : integer; procedure G(c,d: integer); begin c:=c-d; d:=c+d; c:=d-c end; a:=2; b:=3; G(a,b);If both parameters to $G$ are p...
3.2k
views
5 answers
20 votes
go_editor asked Dec 23, 2016
3,218 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...
3.4k
views
3 answers
23 votes
makhdoom ghaya asked Oct 10, 2015
3,431 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...