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* f;
int number, sum=0;
double average;
int size=0;
f = fopen("data.txt", "r");
if(f != NULL)
{
char line[1000];
fgets(line, sizeof(line), f);
char *ch = strtok(line, ",");
printf("Numbers:\n");
while (ch != NULL) {
number=atoi(ch);
sum+=number;
printf("%d ",number);
size++;
ch = strtok(NULL, ",");
}
fclose(f);
}
average = (double) sum / size;
printf("\n\nThe sum: %d\n", sum);
printf("The average: %.2f\n", average);
getchar();
getchar();
return 0;
}
Comments
Leave a comment