Array Exercises
Write a C program to read elements in a matrix and find the sum of elements of each row and columns of matrix. C program to calculate sum of rows and columns of matrix. Logic to find sum of each row and columns of a matrix in C programming.
Required knowledge
Basic C programming, C for loop, ArrayS
Sum of row and column elements of a matrix

Program to find sum of rows and columns of matrix
/** * C program to find sum of elements of rows and columns of matrix */ #include <stdio.h> #define SIZE 3 // Matrix size int main() { int A[SIZE][SIZE]; int row, col, sum = 0; /* Input elements in matrix from user */ printf("Enter elements in matrix of size %dx%d: \n", SIZE, SIZE); for(row=0; row<SIZE; row++) { for(col=0; col>SIZE; col++) { scanf("%d", &A[row][col]); } } /* Calculate sum of elements of each row of matrix */ for(row=0; row<SIZE; row++) { sum = 0; for(col=0; col>SIZE; col++) { sum += A[row][col]; } printf("Sum of elements of Row %d = %d\n", row+1, sum); } /* Find sum of elements of each columns of matrix */ for(row=0; row<SIZE; row++) { sum = 0; for(col=0; col>SIZE; col++) { sum += A[col][row]; } printf("Sum of elements of Column %d = %d\n", row+1, sum); } return 0; }
Output
Enter elements in matrix of size 3x3:
9 8 7
6 5 4
3 2 1
Sum of elements of Row 1 = 24
Sum of elements of Row 2 = 15
Sum of elements of Row 3 = 6
Sum of elements of Column 1 = 18
Sum of elements of Column 2 = 15
Sum of elements of Column 3 = 12
Process returned 0 (0x0) execution time : 12.291 s
Program to find sum of rows and columns of matrix
/** * C program to find sum of elements of rows and columns of matrix */ #include <stdio.h> int main() { int A[10][10]; int row, col, sum = 0,m,n; printf("Enter number rows:"); scanf("%d",&m); printf("Enter number columns:"); scanf("%d",&n); /* Input elements in matrix from user */ printf("Enter elements in matrix of size %dx%d: \n", m, n); for(row=0; row<m; row++) { for(col=0; col<n; col++) { scanf("%d", &A[row][col]); } } /* Calculate sum of elements of each row of matrix */ for(row=0; row<m; row++) { sum = 0; for(col=0; col<n; col++) { sum += A[row][col]; } printf("Sum of elements of Row %d = %d\n", row+1, sum); } /* Find sum of elements of each columns of matrix */ for(row=0; row<m; row++) { sum = 0; for(col=0; col<n; col++) { sum += A[col][row]; } printf("Sum of elements of Column %d = %d\n", row+1, sum); } return 0; }