Home > OS >  Calculating sum in 2d array for each row
Calculating sum in 2d array for each row

Time:11-11

i'm very new to C and im trying to do some exercise about data handling and 2d array so my problem is I seems to get weird results when im trying to run this code that i write to calculate the sum of 1st row in 2d array and the datafile that i use should look like this

1 19 93 92 87
1 20 76 87 75
1 19 75 87 80
1 22 86 23 30
1 20 89 82 29
1 21 28 39 31
1 22 39 21 49
1 20 40 39 19
1 20 22 11 22
1 19 75 90 15

this is the code that i use

void sumRow(){
    int data [10][5];
    float sum;
    ifstream f("datafile.txt");
    for(int row = 0; row < 10; row  ){
        for(int column = 0; column < 5; column  ){
            f >> data[row][column];
        }
    }
    for (int column = 2; column < 5;column  ){
        sum = data[1][column];
    }
    cout << sum;
}

CodePudding user response:

Shouldn't your first row index be 0 instead of 1 and if you want sum of all the elements of first row then why start the for loop with column = 2 rather than column = 0.

CodePudding user response:

The index of the first row (and column) on arrays in c is 0, so if you want to calculate the sum of the items on the first row you should do:

for (int column = 0; column < 5; column  ){
    sum  = data[0][column];
}
  • Related