Write a C program to calculate mean and variance using functions.
#include <stdlib.h>
#include <math.h>
/* calculates mean and variance */
void calculateMeanVariance() {
float *x, mean = 0, sd, variance;
int temp, num, i, j;
/* get the number of entries from user */
printf("Enter the no of entries:");
scanf("%d", &num);
x = (float *)malloc(sizeof (float) * num);
/* get n inputs from user */
printf("Enter your inputs:\n");
for (i = 0; i < num; i++)
scanf("%f", &x[i]);
/* calculate the mean */
for (i = 0; i < num; i++)
mean = mean + x[i];
mean = mean / num;
/* calculate the varianceiance*/
for (i = 0; i < num; i++)
variance = variance + pow((x[i] - mean) , 2);
variance = variance / num;
printf("Variance: %f\n", variance);
printf("Mean: %f\n", mean);
return;
}
int main() {
calculateMeanVariance();
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the no of entries:5
Enter your inputs:
10
20
30
40
50
Variance: 200.000000
Mean: 30.000000
Enter the no of entries:5
Enter your inputs:
10
20
30
40
50
Variance: 200.000000
Mean: 30.000000
No comments:
Post a Comment