C Introduction

Control Statement

Functions

Array

Pointers

Structure and Union

No Examples found for this topic - CodeHelpPro

Data Files

No Examples found for this topic - CodeHelpPro

# Addition and Subtraction of Matrices in c

In this example, We will learn a program to perform Addition and Subtraction of Matrices. Before that, You must have knowledge of the following topics.

- For Loop
- Array

Few important notes you must know:

- To add the two matrices, Dimensions must be same

```
1 3 = 5 3
3 5 4 8
```

Above matrices have same dimension.

- To add or subtract the matrices, We will perform addition or subtraction among corresponding elements.

```
1 3 + 5 3 = 1 + 5 3 + 3
3 5 4 8 3 + 4 4 + 8
```

## CODE: Addition and Subtraction of Matrices

Now, We will see the code to perform addition or subtraction of matrices

```
#include<stdio.h>
int main()
{
int n, m, c, d, first[10][10], second[10][10], sum[10][10], diff[10][10];
printf("\nEnter the number of rows and columns of the 1st matrix \n\n");
scanf("%d%d", &m, &n);
printf("\nEnter the %d elements of the 1st matrix \n\n", m*n);
for(c = 0; c < m; c++)
for(d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("\nEnter the %d elements of the 2nd matrix \n\n", m*n);
for(c = 0; c < m; c++)
for(d = 0; d < n; d++)
scanf("%d", &second[c][d]);
//printing the first matrix
printf("\n\nThe 1st matrix is: \n\n");
for(c = 0; c < m; c++){
for(d = 0; d < n; d++){
printf("%d\t", first[c][d]);
}
printf("\n");
}
//print the second matrix
printf("\n\nThe 2nd matrix is: \n\n");
for(c = 0; c < m; c++){
for(d = 0; d < n; d++){
printf("%d\t", second[c][d]);
}
printf("\n");
}
//finding sum of two matrices
for(c = 0; c < m; c++)
for(d = 0; d < n; d++)
sum[c][d] = first[c][d] + second[c][d];
// printing the elements of the sum matrix
printf("\n\nThe sum of the two entered matrices is: \n\n");
for(c = 0; c < m; c++)
{
for(d = 0; d < n; d++)
{
printf("%d\t", sum[c][d]);
}
printf("\n");
}
// finding sum of two matrices
for(c = 0; c < m; c++)
for(d = 0; d < n; d++)
diff[c][d] = first[c][d] - second[c][d];
// printing the elements of the diff matrix
printf("\n\nThe difference(subtraction) of the two entered matrices is: \n\n");
for(c = 0; c < m; c++)
{
for(d = 0; d < n; d++)
{
printf("%d\t", diff[c][d]);
}
printf("\n");
}
return 0;
}
```

The output of above program is

```
Enter the number of rows and columns of the 1st matrix
2
2
Enter the 4 elements of the 1st matrix
1
2
3
4
Enter the 4 elements of the 2nd matrix
1
3
5
7
The 1st matrix is:
1 2
3 4
The 2nd matrix is:
1 3
5 7
The sum of the two entered matrices is:
2 5
8 11
The difference(subtraction) of the two entered matrices is:
0 -1
-2 -3
```

Subscribe

Login

0 Comments

Inline Feedbacks

View all comments