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
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE* dataFile;
int value, sum=0;
double avg;
char *token;
int size=0;
dataFile = fopen("data.txt", "r");
if(dataFile != NULL)
{
char line[1000];
fgets(line, sizeof(line), dataFile);
token = strtok(line, ",");
printf("All values:\n");
while (token != NULL) {
value=atoi(token);
sum+=value;
printf("%d ",value);
size++;
token = strtok(NULL, ",");
}
fclose(dataFile);
}
avg = (double)sum / size;
printf("\n\nThe sum is %d, average: %.2f\n", sum, avg);
getchar();
getchar();
return 0;
}
The file with numbers:
Comments
Leave a comment