Print the Variance
In this step, you will learn how to format and print the variance calculation with different precision levels and create a function to make the code more modular.
Modify the previous variance.c
file to improve variance printing:
cd ~/project
nano variance_print.c
Write the following C code to enhance variance output:
#include <stdio.h>
#include <math.h>
// Function to calculate variance
float calculate_variance(int numbers[], int count) {
int sum = 0;
float mean, variance = 0.0;
// Calculate sum and mean
for (int i = 0; i < count; i++) {
sum += numbers[i];
}
mean = (float)sum / count;
// Calculate sum of squared deviations
for (int i = 0; i < count; i++) {
variance += pow(numbers[i] - mean, 2);
}
// Divide by count to get variance
variance /= count;
return variance;
}
// Function to print variance with different formats
void print_variance(float variance) {
printf("Variance Representations:\n");
printf("1. Standard Format: %.2f\n", variance);
printf("2. Scientific Notation: %e\n", variance);
printf("3. Precise Format: %.4f\n", variance);
}
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int count = sizeof(numbers) / sizeof(numbers[0]);
// Calculate and print variance
float variance = calculate_variance(numbers, count);
printf("Original Numbers: ");
for (int i = 0; i < count; i++) {
printf("%d ", numbers[i]);
}
printf("\n\n");
print_variance(variance);
return 0;
}
Compile and run the program:
gcc variance_print.c -o variance_print -lm
./variance_print
Example output:
Original Numbers: 10 20 30 40 50
Variance Representations:
1. Standard Format: 200.00
2. Scientific Notation: 2.000000e+02
3. Precise Format: 200.0000
Key improvements:
- Created separate functions for variance calculation
- Added multiple variance printing formats
- Demonstrated different ways to represent variance