Take Square Root for Standard Deviation and Print
In this final step, you will complete the standard deviation calculation by taking the square root of the variance. Standard deviation is a key measure of data dispersion in statistical analysis.
Open the previous file to modify:
cd ~/project
nano mean_calculation.c
Update the program with standard deviation calculation:
#include <stdio.h>
#include <math.h>
#define MAX_SIZE 100
float calculateMean(int arr[], int size) {
float sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum / size;
}
float calculateVariance(int arr[], int size, float mean) {
float sumSquaredDeviations = 0;
for (int i = 0; i < size; i++) {
float deviation = arr[i] - mean;
sumSquaredDeviations += deviation * deviation;
}
return sumSquaredDeviations / size;
}
float calculateStandardDeviation(float variance) {
return sqrt(variance);
}
int main() {
int dataset[MAX_SIZE];
int size;
printf("Enter the number of elements (max %d): ", MAX_SIZE);
scanf("%d", &size);
printf("Enter %d integers:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &dataset[i]);
}
float mean = calculateMean(dataset, size);
float variance = calculateVariance(dataset, size, mean);
float standardDeviation = calculateStandardDeviation(variance);
printf("Dataset Statistics:\n");
printf("Mean: %.2f\n", mean);
printf("Variance: %.2f\n", variance);
printf("Standard Deviation: %.2f\n", standardDeviation);
return 0;
}
Compile the updated program:
gcc mean_calculation.c -o mean_calculation -lm
Run the program and input sample data:
./mean_calculation
Example output:
Enter the number of elements (max 100): 5
Enter 5 integers:
10
20
30
40
50
Dataset Statistics:
Mean: 30.00
Variance: 200.00
Standard Deviation: 14.14
Key points in the code:
- We added a new
calculateStandardDeviation
function.
- This function uses
sqrt()
from the math library to compute standard deviation.
- Standard deviation is the square root of variance.
- The main function now prints all three statistical measures.
- We continue to use
-lm
flag to link the math library.