## C program to add two matrix

Write a c program to print the sum of two matrices. In this blog, we are going to create a program to find the sum of two matrices.

## What are Matrices

Matrices are the rectangular or square arrays that are used in mathematics for certain operation

for example:

1    2     3

4      5     6

7     8      9

## Algorithm to add two matrix

• Include all the library and declare the main method with void as its return type
• Initialize all the variables as per requirement
• Take inputs from the user about the columns, rows, and then their elements
• Operator with logic and then printing the appropriate message

## C program to add two matrix

```#include<stdio.h>
void main(){
int a[10][10],b[10][10],sum[10][10],i,j,c,r;
printf("enter no of rows:");
scanf("%d",&r);
printf("enter no of columns:");
scanf("%d",&c);
printf("1st matrix:\n");
for(i=0;i<r;i++){
for(j=0;j<c;j++){
printf("enter elements:");
scanf("%d",&a[i][j]);
}
}
printf("2nd matrix:\n");
for(i=0;i<r;++i){
for(j=0;j<c;++j){
printf("enter elements:");
scanf("%d",&b[i][j]);
}
}

for(i=0;i<r;++i){
for(j=0;j<c;++j){
sum[i][j]=a[i][j] + b[i][j];
}
}
printf("\nsum of matrix:\n");
for(i=0;i<r;++i){
for(j=0;j<c;++j){
printf("%d ",sum[i][j]);
if (j == c - 1) {
printf("\n");
}
}
}
}```

## Explanation of the code

Step 1 includes the library

Step declare the main method with void as the return type

Step 3 declare 2D arrays a,b, and sum and some required variables for taking input and running loops

Step 4  command to take input of row

Step 5 using scanf to take input of row

Step 6 command to take input of columns

Step 7 using scanf to take input of columns

Step 8 command about from here elements of the first matrix are going to insert

Step 9 using for loop to take input of elements

Step 10 as we are working with 2D arrays we need one more loop to place the taken value at its right position

Step 11 command to give inputs

Step 12 using scanf to place the values at their position

Step 13, Step 14 closing both the loops

from Step 15 to Step 22 performing the same operation again to get the second matrix

Step 23 and Step 24 accessing the elmemts of each matrix one by one, to sum up them

Step 25 here we sum up both matrices and assign the value in the sum matrix

Step 26 and Step 27 close the loops

Step 28 printing message for the user

Step 29 and Step 30 as we have to print the sum we need them to access again

Step 31 printing the sum of the matrix

Step 32 to print the output in matrix form applying the condition

Step 33 breaking the line using the “\n” for perfect output

Closing the loops

## Output

In this blog, we have learned how to create a program to find the sum of two matrices.