curriculum/challenges/english/blocks/quiz-recursion/66edd43cded6bff30944b676.md
To pass the quiz, you must correctly answer at least 9 of the 10 questions below.
What is recursion in programming?
A method of sorting arrays.
A loop that never ends.
A function that returns undefined.
A process in which a function calls itself.
Which of the following is an example of recursion?
function factorial(n) {
let result = 1;
while (n > 0) {
result = result * n;
n--;
}
return result;
}
function factorial(n) {
const arr = Array(n).fill().map((_, i) => i + 1);
return arr.reduce((acc, curr) => acc * curr, 1);
}
function factorial(n) {
let result = 1;
for (let i = n; i > 0; i--) {
result *= i;
}
return result;
}
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}
What will the following function return?
function sum(n) {
if (n === 0) return 0;
return n + sum(n - 1);
}
sum(3);
3
0
1
6
How many times will the mystery function be called?
function mystery(n) {
if (n <= 1) return 1;
return mystery(n - 2);
}
mystery(5);
2
5
4
3
Which of the following is true about recursion?
It should never have a base case.
It should only be used for the Fibonacci sequence.
It should only be used for factorials.
It should always have a base case.
Which of the following options would be an appropriate base case for the given example?
function countDownToZero(number) {
// Base case goes here.
console.log(number);
countDownToZero(number - 1);
}
if (number > 0) {
return;
}
if (number !== 0) {
return;
}
if (number === 0) {
return;
}
if (number < 0) {
return;
}
Why must recursion have a base case?
To ensure the function always has a return value.
To reduce the number of function calls.
To ensure all recursive calls are executed in the correct order and a RecursionError is not thrown.
To provide a way for the function to break out of its recursive calls and prevent infinite loops.
What will this recursive function do?
function repeatString(str) {
return str + repeatString(str);
}
Return the string twice.
Return undefined.
Create an empty string.
Cause a stack overflow.
What is a call stack?
A list of function calls that have been executed.
A list of values that were returned by a function.
A special function used to call a function exactly three times.
A data structure that keeps track of function calls and their execution order.
What does this recursive function do?
function changeString(str) {
if (str === "") return "";
return changeString(str.slice(1)) + str[0];
}
Duplicates a string.
Removes vowels.
Removes spaces.
Reverses a string.