C program to find standard deviation; Through this tutorial, we will learn how to find the standard deviation in c program.
Programs to Calculate Standard Deviation in C
- C Program to Find Standard Deviation
- C Program to Find Standard Deviation using Function
C Program to Find Standard Deviation
/* Standard Deviation - Calculate standard deviation of n numbers */
#include <stdio.h>
#include <math.h>
void main()
{
int i, n, x[50] ;
float avg, std, sum = 0, s = 0 ;
printf("Enter the number of elements: ") ;
scanf("%d", &n) ;
printf("Enter the elements:\n") ;
for(i=0 ; i<n ; i++)
{
scanf("%d", &x[i]) ;
sum=sum+x[i] ;
}
avg=sum/n ;
for(i=0 ; i<n ; i++)
s = s + pow(x[i]-avg, 2) ;
std = sqrt(s/n) ;
printf("The standard deviation of given numbers is %f",std);
return 0;
}
The output of the above c program; as follows:
Enter the number of elements: 5 Enter the elements: 1 2 3 4 5 The standard deviation of given numbers is 1.414214
C Program to Find Standard Deviation using Function
// SD of a population
#include <math.h>
#include <stdio.h>
float calculateSD(float data[], int n);
int main() {
int i, n;
float data[50];
printf("Enter the number of elements: ") ;
scanf("%d", &n) ;
printf("Enter the elements:\n") ;
for (i = 0; i < n; ++i)
scanf("%f", &data[i]);
printf("\nStandard Deviation = %.6f", calculateSD(data, n));
return 0;
}
float calculateSD(float data[], int n) {
float sum = 0.0, mean, SD = 0.0;
int i;
for (i = 0; i < n; ++i) {
sum += data[i];
}
mean = sum / n;
for (i = 0; i < n; ++i) {
SD += pow(data[i] - mean, 2);
}
return sqrt(SD / n);
}
The output of the above c program; as follows:
Enter the number of elements: 5 Enter the elements: 1 2 3 4 5 Standard Deviation = 1.414214