C Program to Find Standard Deviation (User Defined Function)


Question: Write a program in C to read an array containing n numbers and find standard deviation using user defined function. Use two different user defined function one for calculating mean and one to calculate standard deviation.

Standard Deviation Using User Defined Function


#include<stdio.h>
#include<math.h>

/* Function prototypes */
float stddev(float a[100], int n);
float mean(float a[100], int n);

void main()
{
 float a[100], res;
 int i, n;
 clrscr();
 printf("Enter n:\n");
 scanf("%d", &n);
 /* Reading array */
 for(i=0;i< n;i++)
 {
  printf("a[%d]=",i);
  scanf("%f", &a[i]);
 }
 /* Function Call */
 res = stddev(a,n);
 /* Displaying result */
 printf("Standard deviation = %f", res);
 
 return 0;
}
/* Function definition for stddev */
float stddev(float a[10], int n)
{
 int i;
 float fsum=0.0, m;
 m = mean(a,n);
 for(i=0;i< n;i++)
 {
  fsum = fsum + (a[i]-m)*(a[i]-m);
 }
 return(sqrt(fsum/n));
}
/* Function definition for mean */
float mean(float a[10], int n)
{
 int i;
 float sum=0.0;
 for(i=0;i< n;i++)
 {
  sum = sum + a[i];
 }
 return(sum/n);
}