Calum MacRae
Calum MacRae

Reputation: 1

Trying to add every single number within a range using a for loop to create a sum

I can't figure out the issue with my code. The output should add every number in a range (like 1 and 2 when entered will output 3). However, 1 and 3 outputs 12 for no discernible reason.

function Sum(){
        var int1=document.getElementById("TextBox1").value;
        var int2=document.getElementById("TextBox2").value;
        for(i=int1; i<=int2; i++){
            var total=int1;
            total+=i;
            if(i==int2){
                alert("The sum of all numbers is "+total);
            }
        }
}

    
        function Sum(){
        	var int1=document.getElementById("TextBox1").value;
        	var int2=document.getElementById("TextBox2").value;
        	for(i=int1; i<=int2; i++){
        		var total=int1;
        		total+=i;
        	    if(i==int2){
        	        alert("The sum of all numbers is "+total);
        	    }
        	}
        }
    
    
    
        <html>
        <head>
        <title>
        For Sum Exercise
        </title>
        </head>
        <body>
        <script>
        </script>
        User Number 1:<input id="TextBox1"><br><br>
        User Number 2:<input id="TextBox2"><br><br>
        <button onClick="Sum()">Sum</button><br>
        </body>
        </html>
    
    

Upvotes: 0

Views: 29

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386600

You need to take a number from the input. value is from type string. With an unary plus +, you get a number.

You need to declare i as well.

Declare total in advance and take zero as value outside of the loop.

After the loop make the output.

function Sum() {
    var int1 = +document.getElementById("TextBox1").value,
        int2 = +document.getElementById("TextBox2").value,
        total = 0,
        i;

    for (var i = int1; i <= int2; i++) {
        total += i;
    }
    document.getElementById("sum").innerHTML = "The sum of all numbers is " + total;
}
User Number 1: <input id="TextBox1"><br><br> User Number 2: <input id="TextBox2"><br><br>
<button onClick="Sum()">Sum</button><br>
<p id="sum"></p>

Upvotes: 1

Related Questions