Multiple choice

Evaluate the following:

int fn(int v) { if(v==1 || v==0) return 1; if(v%2==0) return fn(v/2)+2; else return fn(v-1)+3; } for fn(7);

  1. 10

  2. 11

  3. 1

  4. 0

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

Trace the recursion: fn(7) calls fn(6)+3. fn(6) calls fn(3)+2. fn(3) calls fn(2)+3. fn(2) calls fn(1)+2. fn(1) returns 1 (base case). Working backward: fn(2)=1+2=3, fn(3)=3+3=6, fn(6)=6+2=8, fn(7)=8+3=11. The function uses different increments for even (divide by 2, add 2) and odd (subtract 1, add 3) paths.