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 return 0; } What is the return value of the function rer when it is called as rer (513, 2)?

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 return 0; } What is the return value of the function rer when it is called as rer (513, 2)? Correct Answer 2

Concept –

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

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

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

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

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

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

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

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

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

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

rer(0, 2) = 0

Now, adding the values in bottom up function after returning from rer(0, 2), we get,

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

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

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

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

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

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

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

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

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

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

Hence, the function returns 2 i.e., sum of bits when 513 represented in binary.

Related Questions