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

Practice Questions for Recursion | Set 4

Last Updated : 21 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Question 1 
Predict the output of the following program. 

C++




#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




#include<stdio.h>
void fun(int x)
{
  if(x > 0)
  {
     fun(--x);
     printf("%d\t", x);
     fun(--x);
  }
}
 
int main()
{
  int a = 4;
  fun(a);
  getchar();
  return 0;
}


Java




import java.io.*;
 
class GFG {
 
    static void fun(int x)
    {
        if(x > 0)
        {
            fun(--x);
            System.out.print(x + " ");
            fun(--x);
        }
    }
     
    public static void main (String[] args)
    {
        int a = 4;
        fun(a);
    }
}
 
// This code is contributed by SHUBHAMSINGH10


Python3




def fun(x):
     
    if(x > 0):
        x -= 1
        fun(x)
        print(x , end=" ")
        x -= 1
        fun(x)
         
# Driver code
a = 4
fun(a)
 
# This code is contributed by SHUBHAMSINGH10


C#




using System;
 
class GFG{
 
    static void fun(int x)
    {
        if(x > 0)
        {
            fun(--x);
            Console.Write(x + " ");
            fun(--x);
        }
    } 
     
    static public void Main ()
    {
        int a = 4;
        fun(a); 
    }
}
// This code is contributed by SHUBHAMSINGH10


Javascript




<script>
 
function fun(x)
{
    if (x > 0)
    {
        x -= 1
        fun(x)
        document.write(x + " ");
        x -= 1
        fun(x)
    }   
}
 
// Driver code
let a = 4;
fun(a)
 
// This code is contributed by bobby
 
</script>


Output: 

0 1 2 0 3 0 1

 

Time complexity: O(2n)

Auxiliary Space: O(n), since n extra space has been taken.
 

 
                   fun(4);
                   /
                fun(3), print(3), fun(2)(prints 0 1)
               /
           fun(2), print(2), fun(1)(prints 0)
           /
       fun(1), print(1), fun(0)(does nothing)
       /
    fun(0), print(0), fun(-1) (does nothing)

Question 2 
Predict the output of the following program. What does the following fun() do in general? 

C++




#include <iostream>
using namespace std;
  
int fun(int a[],int n)
{
  int x;
  if(n == 1)
    return a[0];
  else
    x = fun(a, n - 1);
  if(x > a[n - 1])
    return x;
  else
    return a[n - 1];
}
 
int main()
{
  int arr[] = {12, 10, 30, 50, 100};
  cout << " " << fun(arr, 5) <<" ";
  getchar();
  return 0;
}
 
// This code is contributed by shubhamsingh10


C




#include<stdio.h>
int fun(int a[],int n)
{
  int x;
  if(n == 1)
    return a[0];
  else
    x = fun(a, n-1);
  if(x > a[n-1])
    return x;
  else
    return a[n-1];
}
 
int main()
{
  int arr[] = {12, 10, 30, 50, 100};
  printf(" %d ", fun(arr, 5));
  getchar();
  return 0;
}


Java




import java.io.*;
  
class GFG {
  
    static int fun(int a[],int n)
    {
        int x;
        if(n == 1)
            return a[0];
        else
            x = fun(a, n - 1);
        if(x > a[n - 1])
            return x;
        else
            return a[n - 1];
    }
     
    public static void main (String[] args)
    {
        int arr[] = {12, 10, 30, 50, 100};
        System.out.println(" "+fun(arr, 5)+" ");
    }
}
 
// This code is contributed by shubhamsingh10


Python3




def fun( a, n):
    if(n == 1):
        return a[0]
    else:
        x = fun(a, n - 1)
    if(x > a[n - 1]):
        return x
    else:
        return a[n - 1]
 
# Driver code
arr = [12, 10, 30, 50, 100]
print(fun(arr, 5))
 
# This code is contributed by shubhamsingh10


C#




