Matrix subtraction is a fundamental operation in linear algebra and computer science. Frequently utilized in various applications such as image processing, data manipulation, and numerical simulations. In this article, we are going to perform matrix subtraction in C programming language.
Table of Contents
Matrix Subtraction
Matrix subtractions invlove subtracting corresponding elements of two matrices to create a new matrix. If we have two matrices A and B then the resulting matrix C is computed as follow-
C[i][j] = A[i][j] – B[i][j]
C Program for Matrix Subtraction
#include <stdio.h>
// Function to add two matrices
void subMatrices(int row, int column, int A[row][column], int B[row][column], int C[row][column])
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
C[i][j] = A[i][j] - B[i][j];
}
}
}
void main()
{
int row, column;
printf("Enter the number of rows ");
scanf("%d", &row);
printf("Enter the number of column ");
scanf("%d", &column);
int matrixA[row][column], matrixB[row][column], subtraction[row][column];
printf("Enter the element of first Matrices\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
printf("Enter the element at position {%d,%d}", i, j);
scanf("%d", &matrixA[i][j]);
}
}
printf("Enter the element of second Matrices\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
printf("Enter the element at position {%d,%d}", i, j);
scanf("%d", &matrixB[i][j]);
}
}
subMatrices(row, column, matrixA, matrixB, subtraction);
printf("resultant matrix after subtraction\n ");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
printf("%d\t", subtraction[i][j]);
}
printf("\n");
}
}
Output
How Above Code Works?
- The main function is the entry point of an above C program.
- We declare two variables row and column to store the dimensions of the matrices.
- Program asks users to enter the velue of row and column.
- Three matrices are declared-matrixA, matrixB, and subtraction, Each with dimensions specified by the user.
- Users then entered the element of both matrices matrix and matrix by using a nested loop.
- Function subMatrices is called with the dimension of the matrices and the matrices themselves.
- Inside the function, a nested loop iterates through each element of matrices performs the subtraction of corresponding elements, and stores the result in the subtraction matrix.
- At the end, the program prints the resultant matrix after the subtraction.
Happy Coding
3 thoughts on “Matrix Subtraction in C”