I am trying to define a function range which takes 3 integer parameters: start, end, and step.
The function should return an array of numbers from start to end count
Create an array and use your existing for loop to push the values to that array andthen return the array. I have given both a for loop and a while loop that gets the job done.
// using a for loop
const range = function(start, end, step) {
let arr = [];
for (i = start; i <= end; i += step){
arr.push(i);
};
return arr;
}
console.log("Using a for loop: ", range(0, 10, 2)); // gives [ 0, 2, 4, 6, 8, 10]
// using a while loop
const range2 = function(start, end, step) {
let arr = [];
let i = start
while (i <= end){
arr.push(i);
i += step;
};
return arr;
}
console.log("Using a while loop: ", range2(0, 10, 2)); // gives [ 0, 2, 4, 6, 8, 10]