retagged by
487 views
9 votes
9 votes

Consider the following C code. Where $x$ and $y$ are unknown integers and have been initialized to values greater than $1.$

int i=1, j=0;
while (i<y) {
    j = j+i;
    i = i+1;
    if(i==x) break;
}


Which of the following statement(s) about the variables $i$ and $j$ must be true after execution of this program?

  1. $(j=y(y-1)/2 \wedge (i=y)) \vee ((j=x(x-1)/2)\wedge (i = x))$
  2. If $x > y,$ then $i = y$
  3. If $x > y,$ then $i = y-1$
  4. $(j=y(y+1)/2 \wedge (i=y)) \vee ((j=x(x+1)/2)\wedge (i = x))$
retagged by

1 Answer

7 votes
7 votes
  1. i is starting from 1, incrementing by 1 with each iteration of loop.
  2. j is starting from 0, j adds i to itself in each iteration of loop, i increments after being added to j. Thus, j = $\sum_{n=1}^{i-1}$ n.
  3. loop will end when i = whichever of x, y is smaller.
  1. Suppose, after exiting loop, i == x then

j = $\sum_{n=1}^{x-1}$ n = ( n (n+1) ) / 2 = ( (x-1) (x-1+1) ) / 2 = ( x (x-1) ) / 2.

  1. Suppose, after exiting loop, i == y then

j = $\sum_{n=1}^{y-1}$ n = ( n (n+1) ) / 2 = ( (y-1) (y-1+1) ) / 2 = ( y (y-1) ) / 2.

Option A : True. From 3, 4, 5.

Option B : True. From 3.

Option C : False. From 3.

Option D : False. From 3, 4, 5.

Answer :- A, B

Answer:

Related questions

9 votes
9 votes
3 answers
3
9 votes
9 votes
1 answer
4