ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int ways(int *a, int n, int t) {
    if (t == 0) return 1;
    if (n == 0 || t < 0) return 0;
    return ways(a + 1, n - 1, t - a[0]) + ways(a + 1, n - 1, t);
}
int main(void) {
    int a[] = {1, 2, 3, 4, 5};
    printf("%d", ways(a, 5, 6));
}
  1. A. 4
  2. B. 2
  3. C. 10
  4. D. 3

Correct answer: D. 3

Each call either takes a[0] or skips it, so ways counts subsets of {1, 2, 3, 4, 5} that add up to 6: {1, 5}, {2, 4} and {1, 2, 3}. Order does not matter because each element is considered once, in sequence.

More C Programming questions

Exams that ask this topic