Sum of two matrices using two dimensional array in C
Matrix is the perfect example of a two-dimensional array. It has row and column. A row represents one dimension and column represents the second dimension. For example matrix[4][5], it has 4 rows, each row consisting 5 elements i.e matrix[0] has 5 elements, matrix[1] has 5 elements and so on. In this example, two matrices are added and the result is displayed. Addition is done with corresponding elements of individual matrix i.e. matrix1[0][0] is added with matrix2[0][0].
The complete source code and output are given here….(The code is also available on GitHub). Here are related articles about matrix operation.
Source Code
//Sum of two matrices using two dimensional array #include#include int main(){ int matrix1[10][10], matrix2[10][10], sum[10][10], i, j, m,n,p,q; printf("Enter the order of first matrix: "); scanf("%d%d",&m,&n); printf("Enter the order of second matrix: "); scanf("%d%d",&p,&q); if(m!=p && n!=q){ printf("Order of matrix did not matched!!"); exit(0); } printf("Enter first matrix: \n"); for(i = 0 ; i
OutputThe above program allocates the fixed memory to store the matrix. The program below shows the dynamic memory allocation to allocates the memory to store the matrix.
#include#include int main(int argc, char *argv[]) { int rows, columns, i, j; int **matrix1, **matrix2; if (argc != 3) { printf("Usage: outputfile rows columns\n"); exit(1); } rows = atoi(argv[1]); columns = atoi(argv[2]); // allocate memory for matrices matrix1 = (int**) malloc (sizeof(int*) * columns); for (i = 0; i