Return an array with the N first even numbers

Asked

Viewed 45 times

-1

Write a function that, by receiving an N number as a parameter, returns the N first even numbers (for example, if N is 3, you must print 0, 2 and 4; if N is 5, it must return 0, 2, 4, 6 and 8).

function retornaNNumerosPares(n) {

    let numerosPares = [];
    for (let i = 0; i < n; i++) {
        if (i % 2 == 0) {
            numerosPares.push(i)
        }
    }
    return numerosPares;
}
retornaNNumerosPares(5) 

It stops at 2, 4 does not enter the array.

  • 1

    https://ideone.com/AdOcis

1 answer

1

If you invoke the function retornaNNumerosPares passing by 5 as parameter, then your loop for will only run 5 times... from 0 to 4.

If you want it to run until you find 5 even numbers could make one for with the condition numerosPares.length < n, thus the for would continue running until its array have 5 items:

function retornaNNumerosPares(n) {
    let numerosPares = [];
    for (let i = 0; numerosPares.length < n; i++) {
        if (i % 2 == 0) {
            numerosPares.push(i);
        }
    }
    return numerosPares;
}

console.log(retornaNNumerosPares(5));

We can also make the function more efficient by increasing i 2 in 2 instead of checking that the rest is equal to 0:

function retornaNNumerosPares(n) {
    let numerosPares = [];
    for (let i = 0; numerosPares.length < n; i += 2) {
        numerosPares.push(i);
    }
    return numerosPares;
}

console.log(retornaNNumerosPares(5));

  • Man, thank you so much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.