Code a C program to read five integer values from data.txt to console; calculate and display the sum and average thereof. Use the following data to create your text file: 6,45,12,67,9. (Hint: refer to video presentation on Files and streams)
#include <stdio.h>
int main()
{
FILE* fin;
int value, sum, i;
double avg;
fin = fopen("data.txt", "r");
sum = 0;
printf("Values: ");
for (i=0; i<5; i++) {
fscanf(fin, "%d,", &value);
printf("%d", value);
if (i < 4) {
printf(", ");
}
else {
printf("\n");
}
sum += value;
}
fclose(fin);
avg = sum / 5.0;
printf("The sum is %d, average: %.2f\n", sum, avg);
return 0;
}
Comments
Leave a comment