Click here to Skip to main content
15,881,620 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 21:41pm
v2

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.
 
Share this answer
 
Comments
CPallini 7-Nov-22 8:52am    
5,
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.
 
Share this answer
 
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);
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900