Write a program that reads an array X of size N and calculates that mean and the variance.

\(\mu=\frac{\sum_{i=0}^{N-1}X[i]}{N}\)

\(\sigma^2=\frac{\sum_{i=0}^{N-1}(X[i]-\mu)}{N}\)

 


Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>

#define NB_ELEMENT 10

void main()
{
	int i, size;
	float vector[NB_ELEMENT];
	float mean, variance, diff;

	do{
		printf("Enter the number of elements: ");
		scanf("%d", &size);
	}while(size<=0 || size > NB_ELEMENT);
	
	for (i = 0; i < size ; i++) {
		printf("Enter Element %d: ", i );
		scanf("%f", &vector[i]);
	}

	

	/* mean calculus */
	mean = 0;
	for (i = 0; i < size ; i++) {
		mean += vector[i];
	}
	mean /= size ;	

	/* variance calculus */
	variance = 0;	
	for(i = 0; i < size ; i++) {
		diff = vector[i]-mean;
		variance += diff*diff;	
	}
	variance /= size ;	

	printf("The mean is equal to %.3f\n", mean);
	printf("The variance is equal to %.3f\n", variance);
	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Star pattern 21