Addition and Subtraction of Two Matrices in C using Arrays
C program to make addition and Subtraction of two Matrices using the Arrays.
In this article, you will learn how to make addition and Subtraction of two Matrices using the Arrays.
Example
Enter the number of rows & columns of Matrix:
3 3
Enter the 9 elements of the first array:
67 56 3 9 34 1 1 7 9
Enter the 9 elements of the second array:
7 6 2 90 56 34 90 12 5
The sum of first & second matrices:
74 62 5
99 90 35
91 19 14
The subtraction of first & second matrices:
60 50 1
-81 -22 -33
-89 -5 4
You should have knowledge of the following topics in c programming to understand this program:
- C
main()
function - C
printf()
function - For loop in C
- Arrays in C
Source Code
// Online C Compiler
#include <stdio.h>
int main()
{
int x1, x2, row, col;
printf("Enter the number of rows & columns of Matrix:\n");
scanf("%d%d", &x1, &x2);
int first_matrix[x1][x2], second_matrix[x1][x2], sum_matrix[x1][x2], diff_matrix[x1][x2];
printf("\nEnter the %d elements of the first array:\n", x1 * x2);
for (row = 0; row < x1; row++)
{
for (col = 0; col < x2; col++)
{
scanf("%d", &first_matrix[row][col]);
}
}
printf("\n\nEnter the %d elements of the second array:\n", x1 * x2);
for (row = 0; row < x1; row++)
{
for (col = 0; col < x2; col++)
{
scanf("%d", &second_matrix[row][col]);
}
}
/* Make the sum of two matrices and store in another matrix named - sum_matrix */
printf("\n\nThe sum of first & second matrices:\n");
for (row = 0; row < x1; row++)
{
for (col = 0; col < x2; col++)
{
sum_matrix[row][col] = first_matrix[row][col] + second_matrix[row][col];
printf("%d\t", sum_matrix[row][col]);
}
printf("\n");
}
/* Make the subtraction of two matrices and store in another matrix named - diff_matrix */
printf("\n\nThe subtraction of first & second matrices:\n");
for (row = 0; row < x1; row++)
{
for (col = 0; col < x2; col++)
{
diff_matrix[row][col] = first_matrix[row][col] - second_matrix[row][col];
printf("%d\t", diff_matrix[row][col]);
}
printf("\n");
}
return 0;
}
Output
3 3
Enter the 9 elements of the first array:
67 56 3 9 34 1 1 7 9
Enter the 9 elements of the second array:
7 6 2 90 56 34 90 12 5
The sum of first & second matrices:
74 62 5
99 90 35
91 19 14
The subtraction of first & second matrices:
60 50 1
-81 -22 -33
-89 -5 4