Coder1235
Coder1235

Reputation: 39

Multiplying input values

I am currently attempting a challenge question in one of my homeworks. For now I have written a code that adds all input values until [0] is inputted. The code goes like this:

do {
              results = scanner.nextInt();
              value += results;
} while (results != 0);

However, after attempting to write a code for multiplication, I keep getting my output as 0. I realized that one of the issues was due to the fact that I had previously set my variable value to ```= 0````. Therefore, I created a new variable with a set value of equal to 1. Because any number multiplied to one, is just that number. With many attempts I wrote this code:

 int product = 1;
                        do {
                            results = scanner.nextInt();
                            product *= results;
                        } while (results != 0);

I don' understand why this code is not working. My am multiplying 1 to the values inputted into the loop, so I don't get how the output is zero. Can somebody please help me?

Upvotes: 0

Views: 243

Answers (2)

AvyChanna
AvyChanna

Reputation: 336

When you input zero, results is set to 0 and multiplied with product before you leave the do-while loop.

Just add a check where multiplication does not occur if result = 0

Here is one way to do it

int product = 1;

while (1){
    result = scanner.nextInt();
    if(result == 0){
        break;
    }
    product *= result;
}
// print product here

Upvotes: 2

Ernest
Ernest

Reputation: 25

You multiply by result until result is zero. Any number * zero = zero. When result is 0 I should not multiply by it.

Upvotes: 0

Related Questions