15,672,024 members
1.00/5 (1 vote)
See more:
Write a recursive function, `range`, that takes a start and an end and returns
an array of all numbers in that range, exclusive. If the end number is less than
the start, return an empty array.

It was my first day with recursion and I found getting the range of 2 numbers easy, however, for me getting the range BETWEEN two numbers took me hours. X.X

This works. But I tried to understand it by logging it and... Well. Impossible, for me.

Again, getting the range was easy but the code broke WITHOUT the else statement and when I changed

`else if (startNum <= endNum) `

to
`else if (startNum < endNum) {`

(To not get the last number aka endNum)

This code is clearly not the ideal answer. Could someone explain what on Earth is going on here/a better solution? I was honestly going to call it quits for the night when I decided to try another else statement and then paste

```else {
console.log("Random Else statement that made it work")
return range(startNum+1, endNum)
}```

And it, somehow, worked.

What I have tried:

```function range(startNum, endNum) {
if (startNum > endNum) {
return [];

} else if (startNum < endNum) {
console.log(range(startNum+1, endNum))
var rangeArray = range(startNum+1, endNum);

console.log(startNum + " <-- Start  End ---> " + endNum)
rangeArray.unshift(startNum);
return rangeArray;

} else {
console.log("Random Else statement that made it work")
return range(startNum+1, endNum)
}
};```
Posted
Updated 10-Oct-22 1:27am
v2
Gerry Schmitz 10-Oct-22 12:16pm
You want the numbers "between"; you were / are missing the case where startNum + 1 == endNum (i.e. no numbers in between). Your "else" handles the case where startNum == endNum.
Chris Aug2022 10-Oct-22 21:46pm
Awesome, I wke up this morning and had an 'aha duh' moment. Would you like to provide a solution so I can accept it?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 Richard Deeming 100 Andre Oosthuizen 70 Graeme_Grant 58 Richard MacCutchan 55 k5054 50
 OriginalGriff 1,425 Richard MacCutchan 501 Richard Deeming 280 Patrice T 225 Andre Oosthuizen 175

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900