Skip to content

Instantly share code, notes, and snippets.

@bmccormack
Created March 31, 2015 01:05
Show Gist options
  • Save bmccormack/d12f4bf0c96423d03f82 to your computer and use it in GitHub Desktop.
Save bmccormack/d12f4bf0c96423d03f82 to your computer and use it in GitHub Desktop.
Moving average example in C
#include <stdio.h>
int movingAvg(int *ptrArrNumbers, long *ptrSum, int pos, int len, int nextNum)
{
//Subtract the oldest number from the prev sum, add the new number
*ptrSum = *ptrSum - ptrArrNumbers[pos] + nextNum;
//Assign the nextNum to the position in the array
ptrArrNumbers[pos] = nextNum;
//return the average
return *ptrSum / len;
}
int main(int argc, char *argv[])
{
// a sample array of numbers. The represent "readings" from a sensor over time
int sample[] = {50, 10, 20, 18, 20, 100, 18, 10, 13, 500, 50, 40, 10};
// the size of this array represents how many numbers will be used
// to calculate the average
int arrNumbers[5] = {0};
int pos = 0;
int newAvg = 0;
long sum = 0;
int len = sizeof(arrNumbers) / sizeof(int);
int count = sizeof(sample) / sizeof(int);
for(int i = 0; i < count; i++){
newAvg = movingAvg(arrNumbers, &sum, pos, len, sample[i]);
printf("The new average is %d\n", newAvg);
pos++;
if (pos >= len){
pos = 0;
}
}
return 0;
}
@Thor-x86
Copy link

Thor-x86 commented Feb 9, 2024

What is sizeof(int) supposed to be the size of? "int" is a type

Depends on your targeted machine. On most PC, it's 4 bytes. However, other targets like Arduino Uno only have 2 bytes. So it's safer to write sizeof(int) rather than directly write 4.

For anyone who didn't familiar with C, this line

int count = sizeof(sample) / sizeof(int);

Counts how many elements in sample array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment