6,616 views

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$

Answer should be -15 which is not given in the options, observe carefully the value of k
edited
int f(int n, int k) {
if (n == 0) return 0;
else if (n % 2) return f(n/2, 2*k) + k; // This condition is true when n%2 is 1
else return f(n/2, 2*k) - k; // otherwise
}


bthebestSelf you are doing n%2 = 0 as true, then you get -15 as the answer. If you doing n%2 = 0 as false then you get 9 as an answer :)

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

How is it f (10,2)-1 ??? When its given for every even N we have +k and for every odd n we have -k

Can anybody pls explain how the series values comes?
it is if (n % 2) return f(n/2, 2*k) + k
which means n%2 must be 1 for condition to be true.I think you mistook it for if (n%2==0) 
ya, its ok. you mistook, you will never mistook it agin.

ok keep it up

vamsi
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

Can anybody plzz explain how this series values comes.
its clear now.
Else if (n%2) when n is multiple of 2 it will be like else if (0) therefore it will return false and will execute next else and   return f(n/2,2*k) - K....

9 will be printed.