FaltuTech.Club : Fane of Advanced Logical Thriving Utopian Technical Club

Average of all array elements Using Java

Average of all array elements Using Java



class Average{

    public static void main(String args[]){
        int arr[] = {4,5,6,7,3,4,5};
	
	double sum=0;

	for(int i: arr)
	    sum += i;

	System.out.println("Average is : " + sum/(arr.length));

    }
}

Output

Average is : 4.857142857142857

Discussion

To limit the digits after decimal use : ‘DecimalFormat’ Class or System.out.format() or String.format or System.out.printf()
e.g.

DecimalFormat newDecimalFormat = new DecimalFormat(“#:00”);
newnumber = newDecimalFormat.format(whateverYourNumberIs);

It will give you 4.85 according for above result
Also you need to import java.text.DecimalFormat.


Compiled with JDK 9