for Use Recursion to Create a Range of Numbers
We have defined a function named
rangeOfNumbers
with two parameters. The function should return an array of integers which begins with a number represented by thestartNum
parameter and ends with a number represented by theendNum
parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where bothstartNum
andendNum
are the same.
I came up with
function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
return [startNum];
} else {
var numbers = rangeOfNumbers(startNum + 1, endNum);
numbers.push(startNum);
return numbers;
}
}
it didn’t work. so I went to the guide and looked at the solution to see what I was missing.
the given solution was
function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
return [startNum];
} else {
var numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
return numbers;
}
}
how are those different? what do the actual outcomes look like?
Thank you in advanced.