Similar questions 3 more →
Control Flow & Loop Tracing
![Question 84, 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. }
For which input does it fail?
(A) Y=[1,2,3,4,5,6,7,8,9,10], x<10
(B) Y=[1,3,5,7,9,11,13,15,17,19], x<1
(C) Y=[2,2,2,2,2,2,2,2,2,2], x>2
(D) Y=[2,4,6,8,10,12,14,16,18,20], 2<x<20 and x even](../../assets/questions/CS-2008-Q84-1.webp)
![Question 84, 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. }
For which input does it fail?
(A) Y=[1,2,3,4,5,6,7,8,9,10], x<10
(B) Y=[1,3,5,7,9,11,13,15,17,19], x<1
(C) Y=[2,2,2,2,2,2,2,2,2,2], x>2
(D) Y=[2,4,6,8,10,12,14,16,18,20], 2<x<20 and x even](../../assets/questions/CS-2008-Q84-2.webp)
Your answer
Answer & solution
Answer: C (no official key was published)
1. With all entries equal to 2 and x>2, every comparison takes i=k. The interval evolves (i,j)=(0,9)→(4,9)→(6,9)→(7,9)→(8,9), then k remains 8 forever.
2. Y[k]≠x and i<j both stay true, so the program fails to terminate, option C. For A, all integer keys below 10 that are present (1 through 9) can be found and keys below 1 terminate as absent; B also shrinks j to zero and terminates absent; D contains only present even values strictly between its endpoints.