ProgrammingHardProduct company OA
In a binary search over int indices, why is mid = lo + (hi - lo) / 2 preferred to mid = (lo + hi) / 2?
- A. The first form rounds differently for negative indices
- B. The first form avoids a division, so it is faster
- C. lo + hi can exceed INT_MAX for large indices, and signed overflow is undefined behaviour
- D. The second form makes the loop run forever when lo equals hi
Correct answer: C. lo + hi can exceed INT_MAX for large indices, and signed overflow is undefined behaviour
Both give the same midpoint when nothing overflows, but lo + hi can overflow for indices above about INT_MAX / 2; hi − lo cannot, because it is never larger than hi. Both forms divide, and both handle lo == hi.
More C Programming questions
- What is printed? c int A[2][2] = {{1, 2}, {3, 4}}, B[2][2] = {{0, 1}, {1, 0}}, C[2][2] = {0}; for (int i = 0; i < 2; i++) for (int j = 0…
- When should a variable be declared volatile?
- What is printed? c void f(int a, int n) { if (n <= 1) return; a[n - 2] += a[n - 1]; f(a, n - 1); } int main(void) { int a[] = {1, 2, 3…
- With a 32-bit unsigned int x, which expression has undefined behaviour?
- What is printed? c char s[] = "7392"; int n = 0; for (int i = 0; s[i]; i++) n = n 10 + (s[i] - '0'); printf("%d %d", n % 1000, n / 100 %…
- What is printed? c int f(int n) { if (n == 0) return 0; return (n & 1) + f(n >> 1) 10; } int main(void) { printf("%d", f(13)); }