Answer to Question #258761 in C for theblacksun

Question #258761

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

1
Expert's answer
2021-10-30T03:13:30-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS