// Write a program to sum all the odd elements of an array
a = Number(prompt("a:"));
b = Number(prompt("b:"));
c = Number(prompt("c:"));
sum=Number(0);
var test = [a,b,c];
for (i=0; i<test.length;i++) {
// All even numbers can be divided by 2
if ((test[i]%2)>0) {
alert(test[i] + ":odd");
} else {
alert(test[i] + ":even");
}
test[i]=0;
}
sum=0+test[i];
alert(sum);
My program works brilliant up until its meant to add up all the numbers where it returns a NaN message! Any ideas on how I can sort this problem out?
I see three problems with your code. (Not counting the weird formatting of the curly brackets.)
Edit: looks like the question has been updated a couple of times since I started my answer.
In the “if odd” test you are setting the number to zero withPerhaps you meant to zero out the even numbers so that you could later add up all the numbers and just get the odd ones, buttest[i]=0is not part of the if/else structure. It looks like it should be because of the indenting, but JavaScript ignores extra white-space.You are not adding the numbers to the
sumwithin your loop.You are getting NaN because of this line:
That statement is outside the end of the loop, so at that point
iis equal to the length of the array andtest[i]isundefined.Try the following pseudo-code: