Calculate average of numbers entered by user – Java

Write a program to find the average of numbers provided by User

- Advertisement -

In this example, we are using Scanner to get the value of n and all the numbers from user.

import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {
        System.out.println("How many numbers you want to enter?");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        /* Declaring array of n elements, the value
         * of n is provided by the user
         */
        double[] arr = new double[n];
        double total = 0;

        for(int i=0; i<arr.length; i++){
        	System.out.print("Enter Element No."+(i+1)+": ");
        	arr[i] = scanner.nextDouble();
        }
        scanner.close();
        for(int i=0; i<arr.length; i++){
        	total = total + arr[i];
        }


        
        double average = total / arr.length;
        
        System.out.format("The average is: %.3f", average);
    }
}

 

- Advertisement -

Output:

How many numbers you want to enter?
5
Enter Element No.1: 5
Enter Element No.2: 5
Enter Element No.3: 10
Enter Element No.4: 10
Enter Element No.5: 10
The average is: 8

 

 

 

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More