luc062.c (1164B)
1 /* For the following set of n data points (x, y), write a program to compute the correlation coefficient r. 2 */ 3 4 /* Let Us C, Chap- 13 (Arrays), Qn No.: B(h) */ 5 6 /* This file is auto-generated by a bot. */ 7 /* This code is not compiled; it is for reference only. */ 8 9 10 #include <stdio.h> 11 #include <math.h> 12 #include <stdlib.h> 13 14 int main() 15 { 16 double x[] = {34.22, 39.87, 41.85, 43.23, 40.06, 53.29, 53.29, 54.14, 49.12, 40.71, 55.15}; 17 double y[] = {102.43, 100.93, 97.43, 97.81, 98.32, 98.32, 100.07, 97.08, 91.59, 94.85, 94.65}; 18 19 int n = 11, i; 20 double sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0, sum_y2 = 0; 21 double numerator, denominator, r; 22 23 for (i = 0; i < n; i++) 24 { 25 sum_x += x[i]; 26 sum_y += y[i]; 27 sum_xy += x[i] * y[i]; 28 sum_x2 += x[i] * x[i]; 29 sum_y2 += y[i] * y[i]; 30 } 31 32 numerator = (n * sum_xy) - (sum_x * sum_y); 33 denominator = sqrt((n * sum_x2 - sum_x * sum_x) * (n * sum_y2 - sum_y * sum_y)); 34 35 if (denominator != 0) 36 r = numerator / denominator; 37 else 38 r = 0; // Avoid division by zero 39 40 printf("Correlation coefficient (r) = %.4f\n", r); 41 42 return 0; 43 }