using System;
 
public class GFG{
    static int fun(int[] a,int n)
    {
        int x;
        if(n == 1)
            return a[0];
        else
            x = fun(a, n - 1);
        if(x > a[n - 1])
            return x;
        else
            return a[n - 1];
    }
     
    static public void Main ()
    {
        int[] arr = {12, 10, 30, 50, 100};
        Console.Write(" "+fun(arr, 5)+" ");
    }
}
 
// This code is contributed by shubhamsingh10


Javascript




<script>
//Javascript Implementation
 
function fun(a, n)
{
  var x;
  if(n == 1)
    return a[0];
  else
    x = fun(a, n - 1);
  if(x > a[n - 1])
    return x;
  else
    return a[n - 1];
}
  
// Driver code
var arr = [12, 10, 30, 50, 100];
document.write(fun(arr, 5));
// This code is contributed by shubhamsingh10
</script>


Output: 

100

 

Time complexity: O(n)

Auxiliary Space: O(n)
 

fun() returns the maximum value in the input array a[] of size n.

Question 3 
Predict the output of the following program. What does the following fun() do in general?

C++




#include <iostream>
using namespace std;
 
int fun(int i)
{
  if (i % 2) return (i++);
  else return fun(fun(i - 1));
}
  
int main()
{
  cout << " " << fun(200) << " ";
  getchar();
  return 0;
}
 
// This code is contributed by Shubhamsingh10


C




int fun(int i)
{
  if ( i%2 ) return (i++);
  else return fun(fun( i - 1 ));
}
 
int main()
{
  printf(" %d ", fun(200));
  getchar();
  return 0;
}


Java




import java.io.*;
 
class GFG {
    static int fun(int i)
    {
        if (i % 2 == 1) return (i++);
        else return fun(fun(i - 1));
    }
     
    public static void main (String[] args) {
        System.out.println(" " + fun(200) + " ");
    }
}
 
// This code is contributed by Shubhamsingh10


Python3




def fun(i) :
 
    if (i % 2 == 1) :
        i += 1
        return (i - 1)
    else :
        return fun(fun(i - 1))
   
print(fun(200))
 
# This code is contributed by divyeshrabadiya07


C#




using System;
 
class GFG{
     
static int fun(int i)
{
    if (i % 2 == 1) return (i++);
    else return fun(fun(i - 1));
}
 
// Driver code   
static public void Main ()
{
    Console.WriteLine(fun(200));
}
}
 
// This code is contributed by Shubhamsingh10


Javascript




<script>
 
function fun(i)
{
    if (i % 2 == 1)
        return (i++);
    else
        return fun(fun(i - 1));
}
 
// Driver code
document.write(fun(200));
 
// This code is contributed by bobby
 
</script>


Output: 

199

 

If n is odd, then return n, else returns (n-1). Eg., for n = 12, you get 11 and for n = 11 you get 11. The statement “return i++;” returns the value of i only as it is a post-increment. 

Time complexity: O(n)

Auxiliary Space: O(1)
 

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



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 2
Explain the functionality of the following functions. Question 1 C/C++ 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); } Java Code /* 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); } C/C++ Code # As
3 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 B and B+ Trees
In this article, we will discuss different types of problems based on B and B+ trees. Before understanding this article, you should understand basics of B and B+ trees (see: Introduction, Insert, Delete). These are the types of questions asked in GATE based on B and B+ trees. Type 1. Based on order and number of keys in B and B+ tree - These are th
5 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
Chessboard - Basics Terminologies & Practice Questions
Chess is a famous game as well as a good topic to be asked in the exam. Basic Terminologies of Chess: This is a two-player game that moves their pieces alternatively on a square board.It has an 8×8 grid of 64 equal squares (32 black and 32 white ).Horizontal lines are called ranks.Vertical lines are called Files. Chess pieces are of two colors blac
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
Article Tags :
Practice Tags :