0

i'm trying to find the sum of elements in array my input is : 1 2 3 4 5 the output should be : 15 the output i receive : 012345

<html>
<head>
</head>
<body>
<script>
var numbers=[];
var sum=0;
for (var i=0;i<5;i++)
{
    numbers.push(prompt('Enter Your Numbers'));
    sum += numbers[i];
}
function getSumOfArray() {
    return  sum;
}
document.write("The Sum of Array: "+getSumOfArray()+"<br />");
</script>

</body>
</html>
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
  • 3
    `prompt` returns a string, so the value you're putting in the array is a string. As such, the `sum` you're calculating is really just concatenating the strings together. Hint: convert the value of the prompt to a number before adding it to the array. – Evan Trimboli Mar 27 '18 at 00:12
  • @EvanTrimboli, that should be an answer – smac89 Mar 27 '18 at 00:14

2 Answers2

3

By calling parseFloat() to convert the string input to numbers should fix the issue.

<html>
<head>
</head>
<body>
<script>
var numbers = [];
var sum = 0;
for (var i = 0; i < 5; i++)
{
    numbers.push(parseFloat(prompt('Enter Your Numbers')));
    sum += numbers[i];
}
function getSumOfArray() {
    return sum;
}
document.write("The Sum of Array: " + getSumOfArray() + "<br />");
</script>

</body>
</html>
Ryan Yuan
  • 2,396
  • 2
  • 13
  • 23
0

RyanTheCoders answer is correct. However, I would separate input from processing

<html>
<head>
</head>
<body>
<script>
     var count = 5;
     var numbers=[];
     var sum=0;

     //get inputs
     for (var i=0;i<count;i++)
     {
          numbers.push(parseInt(prompt('Enter Your Numbers')));
     }

     //calculate sum
     for (var x=0;x<count;x++)
     {
          sum += numbers[x];
     }

     function getSumOfArray() {
          return  sum;
     }

     document.write("The Sum of Array: "+getSumOfArray()+"<br />");
</script>
</body>
</html>
Luke101
  • 63,072
  • 85
  • 231
  • 359