retagged by
1,820 views
2 votes
2 votes

Consider the following recursive C function that takes two arguments

unsigned int rer(unsigned int n, unsigned int r){
    if(n>0)return(n%r + rer(n/r,r));
    else retturn 0;
}

What is the return value of the function $rer$ when it is called as $rer(513,2)$?

  1. $9$
  2. $8$
  3. $5$
  4. $2$
retagged by

3 Answers

3 votes
3 votes

Option d) is correct


$rer(513,2)=1+rer(256,2)=2$

$rer(256,2)=0+rer(128,2)=1$

$rer(128,2)=0+rer(64,2)=1$

$rer(64,2)=0+rer(32,2)=1$

$rer(32,2)=0+rer(16,2)=1$

$rer(16,2)=0+rer(8,2)=1$

$rer(8,2)=0+rer(4,2)=1$

$rer(4,2)=0+rer(2,2)=1$

$rer(2,2)=0+rer(1,2)=1$

$rer(1,2)=1+rer(0,2)= 1$

$rer(0,2)=return \ 0$

1 votes
1 votes
If we observe it carefully,the code counts the no of 1's in the binary representation of the no 513,so we can write its binary representation and see how many 1's are there. It will come out to be 2
0 votes
0 votes

what you can observe from the above code is that n%2 will extract the last digit of n and n/2 will extract the first

(no. of digits in the binary representation of the number)-1

Binary representation of the number is 1000000001. It has 2 1s so addition of 1s will take place 2 times

so d)2

Answer:

Related questions

6 votes
6 votes
5 answers
2
Satbir asked Jan 13, 2020
3,832 views
What is the output of the code given below?# include<stdio.h int main() { char name[]="satellites"; int len; int size; len= strlen(name); size = sizeof(name); printf("%d"...
6 votes
6 votes
1 answer
3