'Multiply numbers for loop java returning 0
I'm trying to take a number(n) and multiply it by every number before it, enter 4 you get (1x2x3x4) = 24. My code returns a 0. I have an addition just like this that works. Any ideas?
public static int multiplyTooNum()
{
Scanner myIn = new Scanner(System.in);
int n;
System.out.println("Please enter a number");
n = myIn.nextInt();
myIn.nextLine();
int sum = 0;
for (int i=0; i<n; i++)
{
sum = sum * i;
}
int result = sum*n;
System.out.println(result);
myIn.close();
return result;
}
Solution 1:[1]
In multiplication, the accumulated variable is not called sum. It is called product. The word sum is only used in the context of addition.
Now, on with your problem:
If you remember your elementary school mathematics, anything multiplied by zero gives zero.
That's why you are receiving a zero in the end.
So, in order to fix this, you have to initialize your product with 1 instead of 0, and then make your for loop start counting from index 1 instead of 0.
Solution 2:[2]
for (int i=0; i<n; i++)
{
sum = sum * i;
}
Issue is in this part, you start i from 0, so each time the sum get's 0 and it will be multiplied again. I suggest you to learn debugging and step over in loops to pinpoint the issues.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Juliyanage Silva |
