Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to Substract two matrix

C++ Code Example — Array Programs

ADVERTISEMENT

WAP to Substract two matrix

Objective

Write a C++ program to subtract two 2D Matrices.

Algorithm / Approach

  1. Declare three 3x3 matrices.
  2. Read data for the first two matrices using nested loops.
  3. Calculate the difference by subtracting matching coordinates: m3[i][j] = m1[i][j] - m2[i][j].
  4. Print the resulting difference matrix.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int m1[3][3],m2[3][3],m3[3][3];
 cout<<"Enter Elements of Mat1:\n";
 for(int i = 0; i< 3; i++) {
  for(int j = 0; j< 3; j++) {
   cin>>m1[i][j];
  }
 }
 cout<<"Enter Elements of Mat2:\n";
 for(int i = 0; i< 3; i++) {
  for(int j = 0; j< 3; j++) {
   cin>>m2[i][j];
  }
 }
 cout<<"Difference of matrix:\n";
 for(int i = 0; i< 3; i++) {
  for(int j = 0; j< 3; j++) {
   m3[i][j] = m1[i][j]-m2[i][j];
   cout<< m3[i][j]<<"  ";
  }
  cout<< endl;
 }
 return 0;
}

Expected Output

Enter Elements of Mat1:
3 4 3
2 3 4
6 8 2
Enter Elements of Mat2:
1 2 2
1 2 1
3 1 2
Difference of matrix:
2 2 1
1 1 3
3 7 0

Explanation of the Program

  • Matrix subtraction follows the exact same logic as matrix addition.
  • Remember that for matrix addition and subtraction to be mathematically valid, both matrices must have the exact same dimensions (e.g., both must be exactly 3x3).

Complexity

Time Complexity O(r * c)
Space Complexity O(r * c)
ADVERTISEMENT