<!DOCTYPE html>
<html>
<body>
<script>
var cases=prompt("number of ingredients");
var i=0;
var a=[];
while (i<cases){
i=i+1;
var cost=prompt("cost of this ingredient");
a.push(cost);
}
alert(a);
var t=a.length;
var sum=0;
var j=0;
while (j<t-1){
var sum=sum+a[j];
j=j+1;
}
alert(sum);
</script>
</body>
</html>
Want to create an array depending on users input in 'cases'. Then tried finding the sum of all numbers in the array 'a'. But its not giving me the answer. Whats wrong? Help is appreciated.
You should parse the input to an integer, otherwise it will be treated as string. Also you need node to declare sum variable twice. Variable t is also not needed.
<!DOCTYPE html>
<html>
<body>
<script>
var cases=prompt("Number of ingredients");
var i = 0;
var a = [];
while (i < cases){
var cost = prompt("Cost of this ingredient");
a[i] = parseInt(cost);
i = i + 1;
}
var sum=0;
var j=0;
while (j < a.length){
sum=sum+a[j];
j=j+1;
}
alert(sum);
</script>
</body>