edited by
8,906 views
25 votes
25 votes

What is the output printed by the following program?

#include <stdio.h>

int f(int n, int k) {
    if (n == 0) return 0;
    else if (n % 2) return f(n/2, 2*k) + k;
    else return f(n/2, 2*k) - k;
}

int main () {
    printf("%d", f(20, 1));
    return 0;
}
  1. $5$
  2. $8$
  3. $9$
  4. $20$
edited by

3 Answers

Best answer
34 votes
34 votes

See the following calling sequence. Boxed values show the return values.

Hence, answer is option C.

edited by
12 votes
12 votes
The sequence has to be followed.

6.) f(20,1) = 9.

5.) f(10,2) - 1 = 9

4.) f(5,4) - 2 = 10

3.) f(2,8) + 4 = 12

2.) f(1,16) - 8 = 8

1.) f(0,32) + 16 = 16
Answer:

Related questions