# Average of a stream of numbers in C++

C++Server Side ProgrammingProgramming

Average of numbers is the sum of numbers divided by the total number of numbers.

In this problem, we are given a stream of numbers. And we will print average of the number at every point.

Let’s take an example of how it works −

We have a stream of 5 number 24 , 76 , 29, 63 , 88

The average at each point of the stream would be −

24 , 50 , 43 , 48 , 56.

For this we will find the average of the stream every time a number is added to the stream. So, we need to find the average of 1 number , 2 numbers , 3 numbers and so on. We will make use of previous average for this.

## Algorithm

Step 1 : for i -> 0 to n (length of stream).
Step 2 : find the average of elements using formula :
Average = (average * i) + i / (i+1)
Step 3 : print average.

## Example

Live Demo

#include <iostream>
using namespace std;
int main(){
int arr[] = { 24 , 76 , 29, 63 , 88 };
int average = 0;
int n = sizeof(arr) / sizeof(arr);
for(int i = 0 ; i< n ; i++){
average = ((average * i) + arr[i]) / (i+1);
cout<<"The average of "<<i+1<<" numbers of the stream is "<<average<<endl;
}
return 0;
}

## Output

The average of 1 numbers of the stream is 24
The average of 2 numbers of the stream is 50
The average of 3 numbers of the stream is 43
The average of 4 numbers of the stream is 48
The average of 5 numbers of the stream is 56

The same algorithm is applicable for all data types. And can be used to calculate the average of stream at every point.