Write a number array and add only odd numbers?


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.

Updated on: 30-Jul-2019

928 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements