Joshua Hodge
Joshua Hodge

Reputation: 17

How to add values in a 2d matrix with same first index (c++)

I have a set of values stored in a 2d matrix. I want to create separate totals for the values which have the same first index. Here's a short example:

typedef int matrix [9][9];
matrix sampleMatrix;

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   for (int j = 0; j < 9; j++){
        //here's where I'm stuck
        //if i = 1, then total all values with i = 1 etc.
        if(sampleMatrix[i]){ 
        int sum = sum + sampleMatrix[i][j];
        }
        std::cout << i << " Total: " << sum << std::endl;
   }

}

Thanks for any help.

Upvotes: 0

Views: 48

Answers (2)

Ufuk Can Bicici
Ufuk Can Bicici

Reputation: 3649

Build a integer array of the length 9 like int sums [9] and initialize each entry with 0. In your double for loop, for every sampleMatrix [i][j] entry, add it to the corresponding entry of the sums array, like sums [i] += sampleMatrix [i][j]

Upvotes: 0

JGC
JGC

Reputation: 12997

If you initialize all values of array with 0 then you would be able to sum up all values of each i'th index

matrix sampleMatrix;
for(int i=0;i<9;i++){
    for(int j=0;j<9;j++){
         sampleMatrix[i][j]=0;
    }
}

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   int sum=0;
   for (int j = 0; j < 9; j++){
          sum = sum + sampleMatrix[i][j];       
   }
   cout<<sum<<endl;
}

Upvotes: 1

Related Questions