#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 / 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 |
What are variables c?
An array name contains base address of the array. Can we change the base address of the array?
What are 'near' and 'far' pointers?
What is the difference between far and near ?
which do you prefer C or Pascal?
will the program compile? int i; scanf(ā%dā,i); printf(ā%dā,i);
Here is a good puzzle: how do you write a program which produces its own source code as output?
Program to find the value of e raised to power x using while loop
What is difference between arrays and pointers?
related to rdbms query .
What is variable in c with example?
Write a program to find the given number is odd or even without using any loops(if,for,do,while)