15,793,535 members
See more:
Java
```Scanner sc = new Scanner(System.in);
int num;

int sum = 0;
do {
System.out.println("Enter the number: ");
num = sc.nextInt();
sum += num;
System.out.println("Enter 0 to end the loop: ");
}while (num != 0);
System.out.println("sum is "+sum);

int avg = sum / num;
System.out.println("average is "+avg);```

What I have tried:

i am not able to get the average value of the numbers entered by the user
it is showing "
`Exception in thread "main" java.lang.ArithmeticException: / by zero`
"
Posted
Updated 7-Nov-22 22:41pm
v2

Solution 1

Your loop terminates when `num` is equal to `0`.

You then try to divide the `sum` by `num`, which will (obviously) give you a "divide by zero" error.

You need a separate variable to keep track of how many numbers the user has entered.

You'll also need to convert at least one side of the division to a floating-point number; otherwise, Java will perform an "integer division", truncating the result to fit in an integer. For example, using integers, the average of `1` and `2` would be `1`, which is clearly not correct.

CPallini 7-Nov-22 8:52am
5,

Solution 2

Quote:
i am not able to get the average value of the numbers entered by the user

You need to count the number of value typed by user !
`num` is only the user input, and user typed 0 in order to exit the loop.

Solution 3

Hi,

First of all there's error in your code.

The average for `n` numbers will be sum divided by the count of this numbers.

So your program hangs on the last entered zero.

I'd like to re-write it as follows:
Java
```Scanner sc = new Scanner(System.in);
int num;

int sum = 0;
int count = 0;

do {
System.out.println("Enter the number: ");
num = sc.nextInt();
sum += num;
System.out.println("Enter 0 to end the loop: ");

if (num != 0) count = count + 1;
}while (num != 0);
System.out.println("sum is "+sum);

float avg = sum;

if (count > 0) avg = avg / count;

System.out.println("average is "+avg);```

v2