ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int f(int *a, int n) {
    if (n == 1) return a[0];
    int m = f(a + 1, n - 1);
    return a[0] > m ? a[0] - m : m - a[0];
}
int main(void) {
    int a[] = {3, 8, 2, 7};
    printf("%d", f(a, 4));
}
  1. A. 4
  2. B. 6
  3. C. 2
  4. D. 0

Correct answer: D. 0

f folds from the right, taking absolute differences: f({7}) = 7, f({2, 7}) = 5, f({8, 2, 7}) = |8 − 5| = 3, f({3, 8, 2, 7}) = |3 − 3| = 0. Folding from the left instead (|3 − 8| = 5, |5 − 2| = 3, |3 − 7| = 4) gives the trap answer 4.

More C Programming questions

Exams that ask this topic