Subtraction of two matrices

Given two matrices, we will write a function that subtracts the given matrices.

Example

INPUT
  A[4][4] = { {1, 4, 7, 9},
        {1, 6, 7, 6},
        {6, 3, 7, 12},
        {4, 4, 4, 4}};

 B[4][4] = { {1, 1, 1, 1},
                    {2, 2, 2, 2},
                    {3, 3, 3, 3},
                    {4, 9, 1, 7}};

We will subtract matrix B from matrix A

OUTPUT
    {{0 3 6 8},
    {-1 4 5 4},
    {3 0 4 9},
    {0 -5 3 -3}}

Time Complexity: O(n^2),

where n is the size of the matrix

Algorithm

1. For each row in the two matrices
    a. Subtract the respective elements in matrix B with the elements in matrix A and store the     result in the same position in some auxilary matrix
    b. move to the next row
2. Print the auxilary matrix

C++ Program

#include <bits/stdc++.h>
using namespace std;
#define N 4
int main()
{
	int A[N][N] = { {1, 4, 7, 9},
					{1, 6, 7, 6},
					{6, 3, 7, 12},
					{4, 4, 4, 4}};

	int B[N][N] = { {1, 1, 1, 1},
                    {2, 2, 2, 2},
                    {3, 3, 3, 3},
                    {4, 9, 1, 7}};
	
	
	for(int i=0; i <N; i++)
	{
		for(int j=0; j<N; j++)
			{
				A[i][j] = A[i][j] - B[i][j];
				cout<<A[i][j]<<" ";
			}
		cout<<endl;
	}
	

	return 0;
}
Try It


Next > < Prev
Scroll to Top