#include<stdio.h>

int f(int,int);
int main()
{

printf("%d",f(20,1));
return 0;
}
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;
}
how this program is working and generating output as 9....?



#include<stdio.h> int f(int,int); int main() { printf("%d",f(20,1)); re..

Answer / kodam

n=20, k =1
if, else if false. so it will call
f(n/2,2*k)-k ==> f(10,2)-1
if, else if false
f(n/2,2*k)-k ==> f(5, 4)-2
if is false. else if is true
f(n/2,2*k)+k ==> f(2, 8)+4
if, else if false
f(n/2,2*k)-k ==> f(1, 16)-8
if is false. else if is true
f(n/2,2*k)+k ==> f(0, 32)+16
now n is zero.

output
------
-1-2+4-8+16 = 9

Is This Answer Correct ?    7 Yes 0 No

Post New Answer

More C Interview Questions

What are variables c?

0 Answers  


An array name contains base address of the array. Can we change the base address of the array?

4 Answers   NMIMS, Wipro,


What are 'near' and 'far' pointers?

0 Answers  


What is the difference between far and near ?

0 Answers  


which do you prefer C or Pascal?

1 Answers  






will the program compile? int i; scanf(ā€œ%dā€,i); printf(ā€œ%dā€,i);

3 Answers  


Here is a good puzzle: how do you write a program which produces its own source code as output?

0 Answers  


Program to find the value of e raised to power x using while loop

5 Answers   IBM, N Tech,


What is difference between arrays and pointers?

0 Answers  


related to rdbms query .

2 Answers  


What is variable in c with example?

1 Answers  


Write a program to find the given number is odd or even without using any loops(if,for,do,while)

4 Answers   CNC, Gokul,


Categories