Program for average of an array without running into overflow | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; double average ( int arr [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; return ( double ) sum / N ; } double mean ( int arr [ ] , int N ) { double avg = 0 ; for ( int i = 0 ; i < N ; i ++ ) { avg += ( arr [ i ] - avg ) / ( i + 1 ) ; } return avg ; } int main ( ) { int arr [ ] = { INT_MAX , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Average ▁ by ▁ Standard ▁ method : ▁ " << fixed << setprecision ( 10 ) << average ( arr , N ) << endl ; cout << " Average ▁ by ▁ Efficient ▁ method : ▁ " << fixed << setprecision ( 10 ) << mean ( arr , N ) << endl ; return 0 ; }