Reputation: 27
import java.util.Scanner;
public class Calculations {
public static void main (String [] args) {
Scanner console = new Scanner (System.in);
int a = 0;
int b = 0;
int sum = 0;
int product = 0;
System.out.println ("Enter the Lower Bound");
a = console.nextInt();
System.out.println("Enter the Upper Bound");
b = console.nextInt();
while (a <= b) {
product *= a;
sum += a;
a++;
}
System.out.println("The sum is " + sum);
System.out.println("The Product " + product);
}
}
When I use the +=
for addition I get the result for the addition between a and b. For example if a is 2 and b is 5 the sum will be 14. When I use*=
for multiplication I get a zero. I need help in help in what Im doing wrong that Im getting a zero for the product.
Upvotes: 1
Views: 1566
Reputation: 98
You code is right but you made one simple mathematical mistake. The product of any number with 0 is always 0. So try to use 1 instead of 0. This will solve the problem. The edited code will look like this:
import java.util.Scanner;
public class Calculations
{
public static void main (String [] args)
{
Scanner console = new Scanner (System.in);
int a = 0;
int b = 0;
int sum = 0;
int product = 1;
System.out.println ("Enter the Lower Bound");
a = console.nextInt();
System.out.println("Enter the Upper Bound");
b = console.nextInt();
while (a <= b)
{
product *= a;
sum += a;
a++;
}
System.out.println("The sum is " + sum);
System.out.println("The Product " + product);
}
}
Upvotes: 0
Reputation: 172578
You need to set the value of
int product = 1;
instead of
int product = 0;
As 0 multiplied by anything will be 0.
Upvotes: 3
Reputation: 178313
Anything times 0 is 0. So don't start with a product
of 0
, start with 1
.
int product = 1;
Upvotes: 7