# C Unusual result values for rows/columns in a rudimentary two-dimensional array

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

After making a two-dimensional array using random numbers, A program that outputs an array in a two-dimensional table after obtaining the sum of each row and each column. But if you compare the table with the total value derived, it doesn't match. For example, the total of two rows is 72, but if you actually find the sum of two rows in the table, you get 179. Where did it go wrong?

``````#include <stdio.h>
#include <time.h>
#define ROWS 5 //column (horizontal)
#defineCOLS 3 //row (vertical)

int main(void)
{
int a[ROWS][COLS];

srand((unsigned)time(NULL));

for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
a[i][j] = rand() % 100;
}
}

int sum = 0;

for (int i = 0; i < ROWS; i++)
{
sum = 0;

for (int j = 0; j < COLS; j++)
{
sum += a[i][j];
}

printf("total in column %d\n", i, sum);
}

for (int j = 0; j < COLS; j++)
{
sum = 0;

for (int i = 0; i < COLS; i++)
{
sum += a[i][j];
}

printf("sum of row %d\n",j,sum);
}

for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
printf("%d ", a[i][j]);
}

printf("\n");
}

return 0;
}
``````

c visual-studio list time array

2022-09-20 15:40

If you look closely at the loop to find the sum of the rows, there is a typo.

``````    for (int j = 0; j < COLS; j++)
{
sum = 0;

for (int i = 0; i < COLS; i++)
{
sum += a[i][j];
}

printf("sum of row %d\n",j,sum);
}
``````

In the above code, the conditions of the double for loop are all the same as the ` variable < COLS`. Change the code above as below.

``````    for (int j = 0; j < COLS; j++)
{
sum = 0;

for (int i = 0; i < ROWS; i++)
{
sum += a[i][j];
}

printf("sum of row %d\n",j,sum);
}

``````

2022-09-20 15:40

Popular Tags
python x 1175
android x 247
c x 235
java x 192
javascript x 106
mysql x 30
html x 27
node.js x 24
php x 21
list x 19