Quiz: Recursion

To View Tricks: Login Required

Number of Questions: 10

Question: 6 -

To end a recursive method a RETURN statement is usually kept inside ___.

Options:
  1. IF block

  2. None of these

  3. IF or ELSE block

  4. ELSE block

  5. Answer:

    IF or ELSE block

    Solution:

    A proper RETURN statement ends the recursion process when kept inside a conditional IF or ELSE block.


Question: 7 -

What is the output of the below Java program with recursion?

public class RecursionTesting
{
  static int num=4;
  public static void main(String[] args)
  {
    new RecursionTesting().recursiveMethod();
  }

  void recursiveMethod()
  {
    num--;
    if(num == 0)
      return;
    System.out.print(num + " ");
    recursiveMethod();
  }
}

Options:
  1. 3 2 1 0

  2. Compiler error

  3. 4 3 2 1

  4. 3 2 1

  5. Answer:

    3 2 1 0

    Solution:

    Note that this recursive method does not return anything. It simply does the printing of some values.


Question: 8 -

What is the maximum number of levels in a Recursion?

Options:
  1. No limit

  2. 16

  3. 8

  4. 18

  5. Answer:

    No limit

    Solution:

    There is no limit. The limit actually depends on the size of Stack Memory. If you process a large amount of data, it may lead to a Stack Overflow error.


Question: 9 -

What is the output of the below Java program with Recursion?

public class RecursionTest2
{
  public static void main(String[] args)
  {
    RecursionTest2 rt2 = new RecursionTest2();
    int sum = rt2.summer(4);
    System.out.println(sum);
  }

  int summer(int in)
  {
    int sum = 0;

    if(in ==0)
	  return 0;

    sum = in + summer(--in);	
    return sum;
  }
}

Options:
  1. 0

  2. 10

  3. 6

  4. Infinite loop

  5. Answer:

    10

    Solution:

    IN 4
    IN 3
    IN 2
    IN 1
    IN 0
    10


Question: 10 -

Which is the common problem with Recursive methods in Java?

Options:
  1. None

  2. IndexOutOfBoundsException

  3. StackOverflowError

  4. OutOfMemoryError

  5. Answer:

    StackOverflowError

    Solution:

    StackOverError occurs when the stack has been full and can not allocate space for continuing new method call.