C Program to Calculate Standard Deviation
This program calculates the standard deviation of an individual series using arrays. Visit this page to learn about Standard Deviation.
To calculate the standard deviation, calculateSD()
a function is created. The array containing 10 elements is passed to the function and this function calculates the standard deviation and returns it to the main()
function.
Example: Program to Calculate Standard Deviation
#include <stdio.h>
#include <math.h>
float calculateSD(float data[]);
int main()
{
int i;
float data[10];
printf("Enter 10 elements: ");
for(i=0; i < 10; ++i)
scanf("%f", &data[i]);
printf("\nStandard Deviation = %.6f", calculateSD(data));
return 0;
}
float calculateSD(float data[])
{
float sum = 0.0, mean, standardDeviation = 0.0;
int i;
for(i=0; i<10; ++i)
{
sum += data[i];
}
mean = sum/10;
for(i=0; i<10; ++i)
standardDeviation += pow(data[i] - mean, 2);
return sqrt(standardDeviation/10);
}
Output
Enter 10 elements: 1 2 3 4 5 6 7 8 9 10 Standard Deviation = 2.872281
C program to calculate the standard deviation of a set of numbers:
#include <stdio.h>
#include <math.h>
#define MAX_SIZE 100
int main()
{
int n, i;
float arr[MAX_SIZE];
float mean, sum = 0.0, std_dev = 0.0;
// Input size of the array
printf("Enter the number of elements (max %d): ", MAX_SIZE);
scanf("%d", &n);
// Input elements of the array
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%f", &arr[i]);
}
// Calculate mean
for (i = 0; i < n; i++) {
sum += arr[i];
}
mean = sum / n;
// Calculate standard deviation
for (i = 0; i < n; i++) {
std_dev += pow(arr[i] - mean, 2);
}
std_dev = sqrt(std_dev / n);
// Output result
printf("Standard deviation = %.2f\n", std_dev);
return 0;
}
This program first defines an array arr
of size MAX_SIZE
, where MAX_SIZE
is a constant integer. It then prompts the user to input the size of the array and its elements, calculates the mean of the elements, and then calculates the standard deviation using a loop and the pow
and sqrt
functions from the math.h
library. Finally, it outputs the standard deviation.
Note that the program assumes that the array size is less than or equal to MAX_SIZE
. If the user inputs a size larger than MAX_SIZE
, the program will not work correctly. Additionally, the program assumes that the input numbers are floating-point values. If the user inputs integer values, the program will not produce correct results.