# Program for average of an array without running into overflow

Given an array arr[] of size N, the task is to find the average of the array elements without running into overflow.

Examples:

Input: arr[] = { INT_MAX, INT_MAX }
Output:
Average by Standard method: -1.0000000000
Average by Efficient method: 2147483647.0000000000
Explanation:
The average of the two numbers by standard method is (sum / 2).
Since the sum of the two numbers exceed INT_MAX, the obtained output by standard method is incorrect.

Input: arr[] = { INT_MAX, 1, 2 }
Output:
Average by Standard method: -715827882.0000000000
Average by Efficient method: 715827883.3333332539

Approach: The given problem can be solved based on the following observations:

• The average of N array elements can be obtained by dividing the sum of the array elements by N. But, calculating sum of the array arr[] may lead to integer overflow, if the array contains large integers.
• Therefore, average of the array can be calculated efficiently by the following steps:
• Traverse the array, using a variable i over the range of indices [0, N – 1]
• Update avg = (avg+ (arr[i] – avg)/(i+1))

Follow the steps below to solve the problem:

• Initialize two variables, say sum as 0 and avg as 0, to store the sum and average of the array elements respectively.
• Traverse the array arr[], update avg = avg + (arr[i] – avg) / (i + 1) and update sum = sum + arr[i].
• After completing the above steps, print the average by the standard method, i.e. sum / N and print the average by the efficient method, i.e. avg

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach#include using namespace std; // Function to calculate average of// an array using standard methoddouble average(int arr[], int N){    // Stores the sum of array    int sum = 0;     // Find the sum of the array    for (int i = 0; i < N; i++)        sum += arr[i];     // Return the average    return (double)sum / N;} // Function to calculate average of// an array using efficient methoddouble mean(int arr[], int N){    // Store the average of the array    double avg = 0;     // Traverse the array arr[]    for (int i = 0; i < N; i++) {         // Update avg        avg += (arr[i] - avg) / (i + 1);    }     // Return avg    return avg;} // Driver Codeint main(){    // Input    int arr[] = { INT_MAX, 1, 2 };    int N = sizeof(arr) / sizeof(arr[0]);     // Function call    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;}

## Java

 // Java program for the above approachimport java.util.*;class GFG{  // Function to calculate average of// an array using standard methodstatic Double average(int arr[], int N){       // Stores the sum of array    int sum = 0;     // Find the sum of the array    for (int i = 0; i < N; i++)        sum += arr[i];     // Return the average    return Double.valueOf(sum / N);} // Function to calculate average of// an array using efficient methodstatic Double mean(int arr[], int N){       // Store the average of the array    Double avg = 0.0;     // Traverse the array arr[]    for (int i = 0; i < N; i++)    {         // Update avg        avg += Double.valueOf((arr[i] - avg) / (i + 1));    }     // Return avg    return avg;} // Driver Codepublic static void main(String args[]){       // Input    int arr[] = {Integer.MAX_VALUE, 1, 2 };    int N = arr.length;       // Function call    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)));}} // This code is contributed by ipg2016107.

## Python3

 # Python3 program for the above approachimport sys # Function to calculate average of# an array using standard methoddef average(arr, N):         # Stores the sum of array    sum = 0     # Find the sum of the array    for i in range(N):        sum += arr[i]     # Return the average    return sum // N * 1.0 - 1 # Function to calculate average of# an array using efficient methoddef mean(arr, N):         # Store the average of the array    avg = 0     # Traverse the array arr[]    for i in range(N):                 # Update avg        avg += (arr[i] - avg) / (i + 1)     # Return avg    return round(avg, 7) # Driver Codeif __name__ == '__main__':         # Input    arr = [2147483647, 1, 2]    N = len(arr)     # Function call    print("Average by Standard method: ","{:.10f}".format(        -1.0 * average(arr, N)))     print("Average by Efficient method: ","{:.10f}".format(        mean(arr, N))) # This code is contributed by mohit kumar 29

## C#

 // C# program for the above approachusing System; class GFG{ // Function to calculate average of// an array using standard methodstatic double average(int[] arr, int N){         // Stores the sum of array    int sum = 0;     // Find the sum of the array    for(int i = 0; i < N; i++)        sum += arr[i];     // Return the average    return (double)(sum / N);} // Function to calculate average of// an array using efficient methodstatic double mean(int[] arr, int N){     // Store the average of the array    double avg = 0.0;     // Traverse the array arr[]    for(int i = 0; i < N; i++)    {                 // Update avg        avg += ((double)((arr[i] - avg) / (i + 1)));    }     // Return avg    return avg;} // Driver Codestatic public void Main(){     // Input    int[] arr = { Int32.MaxValue, 1, 2 };    int N = arr.Length;     // Function call    Console.WriteLine("Average by Standard method: " +         (average(arr, N)).ToString("F10"));    Console.WriteLine("Average by Efficient method: " +          (mean(arr, N)).ToString("F10"));}} // This code is contributed by Dharanendra L V.

## Javascript



Output:
Average by Standard method: -715827882.0000000000
Average by Efficient method: 715827883.3333332539

Time Complexity: O(N)
Auxiliary Space: O(1)

Previous
Next