## Tuesday, August 16, 2011

### Sum of two matrices using two dimensional array in C

Matrix is the perfect example of two dimensional array. It has row and column. Row represents one dimension and column represents 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 element and so on. In this example two matrices are added and 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 is given here….

Source Code

//Sum of two matrices using two dimensional array#include<stdio.h>#include<stdlib.h>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 < m; i++){        for(j = 0; j < n; j++)            scanf("%d", &matrix1[i][j]);    }    printf("Enter second matrix: \n");    for(i = 0 ; i < p; i++){        for(j = 0; j < q; j++)            scanf("%d", &matrix2[i][j]);    }    for(i = 0 ; i < m; i++){        for(j = 0; j < n; j++)            sum[i][j] = matrix1[i][j] + matrix2[i][j];    }    printf("The sum of the matrix is :\n");    for(i = 0 ; i < m; i++){        for(j = 0; j < n; j++){            printf("%d", sum[i][j]);            printf("\t");        }        printf("\n");    }    return 0;}

Output