Skip to content
Advertisement

Output Even Numbers In an Array

I want to write a program that receives a list of numbers, converts them into an array, and output the even numbers in the array with Modulus Operator and For Loop.

The code does not run as expected:

function even_num(){
  var submission = prompt("Enter Numbers:", ""); // receive list of numbers 
  var subarray = submission.split('');  // convert to array

  for(var i =1; i < subarray.length; i++){

    if( subarray[i] % 2 != 0){
      document.getElementById("return").innerHTML += subarray[i] + ",";
    }
  }
}
<button onclick="even_num()">Even Number in an Array</button>
<p id = "return"></p>

Thank you

Advertisement

Answer

It’s a matter of incorrect condition. i % 2 would give 0 for even numbers

function even_num() {
  let submission = prompt("Enter Numbers:", "");
  let subarray = submission.split('');
  const result = document.getElementById("return");
  result.innerHTML = '';
  for (var i = 0; i < subarray.length; i++) {
    if (subarray[i] % 2 == 0) {//Condition here was incorrect
      result.innerHTML += subarray[i] + ",";
    }
  }
}
<html>
<button onclick="even_num()">Even Number in an Array</button>
<p id="return"></p>

</html>
Advertisement