Related Articles

# Program for average of an array without running into overflow

• Last Updated : 15 Jun, 2021

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 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 method``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 method``double` `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 Code``int` `main()``{``    ``// Input``    ``int` `arr[] = { INT_MAX, 1, 2 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);` `    ``// 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 approach``import` `java.util.*;``class` `GFG{`` ` `// Function to calculate average of``// an array using standard method``static` `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 method``static` `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 Code``public` `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 approach``import` `sys` `# Function to calculate average of``# an array using standard method``def` `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 method``def` `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 Code``if` `__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 approach``using` `System;` `class` `GFG{` `// Function to calculate average of``// an array using standard method``static` `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 method``static` `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 Code``static` `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)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up