Similar questions 3 more →
Control Flow & Loop Tracing
![Question 85, GATE 2008: This erroneous historical C binary-search function uses integer division:
1. f(int Y[10], int x) {
2. int i,j,k;
3. i=0; j=9;
4. do {
5. k=(i+j)/2;
6. if(Y[k]<x) i=k; else j=k;
7. } while((Y[k]!=x) && (i<j));
8. if(Y[k]==x) printf("x is in the array");
9. else printf("x is not in the array");
10. }
Which correction makes the program work properly?
(A) Replace line 6 with if(Y[k]<x) i=k+1; else j=k−1;
(B) Replace line 6 with if(Y[k]<x) i=k−1; else j=k+1;
(C) Replace line 6 with if(Y[k]<=x) i=k; else j=k;
(D) Replace line 7 with } while((Y[k]==x) && (i<j));](../../assets/questions/CS-2008-Q85-1.webp)
![Question 85, GATE 2008: This erroneous historical C binary-search function uses integer division:
1. f(int Y[10], int x) {
2. int i,j,k;
3. i=0; j=9;
4. do {
5. k=(i+j)/2;
6. if(Y[k]<x) i=k; else j=k;
7. } while((Y[k]!=x) && (i<j));
8. if(Y[k]==x) printf("x is in the array");
9. else printf("x is not in the array");
10. }
Which correction makes the program work properly?
(A) Replace line 6 with if(Y[k]<x) i=k+1; else j=k−1;
(B) Replace line 6 with if(Y[k]<x) i=k−1; else j=k+1;
(C) Replace line 6 with if(Y[k]<=x) i=k; else j=k;
(D) Replace line 7 with } while((Y[k]==x) && (i<j));](../../assets/questions/CS-2008-Q85-2.webp)
![Question 85, GATE 2008: This erroneous historical C binary-search function uses integer division:
1. f(int Y[10], int x) {
2. int i,j,k;
3. i=0; j=9;
4. do {
5. k=(i+j)/2;
6. if(Y[k]<x) i=k; else j=k;
7. } while((Y[k]!=x) && (i<j));
8. if(Y[k]==x) printf("x is in the array");
9. else printf("x is not in the array");
10. }
Which correction makes the program work properly?
(A) Replace line 6 with if(Y[k]<x) i=k+1; else j=k−1;
(B) Replace line 6 with if(Y[k]<x) i=k−1; else j=k+1;
(C) Replace line 6 with if(Y[k]<=x) i=k; else j=k;
(D) Replace line 7 with } while((Y[k]==x) && (i<j));](../../assets/questions/CS-2008-Q85-3.webp)
Answer & solution
Answer: No fully correct option; A repairs the update but is incomplete (no official key was published)
1. Option A changes the bounds to i=k+1 or j=k−1, removing the nonprogress bug in Q84. But line 7 still tests i<j, so it can stop before examining a remaining singleton. Counterexample: Y=[1,2,3,4,5,6,7,8,9,10], x=4.
2. With A, k=4 gives j=3; k=1 gives i=2; k=2 gives i=3. Now i=j=3, so the loop exits and wrongly reports absent because its last examined value was Y[2]=3. A complete repair also changes the continuation bound to i<=j (while retaining the found test), or rewrites the usual while(i<=j) search.
3. B expands bounds, C still stalls on many absent keys, and D continues on equality instead of inequality. Thus A is the likely intended correction, but none alone makes the displayed program generally correct.