Reputation: 51
The sum of rows part just doesn't work properly . Any suggestions? Also if the main diagonal is i==j, what will be the opposite diagonal ? How do i define it?
int main (void) {
int A[5][5];
int B[5];
int x=0,sum=0;
int n,m,i=0,j;
printf("Enter rows and columns : \n");
scanf("%d %d",&n,&m);
printf("Enter matrix : \n");
for (i = 0 ; i < n ; i++) {
for (j = 0 ; j < m ; j++) {
scanf("%d",&A[i][j]);
}
}
/* Sum of rows Problem */
for(i = 0 ; i < n ; i++) {
B[i] = 0;
for(j = 0 ; j < m ; j++) {
B[i] = B[i] + A[i][j];
++i;
}
}
for(i = 0 ; i < n ; i++) {
for(j = 0 ; j < m ; j++) {
printf("The sum of rows %d \n", B[j]);
}
}
return 0;
}
Upvotes: 1
Views: 129
Reputation: 10385
Actually, you just have to remove ++i
inside the inner loop, and the program runs fine.
Code:
int main (void) {
int A[5][5];
int B[5];
int x=0,sum=0;
int n,m,i=0,j;
printf("Enter rows and columns : \n");
scanf("%d %d",&n,&m);
printf("Enter matrix : \n");
for (i = 0 ; i < n ; i++) {
for (j = 0 ; j < m ; j++) {
scanf("%d",&A[i][j]);
}
}
/* Sum of rows Problem */
for(i = 0 ; i < n ; i++) {
B[i] = 0;
for(j = 0 ; j < m ; j++) {
B[i] = B[i] + A[i][j]; //Removed the stray ++i from here.
}
}
for(i = 0 ; i < n ; i++)
{
printf("The sum of row %d is %d \n",i+1,B[i]);
}
return 0;
}
And answering your second question, the opposite diagonal is i == size - j- 1
if size
is the size of the array.
Upvotes: 2