GATE / CS ARCHIVE

GATE CSE 2006 / QUESTION 53

Merge-loop postconditions and output index

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2006 paper

GATE 2006, Q53 2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 53, GATE 2006: Sorted integer arrays a[0…n−1],b[0…m−1] have positive lengths. Array c has capacity n+m. Execute:
i=j=k=0;
while (i<n && j<m) {
  if (a[i]<b[j]) c[k++]=a[i++];
  else c[k++]=b[j++];
}
Which printed postcondition is valid?
I: if i=n, then j<m, k=n+j−1, and a[n−1]<b[j].
II: if j=m, then i<n, k=m+i−1, and b[m−1]≤a[i].
The −1 terms are retained exactly as reproduced in both sources.
Options:
(A) Only I
(B) Only II
(C) Either I or II, but not both
(D) Neither I nor II
Question 53, GATE 2006: Sorted integer arrays a[0…n−1],b[0…m−1] have positive lengths. Array c has capacity n+m. Execute:
i=j=k=0;
while (i<n && j<m) {
  if (a[i]<b[j]) c[k++]=a[i++];
  else c[k++]=b[j++];
}
Which printed postcondition is valid?
I: if i=n, then j<m, k=n+j−1, and a[n−1]<b[j].
II: if j=m, then i<n, k=m+i−1, and b[m−1]≤a[i].
The −1 terms are retained exactly as reproduced in both sources.
Options:
(A) Only I
(B) Only II
(C) Either I or II, but not both
(D) Neither I nor II
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. The loop starts i=j=k=0. Each iteration increments exactly one of i,j and also k, preserving k=i+j.

2. At termination, if i=n then j<m and k=n+j; the final extraction from a implies a[n−1]<b[j]. If j=m then i<n and k=m+i; the final extraction from b implies b[m−1]≤a[i].

3. Both printed assertions instead give k one less than these values. Hence neither assertion is correct: D.

4. This uses positive array lengths and defined array accesses, as intended by the example.

6. Teaching check: Initially k=i+j=0. Every loop iteration increments k and exactly one of i,j, so k=i+j remains true. At exit, replacing i by n or j by m yields k=n+j or k=m+i, directly contradicting the printed −1 regardless of the final comparison.

Original paper, page 7