Recursion Quiz 2

Last Updated :
Discuss
Comments

Question 1

What will the following recursive function print if called as printNTo1(3)?


function printNTo1(n) {
if (n === 0) return;
console.log(n);
printNTo1(n - 1);
}


  • A

    1 2 3

  • B

    3 2 1

  • C

    1 2 3 2 1

  • D

    Infinite loop

Question 2

Which of the following is true about printing numbers from 1 to N using recursion?

  • A

    The recursive call should come before console.log(n)

  • B

    The recursive call should come after console.log(n)

  • C

    Base case is not required

  • D

    JavaScript doesn’t support recursion

Question 3

What is the output of this function when called as print1ToN(3)?

function print1ToN(n) {
if (n === 0) return;
print1ToN(n - 1);
console.log(n);
}


  • A

    3 2 1

  • B

    1 2 3

  • C

    1 2 3 2 1

  • D

    Infinite recursion

Question 4

What is tail recursion?

  • A

    When the recursive call is the first statement

  • B

    When there is no base case

  • C

    When the recursive call is the last operation performed

  • D

    When recursion uses a loop internally

Question 5

Which version of the function below is tail-recursive?


function sum(n) {
if (n === 0) return 0;
return n + sum(n - 1);
}


  • A

    This is tail-recursive

  • B

    This is not tail-recursive

  • C

    Tail-recursive only if n > 1

  • D

    None

Question 6

Which condition correctly checks the base case for palindrome recursion?

  • A

    If left > right

  • B

    If string is empty

  • C

    If characters at both ends differ

  • D

    If left == right or left > right

Question 7

What does this function do?

function isPalindrome(s, left, right) {
if (left >= right) return true;
if (s[left] !== s[right]) return false;
return isPalindrome(s, left + 1, right - 1);
}


  • A

    Prints all characters

  • B

    Checks if the string is a palindrome

  • C

    Reverses the string

  • D

    Finds longest palindrome

Question 8

What is the output of sumOfDigits(123)?


function sumOfDigits(n) {
if (n === 0) return 0;
return (n % 10) + sumOfDigits(Math.floor(n / 10));
}


  • A

    6

  • B

    5

  • C

    3

  • D

    123

Question 9

What will happen if you forget the base case in a recursive function like printNTo1(n)?

  • A

    It will print incorrect output

  • B

    It will print only the first number

  • C

    It will cause a stack overflow

  • D

    Nothing, JavaScript handles it


There are 9 questions to complete.

Take a part in the ongoing discussion