Java Program to Calculate Arithmetic Mean

This article covers a program in Java that finds and prints the arithmetic mean of n numbers entered by the user. The arithmetic mean of n numbers can be calculated as:

Arithmetic Mean = (Sum of All Numbers)/(n)

Calculate the arithmetic mean or average in Java

The question is: write a Java program to find and print the arithmetic mean of n numbers, entered by the user at run-time of the program. The program given below is its answer:

import java.util.Scanner;

public class CodesCracker
{
   public static void main(String[] args)
   {
      int n, i, sum=0;
      float armean;
      Scanner scan = new Scanner(System.in);
      
      System.out.print("How many numbers to enter ? ");
      n = scan.nextInt();
      int[] arr = new int[n];
      
      System.out.print("Enter " +n+ " Numbers: ");
      for(i=0; i<n; i++)
      {
         arr[i] = scan.nextInt();
         sum = sum + arr[i];
      }
      
      armean = sum/n;
      System.out.println("\nArithmetic Mean = " +armean);
   }
}

The snapshot given below shows the sample run of the above program with user input of 6 as size and 10, 20, 30, 40, 50, and 60 as six numbers to find and print the arithmetic mean of these six numbers:

java program calculate arithmetic mean

In the above example, the following statement:

int n, i, sum=0;

Declare integer variables n (number of inputs), i (loop counter), and sum (sum of inputs), and initialize sum to 0. Then the following statement:

Scanner scan = new Scanner(System.in);

Create a Scanner object to read input from the user. Then the following statement:

n = scan.nextInt();

Read an integer value from the user and store it in n. Again, the following statement:

int[] arr = new int[n];

Create an integer array arr of size n. Then the following statement:

arr[i] = scan.nextInt();

In a loop from 0 to n-1, read an integer from the user and store it in arr[i]. Also, add the input to the running total sum. Now the following statement:

armean = sum/n;

Compute the arithmetic mean by dividing the sum by the number of inputs and store it in armean. Finally, the following statement:

System.out.println("\nArithmetic Mean = " +armean);

Display the result to the user.

Same Program in Other Languages

Java Online Test


« Previous Program Next Program »


Liked this post? Share it!