Write a number array and add only odd numbers?

JavascriptObject Oriented ProgrammingProgramming

Odd number summation using JavaScript.

 Live Demo

Example

<html>
<body>
<script>
   var tot = 0;
   var a = [1,45,78,9,78,40,67,76];
   for(var i = 0; i<a.length;i++){
      if(a[i]%2 !== 0){
      tot += a[i]
      }
   }
document.write(tot);
</script>
</body>
</html>

Output

122

Explanation: In the above array , since modulus operator is used to find the remainder , when number is divided by 2 if the remainder is 1 then its an odd number and it is programmed to add all odd numbers in an array.

raja
Published on 21-May-2019 13:22:15
Advertisements