...

/

Example 43: Calculate Sum, Average, and Standard Deviation

Example 43: Calculate Sum, Average, and Standard Deviation

Learn how to calculate the sum, average, and standard deviation of the given numbers using pointers.

We'll cover the following...

Problem

Write a function that calculates the sum, average, and standard deviation of the given numbers. It receives five integers along with three pointers to store the results as parameters.

Example

Input (n1, n2, n3, n4, n5) Output(Sum, Average, Standard Deviation)
4, 5, 3, 7, 9 28.000000, 5.600000, 2.408319
4, -2, 8, -4, 3 9.000000, 1.800000, 4.816638

Try it yourself

Try to solve this question on your own in the code widget below. If you get stuck, you can always refer to the solution provided.

Press + to interact
#include <stdio.h>
#include <math.h>
// try to implement a code that calculates
// the sum, average and standard deviation of the given numbers
void calcSASd (int n1, int n2, int n3, int n4, int n5, float *s, float *a, float *sd){
//write your code here
}

Solution

Given below is our recommended way to approach this problem.

Press + to interact
#include <stdio.h>
#include <math.h>
void calcSASd (int n1, int n2, int n3, int n4, int n5, float *s, float *a, float *sd){
*s = n1 + n2 + n3 + n4 + n5;
*a = *s/ 5;
*sd = sqrt ((pow((n1 - *a ),2) + pow((n2 - *a),2) + pow((n3 - *a),2) + pow((n4 - *a),2) + pow((n5 - *a),2) )/4);
}
int main() {
int n1 = 4, n2 = 5, n3 = 3, n4 =7, n5 = 9;
float sum = 0; float avg = 0; float std = 0;
float *s = &sum; float *a = &avg; float *sd = &std;
calcSASd(n1, n2, n3, n4, n5,s,a,sd);
printf("%f, %f, %f",*s,*a,*sd);
return 0;
}

Explanation

The function cal_sasd() takes in five numbers as its parameters. It then calculates their sum, average, and standard deviation. Next, it assigns all the results to their respective pointers and then prints the pointer values on the console.

The formula to calculate standard deviation is:

s=1Ni= ...