C Code Snippets 6 - Average and Standard Deviation Calculation Using an Array




The following program takes N number of elements from user(where, N is specified by user), stores data in an array and calculates the average and the standard deviation of those numbers.



/**
* Author : Berk Soysal
*/

#include <stdio.h>
#include <math.h>

int main()
{
    //Define the integer Variables
    int i, N;

    printf("\nThis Program Calculates the Average");
    printf(" and the Standard Dev. of the Entered Values;\n\n");
    printf("How Many Numbers ? :");
    scanf("%d",&N); //Get the number of elements of the array
    printf("\n");
    double average, sum=0.0,std, x[N];

    //Calculate the SUM
    for(i=0; i<N; i++)
    {
        printf("%d. number : ",i+1);
        scanf("%lf",&x[i]);

        sum += x[i];
    }
    //Calculate the Average
    average = sum/N;

    // Calculate the Standard Deviation
    for(sum = 0.0, i=0; i<N; i++)
    {
        sum += (x[i]-average)*(x[i]-average);
    }

    std = sqrt( sum/(N-1) );

    //Print
    printf("\nThe Average is = %1.3lf\n",average);
    printf("\nThe Standard Deviation is = %1.3lf\n",std);
    return 0;
}



Result



If you have any questions or comments, please leave a comment below. Thanks. 
Keywords: CCode Snippets
Author:

Software Developer, Codemio Admin


Disqus Comments Loading..