-1

The code below is outputting a string of numbers instead of the sum of the numbers in the array. For example, if n is set to 3 and the numbers 1 2 3 are added to the array the output is 0123 when I need it to be 6. I can only use while loops and not for loops for this which is why the code looks slightly odd. Can someone please explain to me why the output is a string and not the sum of the numbers?

var n = -1;
var n2 = 0;
var numbers = [];

while (n < 0) {
    n = prompt("Please enter a positive interger");
}

while (n > 0) {
    n2 = prompt("Please enter a interger");
    numbers.push(n2);
    n = n - 1
}
var sum = numbers.reduce(function(a, b){
    return a + b;
}, 0);

alert(sum);
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
CodeKid
  • 13
  • 5

2 Answers2

1

Prompt always return a string. You have to parse it:

strN = prompt("Please enter a positive interger");
n = parseInt(strN);
MetallimaX
  • 594
  • 4
  • 13
1

All you need to change is where you push the numbers to the array from

numbers.push(n2);

to

numbers.push(parseInt(n2, 10));

because the prompt believes always that the user inserts a string.

 var n = -1;
    var n2 = 0;
    var numbers = [];

    while (n < 0) {
        n = prompt("Please enter a positive interger");
    }

    while (n > 0) {
        n2 = prompt("Please enter a interger");
        numbers.push(parseInt(n2, 10));
        n = n - 1
    }
    var sum = numbers.reduce(function(a, b){
        return a + b;
    }, 0);
    
    alert(sum);
caramba
  • 21,963
  • 19
  • 86
  • 127