Home >Backend Development >C++ >C program for matrix subtraction
Given two matrices MAT1[row][column] and MAT2[row][column], we have to find the difference between the two matrices and print the result obtained after subtracting the two matrices. The two matrices are subtracted as MAT1[n][m] – MAT2[n][m].
For subtraction, the number of rows and columns of both matrices should be the same.
Input: MAT1[N][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}} MAT2[N][N] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1}} Output: -8 -6 -4 -2 0 2 4 6 8
The method used below is as follows -
We will iterate the matrix for each row and column and start from mat1[][] subtracts the value of mat2[][] from and stores the result in result[][], where the rows and columns of all matrices remain the same.
In fucntion void subtract(int MAT1[][N], int MAT2[][N], int RESULT[][N]) Step 1-> Declare 2 integers i, j Step 2-> Loop For i = 0 and i < N and i++ Loop For j = 0 and j < N and j++ Set RESULT[i][j] as MAT1[i][j] - MAT2[i][j] In function int main() Step 1-> Declare a matrix MAT1[N][N] and MAT2[N][N] Step 2-> Call function subtract(MAT1, MAT2, RESULT); Step 3-> Print the result
Live Demonstration
#include <stdio.h> #define N 3 // This function subtracts MAT2[][] from MAT1[][], and stores // the result in RESULT[][] void subtract(int MAT1[][N], int MAT2[][N], int RESULT[][N]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) RESULT[i][j] = MAT1[i][j] - MAT2[i][j]; } int main() { int MAT1[N][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int MAT2[N][N] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; int RESULT[N][N]; // To store result int i, j; subtract(MAT1, MAT2, RESULT); printf("Resultant matrix is </p><p>"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", RESULT[i][j]); printf("</p><p>"); } return 0; }
If you run the above code, it will generate the following output-
Resultant matrix is -8 -6 -4 -2 0 2 4 6 8
The above is the detailed content of C program for matrix subtraction. For more information, please follow other related articles on the PHP Chinese website!