Practice Questions for Recursion | Set 3

Explain the functionality of below recursive functions.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

void fun1(int n)
{
   int i = 0;  
   if (n > 1)
     fun1(n-1);
   for (i = 0; i < n; i++)
     printf(" * ");
}

chevron_right


Answer: Total numbers of stars printed is equal to 1 + 2 + …. (n-2) + (n-1) + n, which is n(n+1)/2.



Question 2

filter_none

edit
close

play_arrow

link
brightness_4
code

#define LIMIT 1000
void fun2(int n)
{
  if (n <= 0)
     return;
  if (n > LIMIT)
    return;
  printf("%d ", n);
  fun2(2*n);
  printf("%d ", n);
}   

chevron_right


Answer: For a positive n, fun2(n) prints the values of n, 2n, 4n, 8n … while the value is smaller than LIMIT. After printing values in increasing order, it prints same numbers again in reverse order. For example fun2(100) prints 100, 200, 400, 800, 800, 400, 200, 100.
If n is negative, the function is returned immediately.

Please write comments if you find any of the answers/codes incorrect, or you want to share more information about the topics discussed above.



My Personal Notes arrow_drop_up

Improved By : hoangdang



Article Tags :
Practice Tags :


4


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