Reputation: 13
So I created a program that generates a random 4x4 matrix, with values ranging from 0 to 17. Afterwards, it would calculate and print the sum of each rows and columns. The problems are, (1) values of row sums are incorrect, (2) the last element, which is the m[4][4]
, seems to double in value, giving an incorrect value for the sum of Column 4 as well. Here is the code:
srand(time(NULL));
printf("Generating matrix... ");
getch();
printf("\n\n");
for (i = 1; i <= 4; i++) {
for (j = 1; j <= 4; j++) {
m[i][j] = rand() % 17;
printf("%d\t", m[i][j]);
if (i == 1) { // Calculation of Row Sums
rSum[1] += m[i][j];
} else if (i == 2) {
rSum[2] += m[i][j];
} else if (i == 3) {
rSum[3] += m[i][j];
} else if (i == 4) {
rSum[4] += m[i][j];
}
if (j == 1) { // Calculation of Column Sums
cSum[1] += m[i][j];
} else if (j == 2) {
cSum[2] += m[i][j];
} else if (j == 3) {
cSum[3] += m[i][j];
} else if (j == 4) {
printf("\n");
cSum[4] += m[i][j];
}
}
}
getch();
printf("\n\n");
for (i = 1; i <= 4; i++) { // Printing of Values
printf("Sum of Row %d: %d\n", i, rSum[i]);
printf("Sum of Column %d: %d\n", i, cSum[i]);
printf("-----------------------------------------------\n");
}
return 0;
Upvotes: 1
Views: 156
Reputation: 145307
Arrays are 0
based in C. You should change all your loops to iterate this way:
for (i = 0; i < 4; i++) {
And also change other parts of your code where you use explicit index values. This part can be simplified drastically.
The arrays rSum
and cSum
must be initialized to 0
. Failure to do it might explain the incorrect values computed by your program.
Here is an improved version:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int m[4][4];
int rSum[4] = { 0 };
int cSum[4] = { 0 };
int i, j;
srand(time(NULL));
printf("Generating matrix... ");
getch();
printf("\n\n");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
m[i][j] = rand() % 17;
printf("%d\t", m[i][j]);
rSum[i] += m[i][j]; // Calculation of Row Sums
cSum[j] += m[i][j]; // Calculation of Column Sums
}
printf("\n");
}
getch();
printf("\n\n");
for (i = 0; i < 4; i++) { // Printing of Values
printf("Sum of Row %d: %d\n", i, rSum[i]);
printf("Sum of Column %d: %d\n", i, cSum[i]);
printf("-----------------------------------------------\n");
}
return 0;
}
Upvotes: 4