Reputation: 11
I'm trying to return the array containing even numbers, from 0 to a given an integer N.
My actual code is :
function evenNumbers(n) {
let i = 0;
while(i <= n)
i += 2;
var ans = [];
ans.push(0, n%2 === 0);
return ans;
}
module.exports = evenNumbers;
console.log(evenNumbers(6));
Output :
[0, true]
But the expected output is :
[0, 2, 4, 6]
Why evenNumbers()
doesn't return the expected result?
Upvotes: 0
Views: 452
Reputation: 28414
ans=[]
and i=0
at the beginningwhile-loop
, iterate as long as i <= n
i
to ans
and increment it by 2
ans
function evenNumbers(n) {
const ans = [];
let i = 0;
while(i <= n) {
ans.push(i);
i += 2;
}
return ans;
}
console.log('Even numbers 0-2: ', ...evenNumbers(2));
console.log('Even numbers 0-6: ', ...evenNumbers(6));
Upvotes: 1