Mega Code Archive

 
Categories / C / Code Snippets
 

Calculating a floating-point average using pointers

#include <stdio.h> #include <stdlib.h> #include <ctype.h> int main() { double *values = NULL; double sum = 0.0; int capacity = 5; int j = 0; values= (double*)malloc((capacity)*sizeof(double)); if(values == NULL){ printf("Memory allocation failed. Terminating program."); } for(j=0;j<capacity;j++){ values[j] = j; printf(" %.2lf",values[j]); } for(j = 0 ; j<capacity ; j++) sum += *(values+j); /* Output the average */ printf("\n The average of the the values you entered is %.2lf.\n", sum/capacity); free(values); /* We are done - so free the memory */ }