Practice Questions for Recursion | Set 2

Explain the functionality of following functions.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Assume that n is greater than or equal to 1 */
int fun1(int n)
{
  if(n == 1)
     return 0;
  else
     return 1 + fun1(n/2);

chevron_right


Answer: The function calculates and returns log2floor. For example, if n is between 8 and 15 then fun1() returns 3. If n is between 16 to 31 then fun1() returns 4.



Question 2

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Assume that n is greater than or equal to 0 */
void fun2(int n)
{
  if(n == 0)
    return;
  
  fun2(n/2);
  printf("%d", n%2);
}  

chevron_right


Answer: The function fun2() prints binary equivalent of n. For example, if n is 21 then fun2() prints 10101.

Note that above functions are just for practicing recursion, they are not the ideal implementation of the functionality they provide.

Please write comments if you find any of the answers/codes incorrect.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.