How to calculate moving average in C++

So, guys today we will learn How to calculate moving average in C++. Let’s do it together. The topic is basically to find the average of the given array, sequentially moving forward.

First of all, we will calculate the sum of the array as per the given length(for which we need an average) after which we will calculate the average (sum on the given length divided by the average).

Calculate the moving average in C++

For calculating we need to make sure that all the declared elements are as per the requirement of the programmer. We also need to confirm that value of sum and average is initialized with zero else it may use the garbage value because of which the answer may vary.

The next precaution to take is that we will declare the average with the float or double data type. You may think Why am I doing this? If you are Student than you need not worry but once you use this program in the corporate sector there are millions of calculations. If we don’t consider the decimal values it may provide us the answer that’s for sure but with the huge difference.

Ther might be some of you who might not know what moving average means. Don’t worry! Let’s take an example

Input={1,2,3,4}

I am considering the length of 2

Calculation :

Sum : 1+2=3         Avg : 3/2 = 1.5

Sum : 2+3=5         Avg : 5/2=2.5

Sum : 3+4=7         Avg : 7/2=3.5

All the averages are considered as the output.

#include <iostream>
using std::cout;
using std::endl;


int main() {

   
   const int size = 4;
   double N[size] = {1, 2, 3, 4};
   int l_size = 2;
   double sum = 0;
   double mAvg = 0;


 
   for (int i = 0; i <= (size - l_size); i++) {

      sum = 0;                
      cout << "Numbers ";    

      
      for (int j = i; j < i + l_size; j++) {
         sum += N[j];          
         cout << N[j] << " ";  
      }

      
      mAvg = sum / l_size;
      cout << endl << "Moving Average: " << mAvg << endl;

   }


   return 0;
}

 

Output :

Numbers 1 2                                                                                                                                    
Moving Average: 1.5                                                                                                                           

Numbers 2 3                                                                                                                                    
Moving Average: 2.5

Numbers 3 4                                                                                                                                    
Moving Average: 3.5


This is how we can calculate the moving average in C++. Want to learn more? Have a look!
Add two numbers without using Arithmetic Operators in C++

Write a program to print Diamond pattern using C++

Leave a Reply

Your email address will not be published. Required fields are marked *