Dark mode logo
Last Updated:
Sum of the matrix in C

Sum of two matrix in C

Algorithm

Input: Input rows and column of the arrays, elements of the arrays 
output: Displays the sum of element of the array

  1. Start
  2. Input the number of row and store it in m for both matrices
  3. Input the number of column and store it in n for both matrices
  4. Check if m1 = m2 and n1 = n2
    4.1 Enter the elements of the array a [ m1 ] [ n1 ] and b [ n2 ] [ m2 ]
    4.2 i = 0
    while ( i < n )
     4.2.1 j = 0
     4.2.2 while ( j < m )
      4.2.2.1 c [ i ] [ j ] = a[ i ] [ j ] + b [ i ] [ j ]
      4.2.2.2 j++
    4.2.3 i++
    4.3 Print the array c [ i ] [ j ]
  5. Else print "The addition of matrices is not possible, Since the rows or columns does not match" 
  6. Stop

C Program

# include <stdio.h>
int main()

{
//Enter the rows and columns and elements of the first and second array
int n1,m1,n2,m2;
printf("Enter the number of rows of the first matrix: ");
scanf("%d", &n1);
printf("Enter the number of column of the first matrix: ");
scanf("%d", &m1);
printf("Enter the number of rows of the second matrix: ");
scanf("%d", &n2);
printf("Enter the number of column of the second matrix: ");
scanf("%d", &m2);

if ( m1 == m2 && n1 == n2) {
   int a[m1][n1], b[m2] [n2], c[m1] [n1];

printf("Enter the elements of the first array: \n");
for (int i =0; i < m1; i++){
   for (int j = 0; j < n1; j++)
          scanf("%d", &a[i][j]);
}

printf("Enter the elements of the second array: \n");
for (int i =0; i < m2; i++){
    for (int j = 0; j < n2; j++)
          scanf("%d", &b[i][j]);
}

//Calculates the sum of the arrays and stores it in an array named c
for (int i =0; i < m1; i++){
    for (int j = 0; j < n1; j++){
          c[i][j] = a[i][j] + b[i][j];
    }
}
//prints the result
printf("The sum of the array is\n");
for (int i =0; i < m1; i++){
    for (int j = 0; j < n1; j++){
          printf("%d\t", c[i][j]);
    }
printf("\n");
} }
else {
printf("The addition of matrices is not possible, Since the rows or columns does not match");
}

return 0;
}


Note: This Program was created using visual studio code. The Program file can be downloaded by clicking here

Comments