Monday, October 19, 2015

Average and standard deviation program

/* Average (mean) and standard deviation program */
/*      avg_std3.c                               */

#include <stdio.h>

#include <stdlib.h>

#include <math.h>
/* Require math.h to perform square-root and square calculations */
int
main(
){
    int i,j;
    int x[10];
    double sum,avg,sigma,sigma_sq;
    int *ptr;

    sum = 0;

    for(i=0;i<10;i++)
    {
        x[i]=i;
   
        /* ptr is assigned the value of the x[i] element address */
        ptr=&x[i];           
               
        /* notice for long printf() statements, close the " and open " on next line */
        printf("\nx[%d] = %d, at address using pointer *ptr %X, "
                "and using pointer ADDRESS operator &x[i] = %X\n",i,x[i],ptr,&x[i]);   
       
        /* taking a running average by using the variable, sum  */
        /* also using the pointer *ptr to 'point' to the value  */
        sum=sum+*ptr;
               
    }
   
    j=i;

    printf("\nSum = %f\n", sum);

    avg=sum/(i);
    printf("\nAverage = %f\n", avg);

    sum=0;
    for (i=0;i<10;i++)
    {
        /* the pow(a,b) = a^b using the math.h library */

        sum=sum+pow((x[i]-avg),2);
    }
   
    /*calculate the variance whichi is the square of the standard deviation, sigma_sq*/

    sigma_sq=sum/(i);

    /*take the square root of the variance to calculate the standard deviation, sigma*/

    /* sqrt(a) is the square root function using the math.h library */

    sigma=sqrt(sigma_sq); 


    printf("\nVariance sigma_sq = %f\n\n",sigma_sq);

    printf("\nStandard Deviation sigma = %f\n\n",sigma);

    /******************************************************************/
    /* to compile,                                                    */
    /*      gcc avg_std3.c -lm                                        */
    /*                                                                */
    /* the -lm links the math.h library to the program avg_std3.c     */
    /* during compile.                                                */
    /*                                                                */
    /* the program can be compiled in the 'me' directory              */
    /*                                                                */
    /* To execute, ./a.out                                            */
    /*                                                                */
    /* To name an executable named avg_std3:                          */
    /*      gcc avg_std3.c -o avg_std3 -lm                            */
    /******************************************************************/

    return(0);
}

No comments:

Post a Comment