Program for average of an array without running into overflow | Java program for the above approach ; Function to calculate average of an array using standard method ; Stores the sum of array ; Find the sum of the array ; Return the average ; Function to calculate average of an array using efficient method ; Store the average of the array ; Traverse the array arr [ ] ; Update avg ; Return avg ; Driver Code ; Input ; Function call
import java . util . * ; class GFG { static Double average ( int arr [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; return Double . valueOf ( sum / N ) ; } static Double mean ( int arr [ ] , int N ) { Double avg = 0.0 ; for ( int i = 0 ; i < N ; i ++ ) { avg += Double . valueOf ( ( arr [ i ] - avg ) / ( i + 1 ) ) ; } return avg ; } public static void main ( String args [ ] ) { int arr [ ] = { Integer . MAX_VALUE , 1 , 2 } ; int N = arr . length ; System . out . println ( " Average ▁ by ▁ Standard ▁ method : ▁ " + String . format ( " % .10f " , average ( arr , N ) ) ) ; System . out . println ( " Average ▁ by ▁ Efficient ▁ method : ▁ " + String . format ( " % .10f " , mean ( arr , N ) ) ) ; } }