Search code examples
javascripttypestype-conversioniterationmultiplication

Multiplying Integers on a For Loop


Beginning JavaScript learner here...

I'm working through Adrian Neumann's Simple Programming Problems and my question is about number 6 in the elementary exercises.

Write a program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the product of 1,…,n.

// var myArray = []; // for testing
var mySum = 0;
var userNum = prompt("What is your number? ");
var userChoice = prompt("Would you like to add up (+) or multiply (*) all the numbers from 1 to your number? Please enter (+) or (*): ");

if (userChoice == "+") {
    for (var i = userNum; i > 0; i--) {
        mySum += +i;
    }
    console.log("Your answer is " + mySum);
} else if (userChoice == "*") {
    for (var i = userNum; i > 0; i--) {
        mySum *= +i;
        // myArray.push(i); // for testing
    }
    console.log("Your answer is " + mySum);
    // console.log(myArray); // for testing
}

When entering values for multiplication, the answer is always 0. Obviously, I thought 0 was being included in the iteration, so I setup an empty array myArray, and pushed all the numbers to the array using myArray.push(i);... 0 was never included as a value in the array.

Other than some obvious form-validation considerations, can anyone tell me what I'm missing? Why is my answer always 0?

Note: The sum section of the code seems to work brilliantly.

Please note I'm a beginniner to JavaScript, so if you'd like to comment, let me know WHY you changed the code the way you do, rather than simply spitting back code to me. That's a big help, thanks.


Solution

  • Well, you initialize mySum to 0 so in every iteration of the loop you'll multiplying i by zero and save the result (again, zero) back into mySum. For multiplication you'd have to start at one.