#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
What is array of structure in c programming?
Why c is known as a mother language?
What are compound statements?
What is static function in c?
Which are low level languages?
What is define c?
What are the preprocessor categories?
When I set a float variable to, say, 3.1, why is printf printing it as 3.0999999?
Write a code to remove duplicates in a string.
Explain the use of fflush() function?
Why is c called a structured programming language?
What is cohesion and coupling in c?
What is the difference between printf and scanf )?
What is static and volatile in c?
Are the expressions * ptr ++ and ++ * ptr same?