Answer to Question #258359 in C for theblacksun

Question #258359

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)

1
Expert's answer
2021-10-28T17:38:45-0400
#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;
}

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