#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....?

Answer Posted / 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       View All Answers


Please Help Members By Posting Answers For Below Questions

What is unary operator?

656


Which is not valid in C a) class aClass{public:int x;}; b) /* A comment */ c) char x=12;

603


What is a global variable in c?

587


What was noalias and what ever happened to it?

590


Why do we use namespace feature?

577






How to Throw some light on the splay trees?

617


I need a sort of an approximate strcmp routine?

655


What is echo in c programming?

553


What are header files why are they important?

574


write a proram to reverse the string using switch case?

2461


hai iam working in sap sd module for one year and working in lumax ind ltd in desp department but my problem is i have done m.b.a in hr/marketing and working sap sd there is any combination it. can you give right solution of my problem. and what can i do?

1654


why return type of main is not necessary in linux

1697


How do you determine a file’s attributes?

598


Write the program that calculates and prints the average of several integers. Assume that the last value read is sentinel 9999.

3118


Explain what standard functions are available to manipulate strings?

608