Find All The Odd Numbers

Ben Harter-Murphy
2 min readDec 14, 2021

This week we are going to dive into another solution. Finding all the odd numbers in a given range, and returning them into a new array. You know the drill, lets see our problem and find a way to solve it!

Our Problem — We have an inclusive range represented by arguments in our function. Let’s call them l and r. Between those two integers our task is to find all the odd numbers and return them into a new array.

First, lets define our function:

let arr = [];function oddNumbers(l,r){}

Since we are never given an array to work with, we are going to have to declare an empty one on our own to work with. Here we are using a variable of “arr” to define our empty array. And a function declaration of oddNumbers and passing in our two arguments: l and r. These two arguments represent the starting and ending numbers of our inclusive range.

Second, how do we loop over this range?!?!

let arr = [];function oddNumbers(l,r){
for(let i = l; i <= r; i++){
}}

Here we have our iterator. Normally when we are working with an array we would declare i as 0 and loop until the arrays length. Here we are going to declare i as our starting integer. And iterate until we reach the end of our range, whatever that may be. Now the question is how do we determine if our number is odd or not?

Third, Determining an Odd Number:

let arr = [];function oddNumbers(l,r){
for(let i = l; i <= r; i++){
if(i % 2 !== 0){
}}}

So here we have a conditional for each integer that gets passed in. Normally to determine if a number is even or not we would use the modulo operator. If a number can be divided by two and have an remainder of 0 it is even. That being said if that is how we determine an even number, we would negate that statement to say if it does NOT equal zero to determine an odd number. And that is how we find our odd numbers.

Fourth, What to do with the numbers after we find them:

let arr = [];function oddNumbers(l,r){
for(let i = l; i <= r; i++){
if(i % 2 !== 0){
arr.push(i)
}}}

Here we are finally using our empty array with the push method. If the determined number evaluates to true given our conditional then we want to push them into the empty array, creating our own array of odd numbers. Next all we have to do to finish the function is return the array.

The Solution:

let arr = [];function oddNumbers(l,r){
for(let i = l; i <= r; i++){
if(i % 2 !== 0){
arr.push(i);
} } return arr;}

And there you have it! A function that returns an array of established odd numbers. I hope as always that this is informative and helpful in your coding process. Happy Coding!

--

--