I need to check if sums of i-th row and j-th column are same in 2d array and output i of the row and j of the column and sum. Also how can I make count it normally like [1][1],[1][2]
etc.
Thanks in advance.
That's what I've got and sadly it's not working
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
int sum1 = 0, sum2 = 0;
int a[2][3];
int i, j;
for (i = 0; i<2; i++)
{
for (j = 0; j<3; j++)
{
printf("a[%d][%d] = ", i, j);
scanf("%d", &a[i][j]);
}
}
for (i = 0; i<2; i++)
{
sum1 = 0, sum2 = 0;
for (j = 0; j<3; j++)
{
sum1 += a[i][j];
sum2 += a[j][i];
}
if (sum1 == sum2)
printf("row is %d and column is %d = %d", i, j, sum1);
}
return 0;
}
Your calculation of row sum seems correct but your calculation of column sum is wrong.
Try like:
for (i = 0; i<2; i++) // For every row
{
// Calculate row sum
sumRow = 0;
for (j = 0; j<3; j++)
{
sumRow += a[i][j];
}
for (j = 0; j<3; j++) // For every column
{
// Calculate column sum
sumColumn = 0;
for (i = 0; i<2; i++)
{
sumColumn += a[i][j];
}
// Compare results
if (sumRow == sumColumn)
printf("row is %d and column is %d = %d", i, j, sumRow);
}
}
The above code is however not efficient. A better way would be to pre-calculate the column sums so you won't need to repeat it.
Something like:
int columnSum[3] = {0};
for (j = 0; j<3; j++) // For every column
{
// Calculate column sum
for (i = 0; i<2; i++)
{
columnSum[j] += a[i][j];
}
}
for (i = 0; i<2; i++) // For every row
{
// Calculate row sum
sumRow = 0;
for (j = 0; j<3; j++)
{
sumRow += a[i][j];
}
for (j = 0; j<3; j++) // For every column
{
// Compare results
if (sumRow == columnSum[j])
printf("row is %d and column is %d = %d", i, j, sumRow);
}
}
Also how can I make count it normally like [1][1],[1][2]
If you want to program in C, you'll have to count like the language makes it natural - for instance, start from zero. And further in row-major. So use
Column 0 Column 1 Column 2
Row 0: [0][0] [0][1] [0][2]
Row 1: [1][0] [1][1] [1][2]