215k views
5 votes
Write a function named countEvens that counts and returns the number of even integers in an array. The function must have this header: function countEvens(list) For example, if the countEvens function were called like this: var list = [ 17, 8, 9, 5, 20 ]; var count = countEvens(list); The countEvens function would return 2 because 8 and 20 are even integers.

User Scorpeo
by
7.4k points

1 Answer

5 votes

Answer:

function countEvens(list) {

// IMPLEMENT THIS FUNCTION!

var even = [];

for(var i = 0; i < list.length; i++){

if (list[i] % 2 == 0){

even.push(list[i]);

}

}

return console.log(even)

}

var list = [ 17, 8, 9, 5, 20 ];

var count = countEvens(list);

Step-by-step explanation:

The programming language used is JavaScript.

An even variable is initialized, to hold the even variables within list.

A FOR loop loop iterates through all the elements in the list, an IF statement is used to check using the modulo division to check if the elements in the list are even.

The even elements are appended to the even list using .push() method.

Finally, the function returns the even list and outputs the list to the log using console.log(even) .

A list is created and the function is called.

Write a function named countEvens that counts and returns the number of even integers-example-1
User Highmastdon
by
7.4k points