Average of a stream of numbers - GeeksforGeeks

20 Oct, 2021
Difficulty Level: Rookie Given a stream of numbers, print the average (or mean) of the stream at every point. For example, let us consider the stream as 10, 20, 30, 40, 50, 60, ... 
  Average of 1 numbers is 10.00
  Average of 2 numbers is 15.00
  Average of 3 numbers is 20.00
  Average of 4 numbers is 25.00
  Average of 5 numbers is 30.00
  Average of 6 numbers is 35.00
  ..................
 
To print the mean of a stream, we need to find out how to find the average when a new number is being added to the stream. To do this, all we need is the count of numbers seen so far in the stream, previous average, and new number. Let n be the count, prev_avg be the previous average and x be the new number being added. The average after including x number can be written as (prev_avg*n + x)/(n+1).  
C++
C
Java
Python3
C#
PHP
Javascript
#include <iostream>using namespace std; // Returns the new average after including xfloat getAvg(float prev_avg, int x, int n){    return (prev_avg * n + x) / (n + 1);} // Prints average of a stream of numbersvoid streamAvg(float arr[], int n){    float avg = 0;    for (int i = 0; i < n; i++) {        avg = getAvg(avg, arr[i], i);        cout <<"Average of " <<i+1 << " numbers is " << avg << endl;    }    return;} // Driver program to test above functionsint main(){    float arr[] = { 10, 20, 30, 40, 50, 60 };    int n = sizeof(arr) / sizeof(arr[0]);    streamAvg(arr, n);     return 0;} // This code is contributed by shivanisinghss2110
#include <stdio.h> // Returns the new average after including xfloat getAvg(float prev_avg, int x, int n){    return (prev_avg * n + x) / (n + 1);} // Prints average of a stream of numbersvoid streamAvg(float arr[], int n){    float avg = 0;    for (int i = 0; i < n; i++) {        avg = getAvg(avg, arr[i], i);        printf("Average of %d numbers is %f \n", i + 1, avg);    }    return;} // Driver program to test above functionsint main(){    float arr[] = { 10, 20, 30, 40, 50, 60 };    int n = sizeof(arr) / sizeof(arr[0]);    streamAvg(arr, n);     return 0;}
// Java program to find average// of a stream of numbersclass GFG {     // Returns the new average after including x    static float getAvg(float prev_avg, float x, int n)    {        return (prev_avg * n + x) / (n + 1);    }     // Prints average of a stream of numbers    static void streamAvg(float arr[], int n)    {        float avg = 0;        for (int i = 0; i < n; i++)        {            avg = getAvg(avg, arr[i], i);            System.out.printf("Average of %d numbers is %f \n",                                                   i + 1, avg);        }        return;    }     // Driver program to test above functions    public static void main(String[] args)    {        float arr[] = { 10, 20, 30, 40, 50, 60 };        int n = arr.length;        streamAvg(arr, n);    }} // This code is contributed by Smitha Dinesh Semwal
# Returns the new average# after including xdef getAvg(prev_avg, x, n):    return ((prev_avg *             n + x) /            (n + 1)); # Prints average of# a stream of numbersdef streamAvg(arr, n):    avg = 0;    for i in range(n):        avg = getAvg(avg, arr[i], i);        print("Average of ", i + 1,              " numbers is ", avg); # Driver Codearr = [10, 20, 30,       40, 50, 60];n = len(arr);streamAvg(arr, n); # This code is contributed# by mits
// C# program to find average// of a stream of numbersusing System; class GFG{     // Returns the new average    // after including x    static float getAvg(float prev_avg,                        float x, int n)    {        return (prev_avg * n + x) / (n + 1);    }     // Prints average of    // a stream of numbers    static void streamAvg(float[] arr,                          int n)    {        float avg = 0;        for (int i = 0; i < n; i++)        {            avg = getAvg(avg, arr[i], i);            Console.WriteLine("Average of {0} " +                                "numbers is {1}",                                     i + 1, avg);        }        return;    }     // Driver Code    public static void Main(String[] args)    {        float[] arr = {10, 20, 30,                       40, 50, 60};        int n = arr.Length;        streamAvg(arr, n);    }} // This code is contributed by mits
<?php// PHP program for Average of// a stream of numbers // Returns the new average// after including xfunction getAvg($prev_avg, $x, $n){    return ($prev_avg * $n + $x) /                        ($n + 1);} // Prints average of a// stream of numbersfunction streamAvg($arr, $n){    $avg = 0;    for ($i = 0; $i < $n; $i++)    {        $avg = getAvg($avg, $arr[$i], $i);        echo "Average of ",$i + 1, "numbers is "                                    ,$avg,"\n";    }    return;}     // Driver Code    $arr = array(10, 20, 30, 40, 50, 60);    $n = sizeof($arr);    streamAvg($arr, $n); // This code is contributed by aj_36?>
<script>// javascript program to find average// of a stream of numbers // Returns the new average after including xfunction getAvg( prev_avg,  x,  n){    return (prev_avg * n + x) / (n + 1);} // Prints average of a stream of numbersfunction streamAvg( arr,  n){    let avg = 0;    for (let i = 0; i < n; i++) {        avg = getAvg(avg, arr[i], i);       document.write("Average of "+(i + 1) +" numbers is "+  avg.toFixed(6) + "<br/>");    }    return;} // Driver program to test above functions    let arr = [10, 20, 30, 40, 50, 60 ];    let n = arr.length;    streamAvg(arr, n);    // This code is contributed by todaysgaurav </script>
Output :  
Average of 1 numbers is 10.000000 
Average of 2 numbers is 15.000000 
Average of 3 numbers is 20.000000 
Average of 4 numbers is 25.000000 
Average of 5 numbers is 30.000000 
Average of 6 numbers is 35.000000 
Time Complexity: O(n)
Auxiliary Space: O(1)
The above function getAvg() can be optimized using the following changes. We can avoid the use of prev_avg and the number of elements by using static variables (Assuming that only this function is called for an average of stream). Following is the optimized version.  
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; // Returns the new average after including xfloat getAvg(int x){    static int sum, n;     sum += x;    return (((float)sum) / ++n);} // Prints average of a stream of numbersvoid streamAvg(float arr[], int n){    float avg = 0;    for (int i = 0; i < n; i++)    {        avg = getAvg(arr[i]);        cout<<"Average of "<<i+1<<" numbers is "<<fixed<<setprecision(1)<<avg<<endl;    }    return;} // Driver codeint main(){    float arr[] = { 10, 20, 30, 40, 50, 60 };    int n = sizeof(arr) / sizeof(arr[0]);    streamAvg(arr, n);     return 0;} // This code is contributed by rathbhupendra
#include <stdio.h> // Returns the new average after including xfloat getAvg(int x){    static int sum, n;     sum += x;    return (((float)sum) / ++n);} // Prints average of a stream of numbersvoid streamAvg(float arr[], int n){    float avg = 0;    for (int i = 0; i < n; i++) {        avg = getAvg(arr[i]);        printf("Average of %d numbers is %f \n", i + 1, avg);    }    return;} // Driver program to test above functionsint main(){    float arr[] = { 10, 20, 30, 40, 50, 60 };    int n = sizeof(arr) / sizeof(arr[0]);    streamAvg(arr, n);     return 0;}
// Java program to return// Average of a stream of numbersclass GFG{static int sum, n;     // Returns the new average// after including xstatic float getAvg(int x){    sum += x;    return (((float)sum) / ++n);} // Prints average of a// stream of numbersstatic void streamAvg(float[] arr,                      int n){    float avg = 0;    for (int i = 0; i < n; i++)    {        avg = getAvg((int)arr[i]);        System.out.println("Average of "+ (i + 1) +                           " numbers is " + avg);    }    return;} // Driver Codepublic static void main(String[] args){    float[] arr = new float[]{ 10, 20, 30,                               40, 50, 60 };    int n = arr.length;    streamAvg(arr, n);}} // This code is contributed by mits
# Returns the new average# after including xdef getAvg(x, n, sum):    sum = sum + x;    return float(sum) / n; # Prints average of a# stream of numbersdef streamAvg(arr, n):    avg = 0;    sum = 0;    for i in range(n):        avg = getAvg(arr[i], i + 1, sum);        sum = avg * (i + 1);        print("Average of ", end = "");        print(i + 1, end = "");        print(" numbers is ", end = "");        print(avg);    return; # Driver Codearr= [ 10, 20, 30,       40, 50, 60 ];n = len(arr);streamAvg(arr,n); # This code is contributed by mits
using System; class GFG{static int sum, n;     // Returns the new average// after including xstatic float getAvg(int x){     sum += x;    return (((float)sum) / ++n);} // Prints average of a// stream of numbersstatic void streamAvg(float[] arr, int n){    float avg = 0;    for (int i = 0; i < n; i++)    {        avg = getAvg((int)arr[i]);        Console.WriteLine("Average of {0} numbers " +                             "is {1}", (i + 1), avg);    }    return;} // Driver Codestatic int Main(){    float[] arr = new float[]{ 10, 20, 30,                               40, 50, 60 };    int n = arr.Length;    streamAvg(arr, n);     return 0;}} // This code is contributed by mits
<?php// Returns the new average// after including xfunction getAvg($x){    static $sum;    static $n;    $sum += $x;    return (((float)$sum) / ++$n);} // Prints average of// a stream of numbersfunction streamAvg($arr, $n){    for ($i = 0; $i < $n; $i++)    {        $avg = getAvg($arr[$i]);        echo "Average of " . ($i + 1) .             " numbers is ".$avg." \n";    }    return;} // Driver Code$arr = array(10, 20, 30,             40, 50, 60);$n = sizeof($arr) / sizeof($arr[0]);streamAvg($arr, $n); // This code is contributed by mits?>
<script>// javascript program to return// Average of a stream of numbers     var sum=0, n=0;     // Returns the new average    // after including x    function getAvg(x) {        sum += x;        n++;        return (sum / n);    }     // Prints average of a    // stream of numbers    function streamAvg( arr , m) {        var avg = 0;        for (i = 0; i < m; i++) {            avg = getAvg(parseInt(arr[i]));            document.write("Average of " + (i + 1) + " numbers is " + avg.toFixed(1)+"<br/>");        }        return;    }     // Driver Code             var arr =  [ 10, 20, 30, 40, 50, 60 ];        var m = arr.length;        streamAvg(arr, m); // This code is contributed by todaysgaurav</script>
Output:  
Average of 1 numbers is 10.0
Average of 2 numbers is 15.0
Average of 3 numbers is 20.0
Average of 4 numbers is 25.0
Average of 5 numbers is 30.0
Average of 6 numbers is 35.0
Time Complexity: O(n)
Auxiliary Space: O(1)
Thanks to Abhijeet Deshpande for suggesting this optimized version. Related article: Program for an average of an array (Iterative and Recursive)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Smitha Dinesh Semwal
jit_t
Mithun Kumar
rathbhupendra
todaysgaurav
subham348
subhammahato348
shivanisinghss2110
rishavmahato348
array-stream
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays