ProgrammingVery hardGATE CS · Product company OA
What is printed?
What is printed?
int a[] = {2, 4, 6, 8, 10, 12, 14}, lo = 0, hi = 6, steps = 0, x = 7;
while (lo <= hi) {
int m = (lo + hi) / 2;
steps++;
if (a[m] == x) break;
if (a[m] < x) lo = m + 1; else hi = m - 1;
}
printf("%d %d %d", steps, lo, hi);- A. 3 2 2
- B. 3 3 3
- C. 4 3 2
- D. 3 3 2
Correct answer: D. 3 3 2
m = 3 (8 > 7) sets hi = 2; m = 1 (4 < 7) sets lo = 2; m = 2 (6 < 7) sets lo = 3, and lo > hi ends the search. After a failed search lo is the index where x would be inserted (3) and hi = lo − 1.
More C Programming questions
- What is printed? c struct E { char n; int age; } e[] = {{'A', 30}, {'B', 25}, {'C', 35}}; int cmp(const void x, const void y) { return…
- What is printed? c #define SCALE(x) (x factor) int factor = 3; int f(void) { int factor = 10; return SCALE(2); } int main(void) {…
- What is printed? c int i = 0, n = 0; while (i++, i < 4) n += i; printf("%d %d", n, i);
- What is the range of values of a signed 8-bit two's-complement integer?
- What is printed? c unsigned x = 8; if (x & (x - 1) == 0) puts("pow2"); else puts("not");
- What is printed? c int m[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, r[3][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++)…