How can I make a modulus operator add odd numbers between two numbers in JavaScript?

789 views Asked by At

Below is what I have so far. And do I place the user prompt within the function or leave it where it is? What I am "trying" to accomplish is to add

<!DOCTYPE HTML>
 <html lang="en-us">
  <head>
   <meta charset="utf-8">
  <script type="text/javascript">
/* Input: user types in an integer
 * Processing: adds all odd numbers between input and 0
 * Output: the sum of the odd numbers 
 */
 function addOdds() {
    var n = parseInt(document.getElementById('number').value);  
        var sum = i=i+2;
            for **(var i = -1; i < 6; i = i + 2)** {
                if (n == 0) {
                    break;
                }
                sum += n;
            }
            window.alert(sum);
        }   
        </script>
    </head>

    <body>
    Please enter a number. <input type="text" id="number">
    <button type="button" onclick="addOdds()"> Get the sum </button>
    <div id=""> </div> <!--is this part need? -->
</body>
</html>
3

There are 3 answers

0
ggbranch On
var sum = 0;
for (var i = 1; i<=n; i+=2) {
   sum+=i;
}
2
RobG On

In your function you have:

function addOdds() {
  var n = parseInt(document.getElementById('number').value);  
  var sum = i=i+2;

i is declared below so its value is undefined. Adding 2 returns NaN. Just initialise sum to 0:

  var sum = 0;

  for (var i = -1; i < 6; i = i + 2) {

I think you need to start from 0, though it's even so start from 1. And you want to go up to value, so:

  for (var i=1; i<=n; i++) {

Now just add i if it's not even:

    sum += i%2? i : 0;
  }

and you're done.

  document.getElementById('sum').textContent = sum
}

Assuming that you also have:

<div id="sum"></div>

But I like Wee You's answer. ;-)

0
Jaffer Wilson On

Try this code, it will help you..

<!DOCTYPE HTML>
 <html lang="en-us">
  <head>
   <meta charset="utf-8">
  <script type="text/javascript">
/* Input: user types in an integer
 * Processing: adds all odd numbers between input and 0
 * Output: the sum of the odd numbers 
 */
 function addOdds() {
    var n = parseInt(document.getElementById('number').value);  
        var sum = 0;
            for (var i = 0; i < n; i++) {
                if (i % 2 != 0) {
                    sum += i;
                }
                ;
            }
            window.alert(sum);
        }   
        </script>
    </head>

    <body>
    Please enter a number. <input type="text" id="number">
    <button type="button" onclick="addOdds()"> Get the sum </button>
    <div id=""> </div> <!--is this part need? -->
</body>
</html>