Answer to Question #258757 in Visual Basic for theblacksun

Question #258757

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:32-0400
#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:


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