Mean - average of array in java

Posted By: Java Examples - 7:48 PM

Share

& Comment

For this, first of all we have to define a class name "ArrayAverage" that has int type array to contain some values .Now we take a double type data that calculates the average of array ( avg = sum / array.length). And finally it will display the result on the command prompt with message by using the System.out.println().


Java version of the average of array problem is given below:
/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package array;

import java.util.Scanner;

/**
 *
 * @author ACHCHUTHAN
 */
public class ArrayAverage {

    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        System.out.println("How many numbers you want to calculate average : ");
        //get number 
        int n = input.nextInt();
        //create array with size n
        int[] array = new int[n];
        //initialize the initial value of sum
        int sum = 0;
        //get the input numbers using for loop
        for (int m = 0; m < n; m++) {
            System.out.print("Array element  " + m + " : ");
            array[m] = input.nextInt();
        }
        //calculate sum of all array elements
        for (int m = 0; m < n; m++) {
            sum = array[m] + sum;
        }

        {
            System.out.println("Total value of array element  = " + sum);
        }
        {
            double avg;
            //calculate average value
            avg = sum / array.length;
            System.out.println("Average of Array = " + avg);
        }
    }
}

Output of this program :

run:
How many numbers you want to calculate average : 
5
Array element  0 : 12
Array element  1 : 56
Array element  2 : 95
Array element  3 : 68
Array element  4 : 94
Total value of array element  = 325
Average of Array = 65.0
BUILD SUCCESSFUL (total time: 10 seconds)

About Java Examples

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

Copyright © 2016 Java Examples ACHCHUTHAN.ORG. Designed by Templateism .