New to C, simple loop

I have a testdata1 file, and I have 20 values โ€‹โ€‹of the same number. How can I add all these numbers and then print this number on the screen. I currently have this, but I know that this is probably the worst way to do this and probably should use a loop.

#include <stdio.h>

int main(int argc, char *argv[]) {
FILE* fin;
fin = fopen("testdata1.txt", "r");
int n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14, n15, n16, n17, n18, n19, n20, sum;

fscanf(fin, "%d", &n1);
fscanf(fin, "%d", &n2);
fscanf(fin, "%d", &n3);
fscanf(fin, "%d", &n4);
fscanf(fin, "%d", &n5);
fscanf(fin, "%d", &n6);
fscanf(fin, "%d", &n7);
fscanf(fin, "%d", &n8);
fscanf(fin, "%d", &n9);
fscanf(fin, "%d", &n10);
fscanf(fin, "%d", &n11);
fscanf(fin, "%d", &n12);
fscanf(fin, "%d", &n13);
fscanf(fin, "%d", &n14);
fscanf(fin, "%d", &n15);
fscanf(fin, "%d", &n16);
fscanf(fin, "%d", &n17);
fscanf(fin, "%d", &n18);
fscanf(fin, "%d", &n19);
fscanf(fin, "%d", &n20);

sum = n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9 + n10 + n11 + n12 + n13 + n14 + n15 + n16 + n17 + n18 + n19 + n20;
printf("The sum of numbers is %d.\n", sum);
fclose(fin);

return 0; 
}
+4
source share
3 answers

You do not need to use an array. Just add the numbers together when you read them:

#include <stdio.h>

int main(int argc, char *argv[]) {
    int i, n, sum = 0;
    FILE* fin = fopen("testdata1.txt", "r");
    if (!fin) {
        fprintf(stderr,"Error: Unable to open file\n");
        return 1;
    }

    for (i=0; i<20; i++) {
        if (fscanf(fin, "%d", &n) != 1) {
            fprintf(stderr,"Error: Unexpected input\n");
            fclose(fin);
            return 1;
        }
        sum += n;
    }
    printf("The sum of numbers is %d.\n", sum);
    fclose(fin);

    return 0; 
}
+7
source

I'm not quite sure what you are asking here, but I'm sure you are asking for a loop that can add all these values, so I will get away from this.

, , , . 20 . :

. , 20 : int values[20]

. int ,

A :

int main(int argc, char* argv[]){
    int sum, values[20];
    FILE* file = fopen("file");
    for (i=0; i<20; i++) {
        if (fscanf(fin, "%d", &values[i]) != 1) {
            printf("%s\n","error handling here");
            fclose(fin);
            return 1;
        }
        sum += n;
    }
}

B, ossifrage :)

+1

Of course you should use a loop, this time you don't need arrays; just replace the part in which you read each number and put this:

for (i=0; i<20; i++) {
  fscanf(fin, "%d", &n1);
  sum += n1;
}

And here you are! your variable sumwill contain the amount

0
source

Source: https://habr.com/ru/post/1670008/


All Articles