Search code examples
ctext-filesstdio

Having Trouble Counting and Summing Integers from Text File


Sorry for being such a novice.

For this question I used C language, and the libraries stdlio.h and stdlib.h.


Question

So a question is asking me to:

  1. Open a text file named 'numbers.txt' in read mode. This text file has 6 integers in it.
  2. Read the 6 integers from that text file using a loop.
  3. Calculate and display the total and average of those 6 integers.

The text file 'numbers.txt' holds the integers: 5, 10, 15, 20, 25.

Here's my code:

    FILE *n;
    n = fopen("numbers.txt", "r");
    int a, num, sum = 0;
    float avg;

    for (a = 0; a < 6; a++) {
        fscanf(n, "%d", &num);
        sum = sum + num;
    }
    avg = sum / (a - 1);
    printf("Sum = %d\nAverage = %.2f\n\n", sum, avg);
    fclose(n);

Another variation of the question is that I need to use a while loop to read the integers in the text file.

Here's my code for that:

    FILE *n;
    n = fopen("numbers.txt", "r");
    int a = 0, num, sum = 0;
    float avg;

    while (fscanf(n, "%d", &num) != EOF) {
        fscanf(n, "%d", &num);
        sum = sum + num;
        a++;
    }

    avg = sum / a;
    printf("Sum = %d\nAverage = %.2f\n\n", sum, avg);
    fclose(n);

Problem

When I run each of the above programs, I expect this output:

Sum = 75
Average = 15.00

However I get this instead (for the first code):

Sum = 100
Average 20.00

And this (for the second code):

Sum = 55
Average = 18.00

How am I able to get the correct output from both of these programs?

Again I apologise for how basic this question is. Nonetheless, any help would be appreciated.


Solution

  • In the first one, you tried to read one-to many numbers, but since there were only 5 numbers, the last number was added twice to your sum, so you ended up adding an extra 25 to the sum to get 100.

    In the second code, after reading the last number, the end of the file was reached, so your code did not get the opportunity to add the last read number, so you missed adding 25 to your sum.


    You were much closer with your first code, just change the for-loop to only iterate 5 times