# Thread: howto build this addition matrix

1. ## howto build this addition matrix

this matrix
0 2 2 4
0 2 2 1
8 6 0 3

should return the sum of 224+221+8603
this is a part of a code
why its not working??
Code:
```int power=1;
int coef=0;
for (index = 0; index < rows; index++)
{
for (kndex = 0; kndex < cols; kndex++)
{
for (z=0;z<(cols-kndex);z++){
pwer=pwer*10;
}
coef=matrix[index][kndex]*pwer;

tsum=tsum+coef;
}

}
printf("%d ",tsum);```

2. You should spread it out and make it easier to understand. I find myself getting lost in embedded loops all the time. If you want, you can use this method:

Code:
```#include <stdio.h>

int main (void)
{
int matrix[] = {0, 2, 2, 4, 0, 2, 2, 1, 8, 6, 0, 3};
int i, j, sum = 0;

for (i = 0; i < 12; i++)
{
switch (i % 4)
{
case 0:
sum += matrix[i] * 1000;
break;
case 1:
sum += matrix[i] * 100;
break;
case 2:
sum += matrix[i] * 10;
break;
case 3:
sum += matrix[i] * 1;
break;
}

}

printf("%d\n", sum);

return 0;
}```

3. It's not working because your algorithm (at least as implemented) is horribly, horribly broken. I can't tell whether what you're trying to do is correct and you've just flubbed the algorithm, or your algorithm was wrong to start with. So trace through it, already (C is not a write-only language!) and see if it's doing what you expect.

4. Originally Posted by transgalactic2
this matrix
0 2 2 4
0 2 2 1
8 6 0 3

should return the sum of 224+221+8603
this is a part of a code
why its not working??
Code:
```int power=1;
int coef=0;
for (index = 0; index < rows; index++)
{
for (kndex = 0; kndex < cols; kndex++)
{
for (z=0;z<(cols-kndex);z++){
pwer=pwer*10;
}
coef=matrix[index][kndex]*pwer;

tsum=tsum+coef;
}

}
printf("%d ",tsum);```
1) power is misspelled or never used
2) pwer needs to be reset to 1 after the tsum=tsum+coef, line of code
3) z in the for loop, needs to start at 1, not zero.

Your algorithm is fine, just a few mistakes. Here's a corrected version:

Code:
```#include <stdio.h>
#define rows 3
#define cols 3

int main()  {
int index, kndex, z, pwer, tsum, coef;

int matrix[rows][cols] = {
{ 3, 5, 5 },      //355
{ 1, 2, 5 },      //125
{ 4, 5, 6 } };    //456
//======================
//                  936

tsum = coef = 0;
pwer = 1;
for (index = 0; index < rows; index++)
{
for (kndex = 0; kndex < cols; kndex++)
{
for (z=1;z<(cols-kndex);z++){
pwer=pwer*10;
}
coef=matrix[index][kndex]*pwer;

tsum=tsum+coef;
pwer = 1;
}

}
printf("%d ",tsum);
tsum  = getchar();
return 0;
}```

5. Ew calculating the powers of 10 for every column seems a bit wasteful...

Code:
```   for(row = 0; row < ROWS; row++)
{
power = 1;

for(col = COLS - 1; col >= 0; col--)
{
coeff += matrix[row][col] * power;
power *= 10;
}

printf("%d\n", coeff);
}```
Is MUCH nicer. You could even make it faster by pre-calculating the powers of 10.

Also try not to strip the vowels out of your variable names, ie "pwer" is a terrible name for "power".

6. thanks

Popular pages Recent additions