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;
}
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);
}
© 2024 OneMinuteCode. All rights reserved.