This blog is under construction

Tuesday 9 July 2013

C program to calculate correlation coefficient

How to find correlation coefficient?
Please check the below link to get better understanding on correlation coefficient.

Write a C program to calculate correlation coefficient.


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

  int main() {
        int x[100], y[100], xy[100], xsquare[100], ysquare[100];
        int i, n, xsum, ysum, xysum, xsqr_sum, ysqr_sum;
        float coeff, num, deno;

        xsum = ysum = xysum = xsqr_sum = ysqr_sum = 0;

        /* get the number of entries from the user */
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* get the values for x and y  from the user */
        printf("Enter the value for x and y:\n");
        for (i = 0; i < n; i++) {
                printf("x[%d] and y[%d]: ", i, i);
                scanf("%d%d", &x[i], &y[i]);
        }

        /* find the needed data to manipulate correlation coeff */
        for (i = 0; i < n; i++) {
                xy[i] = x[i] * y[i];
                xsquare[i] = x[i] * x[i];
                ysquare[i] = y[i] * y[i];
                xsum = xsum + x[i];
                ysum = ysum + y[i];
                xysum = xysum + xy[i];
                xsqr_sum = xsqr_sum + xsquare[i];
                ysqr_sum = ysqr_sum + ysquare[i];
        }

        num = 1.0 * ((n * xysum) - (xsum * ysum));
        deno = 1.0 * ((n * xsqr_sum - xsum * xsum)* (n * ysqr_sum - ysum * ysum));

        /* calculate correlation coefficient */
        coeff = num / sqrt(deno);

        /* print the result */
        printf("Correlation Coefficient : %.4f\n", coeff);
        return 0;
  }


Note:
gcc corr_coeff.c -lm => linked math library since we have used sqrt() math function.

  Output:
  jp@jp-VirtualBox:~/$ gcc corr_coeff.c -lm
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:6
  Enter the value for x and y:
  x[0] and y[0]: 43 99
  x[1] and y[1]: 21 65
  x[2] and y[2]: 25 79
  x[3] and y[3]: 42 75
  x[4] and y[4]: 57 87
  x[5] and y[5]: 59 81
  Correlation Coefficient : 0.5298




See Also:

6 comments:


  1. Very informative article.Thank you author for posting this kind of article .


    http://www.wikitechy.com/view-article/power-function-in-c-with-example-and-explanation



    Both are really good,
    Cheers,
    Venkat

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Thanks 😊
    You can also find Programming exercise in c++ here.
    https://myustaadg.com/category/programs/

    ReplyDelete