The Wayback Machine - https://web.archive.org/web/20240927020933/https://www.geeksforgeeks.org/practice-questions-for-recursion-set-2/
Open In App

Practice Questions for Recursion | Set 2

Last Updated : 25 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Explain the functionality of the following functions. 

Question 1 

C++




/* 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);
}


Java




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


Python3




# Assume that n is greater than or equal to 1 */
def fun1(n):
    if(n == 1):
        return 0
    else:
        return 1 + fun1(n//2)


C#




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


Javascript




<script>
 
/* Assume that n is greater than or equal to 1 */
function fun1(n)
{
    if (n == 1)
        return 0
    else
        return 1 + fun1(Math.floor(n / 2))
}
</script>


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 

C++




/* Assume that n is greater than or equal to 0 */
void fun2(int n)
{
if(n == 0)
    return;
 
fun2(n/2);
cout << n%2 << endl;
}


C




/* 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);
} 


Java




/* Assume that n is greater than or equal to 1 */
static void fun2(int n)
{
if(n == 0)
    return;
  
fun2(n/2);
System.out.println(n%2);
}


Python3




# Assume that n is greater than or equal to 0 */
def fun2(n):
    if(n == 0):
        return
     
    fun2(n // 2)
    print(n % 2, end="")


C#




void fun2(int n)
{
if(n == 0)
    return;
   
fun2(n/2);
Console.Write(n%2);
}


Javascript




<script>
 
// Assume that n is greater than or equal to 1
function fun2(n)
{
    if (n == 0)
        return;
     
    fun2(Math.floor(n / 2));
    document.write(n % 2 + " ")
}
</script>


Auxiliary Space: O(log2N), due to recursion call stack

Time Complexity: O(log N)

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

Note: 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. 



Previous Article
Next Article

Similar Reads

Practice Questions for Recursion | Set 1
Explain the functionality of the following functions. Question 1 C/C++ Code int fun1(int x, int y) { if (x == 0) return y; else return fun1(x - 1, x + y); } C/C++ Code int fun1(int x, int y) { if (x == 0) return y; else return fun1(x - 1, x + y); } Java Code static int fun1(int x, int y) { if (x == 0) return y; else return fun1(x - 1, x + y); } C/C
5 min read
Practice Questions for Recursion | Set 4
Question 1 Predict the output of the following program. C/C++ Code #include <iostream> using namespace std; void fun(int x) { if(x > 0) { fun(--x); cout << x <<" "; fun(--x); } } int main() { int a = 4; fun(a); return 0; } // This code is contributed by SHUBHAMSINGH10 C/C++ Code #include<stdio.h> void fun(int x)
6 min read
Practice Questions for Recursion | Set 5
Question 1Predict the output of the following program. What does the following fun() do in general? C/C++ Code #include <iostream> using namespace std; int fun(int a, int b) { if (b == 0) return 0; if (b % 2 == 0) return fun(a + a, b/2); return fun(a + a, b/2) + a; } int main() { cout << fun(4, 3) ; return 0; } // This code is contribut
5 min read
Practice Questions for Recursion | Set 7
Question 1 Predict the output of the following program. What does the following fun() do in general? C/C++ Code #include <iostream> using namespace std; int fun(int n, int* fp) { int t, f; if (n <= 2) { *fp = 1; return 1; } t = fun(n - 1, fp); f = t + *fp; *fp = t; return f; } int main() { int x = 15; cout << fun(5, &x) <<
4 min read
Practice Questions for Recursion | Set 3
Explain the functionality of below recursive functions. Question 1 C/C++ Code 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/C++ Code void fun1(int n) { int i = 0; if (n > 1) fun1(n-1); for (i = 0; i < n; i++) printf(" *
3 min read
Practice Questions for Recursion | Set 6
Question 1 Consider the following recursive C function. Let len be the length of the string s and num be the number of characters printed on the screen. Give the relation between num and len where len is always greater than 0. [GFGTABS] C++ void abc(char *s) { if(s[0] == '\0') return; abc(s + 1); abc(s + 1); cout << s[0]; } C void abc
4 min read
Practice questions for Linked List and Recursion
Assume the structure of a Linked List node is as follows. C/C++ Code struct Node { int data; struct Node *next; }; // This code is contributed by SHUBHAMSINGH10 C/C++ Code struct Node { int data; struct Node *next; }; Java Code static class Node { int data; Node next; }; // This code is contributed by shubhamsingh10 C/C++ Code class Node: def __ini
11 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Permutation and Combination Practice Questions | Set 1
Permutations and combinations (PnC) are fundamental concepts in combinatorics used to count arrangements and selections of objects. Permutations refer to the different ways of arranging a set of items where order matters. For example, the arrangement of letters in a word or the order of runners finishing a race.Combinations, on the other hand, invo
5 min read
Practice Questions on Huffman Encoding
Huffman Encoding is an important topic from GATE point of view and different types of questions are asked from this topic. Before understanding this article, you should have basic idea about Huffman encoding. These are the types of questions asked in GATE based on Huffman Encoding. Type 1. Conceptual questions based on Huffman Encoding - Here are t
4 min read
Practice questions on Height balanced/AVL Tree
AVL tree is binary search tree with additional property that difference between height of left sub-tree and right sub-tree of any node can’t be more than 1. Here are some key points about AVL trees: If there are n nodes in AVL tree, minimum height of AVL tree is floor(log2n).If there are n nodes in AVL tree, maximum height can’t exceed 1.44*log2n.I
4 min read
Practice questions on Arrays
In this article, we will discuss some important concepts related to arrays and problems based on that. Before understanding this, you should have basic idea about Arrays. Type 1. Based on array declaration - These are few key points on array declaration: A single dimensional array can be declared as int a[10] or int a[] = {1, 2, 3, 4}. It means spe
6 min read
Practice questions on Strings
String is an important topic from GATE exam point of view. We will discuss key points on strings as well different types of questions based on that. There are two ways to store strings as character array (char p[20]) or a pointer pointing to a string (char* s = “string”), both of which can be accessed as arrays. Assuming p as character array and s
4 min read
Mathematics | Graph theory practice questions
Problem 1 - There are 25 telephones in Geeksland. Is it possible to connect them with wires so that each telephone is connected with exactly 7 others. Solution - Let us suppose that such an arrangement is possible. This can be viewed as a graph in which telephones are represented using vertices and wires using the edges. Now we have 25 vertices in
4 min read
Practice Questions on Time Complexity Analysis
Prerequisite: Analysis of Algorithms1. What is the time, and space complexity of the following code: [GFGTABS] CPP int a = 0, b = 0; for (i = 0; i < N; i++) { a = a + rand(); } for (j = 0; j < M; j++) { b = b + rand(); } Java int a = 0, b = 0; for (i = 0; i < N; i++) { a = a + Math.random(); } for (j = 0; j < M; j++) { b = b + Math.rand
8 min read
Juggler Sequence | Set 2 (Using Recursion)
Juggler Sequence is a series of integer number in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation : [Tex]a_{k+1}=\begin{Bmatrix} \lfloor a_{k}^{1/2} \rfloor & for \quad even \quad a_k\\ \lfloor a_{k}^{3/2} \rfloor & for \q
4 min read
Product of 2 numbers using recursion | Set 2
Given two numbers N and M. The task is to find the product of the 2 numbers using recursion.Note: The numbers can be both positive or negative. Examples: Input : N = 5 , M = 3 Output : 15 Input : N = 5 , M = -3 Output : -15 Input : N = -5 , M = 3 Output : -15 Input : N = -5 , M = -3 Output:15 A recursive solution to the above problem for only posit
8 min read
Count Set-bits of number using Recursion
Given a number N. The task is to find the number of set bits in its binary representation using recursion. Examples: Input : 21 Output : 3 21 represented as 10101 in binary representation Input : 16 Output : 1 16 represented as 10000 in binary representation Approach: First, check the LSB of the number.If the LSB is 1, then we add 1 to our answer a
4 min read
Sum of N-terms of geometric progression for larger values of N | Set 2 (Using recursion)
A Geometric series is a series with a constant ratio between successive terms. The first term of the series is denoted by a and the common ratio is denoted by r. The series looks like this:- [Tex]a, ar, ar^2, ar^3, ar^4,... [/Tex]The task is to find the sum of such a series, mod M. Examples: Input: a = 1, r = 2, N = 10000, M = 10000 Output: 8751 In
7 min read
Decode a string recursively encoded as count followed by substring | Set 2 (using Recursion)
An encoded string str is given. The pattern in which the string is encoded is as follows. <count>[sub_str] ==> The substring 'sub_str' appears count times. The task is to decode this string str. Examples: Input: str = "1[b]"Output: bExplanation: The substring 'b' is repeated 1 time. Input: str = "2[ab]"Output: ababExplanation: The substrin
9 min read
Repeat substrings of the given String required number of times | Set 2 (Recursion)
Given string str, the task is to repeat every substring of the string X number of times where X is the number composed of the consecutive digits present just after the substring in the original string. For example, if str = “g1e2ks1” then the resultant string will be “geeks”. Examples: Input: str = “2a10bd3”Output: aaaaaaaaaabdbdbdExplanation: Firs
7 min read
The Great Tree-List Recursion Problem.
Asked by Varun Bhatia. Question: Write a recursive function treeToList(Node root) that takes an ordered binary tree and rearranges the internal pointers to make a circular doubly linked list out of the tree nodes. The”previous” pointers should be stored in the “small” field and the “next” pointers should be stored in the “large” field. The list sho
1 min read
Inorder Tree Traversal without recursion and without stack!
Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. 1. Initialize current as root 2. While current
9 min read
Print 1 to 100 in C++ Without Loops and Recursion
We can print 1 to 100 without using loops and recursion using three approaches discussed below: 1) Template Metaprogramming: Templates in C++ allow non-datatypes also as parameters. Non-datatype means a value, not a datatype. Example: C/C++ Code // CPP Program to print 1 to 100 // without loops and recursion #include <iostream> using namespac
3 min read
Print ancestors of a given binary tree node without recursion
Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.For example, consider the following Binary Tree 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10 Following are different input keys and their ancestors in the above tree Input Key List of Ancestors ------------------------- 1 2 1 3 1 4 2 1 5 2 1
15 min read
Remove duplicates from a sorted linked list using recursion
Write a removeDuplicates() function which takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43->60. Algorithm: Traverse th
8 min read
Reverse a Doubly linked list using recursion
Given a doubly linked list. Reverse it using recursion. Original Doubly linked list Reversed Doubly linked list We have discussed Iterative solution to reverse a Doubly Linked List Algorithm: If list is empty, return Reverse head by swapping head->prev and head->next If prev = NULL it means that list is fully reversed. Else reverse(head->p
9 min read
Sum of natural numbers using recursion
Given a number n, find sum of first n natural numbers. To calculate the sum, we will use a recursive function recur_sum().Examples : Input : 3 Output : 6 Explanation : 1 + 2 + 3 = 6 Input : 5 Output : 15 Explanation : 1 + 2 + 3 + 4 + 5 = 15 Below is code to find the sum of natural numbers up to n using recursion : C/C++ Code // C++ program to find
3 min read
Postorder traversal of Binary Tree without recursion and without stack
Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The approach used is based on using an unordered set to k
15 min read
Product of 2 Numbers using Recursion
Given two numbers x and y find the product using recursion. Examples : Input : x = 5, y = 2 Output : 10 Input : x = 100, y = 5 Output : 500 Method 1) If x is less than y, swap the two variables value 2) Recursively find y times the sum of x 3) If any of them become zero, return 0 C/C++ Code // C++ Program to find Product // of 2 Numbers using Recur
4 min read
Article Tags :
Practice Tags :