Statement for Linked Answer Questions 84 and 85: Consider the following C…
GATE · 2008 · CSModified — slightly modified from the official paper; see the solution
Statement for Linked Answer Questions 84 and 85: Consider the following C program that attempts to locate an element x in an array Y[] using binary search. The program is erroneous.
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. }
Question 85: The correction needed in the program to make it work properly is
- A.
Change line 6 to: if (Y[k] < x) i = k+1; else j = k-1; and line 7 to: } while ((Y[k] != x) && (i <= j));
- B.
Change line 6 to: if (Y[k] < x) i = k - 1; else j = k+1;
- C.
Change line 6 to: if (Y[k] <= x) i = k; else j = k;
- D.
Change line 7 to: } while ((Y[k] == x) && (i < j));
Attempted by 100 students.
Sign up free to check your answer
Sign up freeLoading lesson…