(Translated by https://www.hiragana.jp/)
Practice Questions for Recursion | Set 3 - GeeksforGeeks
Open In App

Practice Questions for Recursion | Set 3

Last Updated : 20 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Explain the functionality of below recursive functions. 

Question 1 

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

// This code is contributed by shubhamsingh10
C Java Python C# JavaScript

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

Time complexity: O(n2)
Auxiliary Space:  O(n), due to recursion call stack

Question 2

C++
#define LIMIT 1000
void fun2(int n)
{
  if (n <= 0)
     return;
  if (n > LIMIT)
    return;
  cout << n <<" ";
  fun2(2*n);
  cout << n <<" ";
}

// This code is contributed by shubhamsingh10
C Java Python C# JavaScript

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. 

Time complexity: O(log(limit/n)).
Auxiliary Space:  O(log(limit/n)), due to recursion call stack


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


Article Tags :
Practice Tags :

Similar Reads