The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+14 votes
1.3k 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$
asked in Algorithms by Boss (16.3k points)
edited by | 1.3k views

2 Answers

+20 votes
Best answer

See the following calling sequence:

Hence, answer is option C.

answered by Boss (23.4k points)
edited by
+2
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

Then how come we reverse the sign in each interation ?
0
Can anybody pls explain how the series values comes?
+1
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) 
+11 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
answered by Boss (19.9k points)
0
Why have u executed else part in 5th step I guess else if has to be executed since 10 which is divisible by 2.
+9

else if (n%2)

This will be true if n is NOT a multiple of 2. When n is a multiple of 2, n%2 returns 0 and if will be false. 

+1
Thank you sir.
0
how values are come i mean like 9,10,8.,16 etc.Anybody plz explain?
0
Can anybody plzz explain how this series values comes.
0
its clear now.
0
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....
Answer:

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
49,541 questions
54,083 answers
187,206 comments
70,992 users