edited by
6,533 views
0 votes
0 votes

Consider the following pseudo-code fragment, where $m$ is a non-negative integer that has been initialized:

$p=0$

$k=0$

while $(k<m)$

$p=p+2^k$

$k=k+1$

end while

Which of the following is a loop invariant for the while statement?

(Note: a loop invariant for a while statement is an assertion that is true each time the guard is evaluated during the execution of the while statement).

  1. $p=2^k-1$ and $0 \leq k < m$
  2. $p=2^{k+1}-1$ and $0 \leq k < m$
  3. $p=2^k-1$ and $0 \leq k \leq m$
  4. $p=2^{k+1}-1$ and $0 \leq k \leq m$
edited by

1 Answer

0 votes
0 votes
$k=0,p=0$

After $first$ iteration, $p=0+2^0=1,\,k=1$

After $n^{th}$ iteration, $p=2^0+2^1+...+2^{n-1}=2^{n}-1,k=n$

As, the loop will go for $m$ iterations, so, $0\leq k\leq m$

So, $(C)$ should be the answer

Related questions

1 votes
1 votes
0 answers
3
0 votes
0 votes
2 answers
4
Arjun asked Jan 2, 2019
4,385 views
Consider the graph shown below:Use Kruskal’s algorithm to find the minimum spanning tree of the graph. The weight of this minimum spanning tree is$17$$14$$16$$13$