# Subtract matrix2 from matrix1 and print the resultant matrix program

21 April 2023

21 April 2023

Subtract matrix2 from matrix1 and print the resultant matrix

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

## Description

Given 2 matrices of same dimension. Subtract matrix2 from matrix1 and print the resultant matrix.

Sample input :

3 3

1 2 3

4 5 6

7 8 9

1 0 0

0 1 0

0 0 1

Sample output :

2 3 4

4 6 6

7 8 10

## C Program

#include <stdio.h>

int main()

{

int r1,c1,r2,c2;

scanf("%d%d",&r1,&c1);

int arr1[r1][c1];

for(int i = 0 ; i<r1 ; i++)

{

for(int j = 0 ; j<c1 ; j++)

{

scanf("%d",&arr1[i][j]) ;

}

}

scanf("%d%d",&r2,&c2);

int arr2[r2][c2];

for(int i = 0 ; i<r2 ; i++)

{

for(int j = 0 ; j<c2 ; j++)

{

scanf("%d",&arr2[i][j]) ;

}

}

for(int i = 0 ; i<r1 ; i++)

{

for(int j = 0 ; j<c1 ; j++)

{

arr1[i][j] = arr1[i][j] - arr2[i][j];

}

}

for(int i = 0 ; i<r1 ; i++)

{

for(int j = 0 ; j<c1 ; j++)

{

printf("%d ",arr1[i][j]);

}

printf("\n");

}

return 0;

}

## C++ Program

#include <bits/stdc++.h>

using namespace std;

int main()

{

int r1,c1,r2,c2;

cin>>r1>>c1;

int arr1[r1][c1];

for(int i = 0 ; i<r1 ; i++)

{

for(int j = 0 ; j<c1 ; j++)

{

cin>>arr1[i][j];

}

}

cin>>r2>>c2;

int arr2[r2][c2];

for(int i = 0 ; i<r2 ; i++)

{

for(int j = 0 ; j<c2 ; j++)

{

cin>>arr2[i][j];

}

}

for(int i = 0 ; i<r1 ; i++)

{

for(int j = 0 ; j<c1 ; j++)

{

arr1[i][j] = arr1[i][j] - arr2[i][j];

}

}

for(int i = 0 ; i<r1 ; i++)

{

for(int j = 0 ; j<c1 ; j++)

{

cout<<arr1[i][j]<<" ";

}

cout<<"\n";

}

return 0;

}

## JAVA Program

import java.util.*;

import java.lang.*;

import java.io.*;

class Main

{

public static void Subtraction(int arr1[][],int arr2[][],int r1,int c1)

{

for(int i = 0 ; i<r1 ; i++)

{

for(int j = 0 ; j<c1 ; j++)

{

arr1[i][j] = arr1[i][j] - arr2[i][j];

}

}

for(int i = 0 ; i<r1 ; i++)

{

for(int j = 0 ; j<c1 ; j++)

{

System.out.print(arr1[i][j] + " ");

}

System.out.println();

}

}

public static void main (String[] args) throws java.lang.Exception

{

Scanner sc=new Scanner(System.in);

int r1,r2,c1,c2;

r1 = sc.nextInt();

c1 = sc.nextInt();

int arr1[][] = new int[r1][c1];

for(int i = 0 ; i<r1 ; i++)

{

for(int j = 0 ; j<c1 ; j++)

{

arr1[i][j] = sc.nextInt();

}

}

r2 = sc.nextInt();

c2 = sc.nextInt();

int arr2[][] = new int[r2][c2];

for(int i = 0 ; i<r1 ; i++)

{

for(int j = 0 ; j<c1 ; j++)

{

arr2[i][j] = sc.nextInt();

}

}

Subtraction(arr1,arr2,r1,c1);

}

}

## PYTHON Program

a1=[[1, 2, 3],

[4, 5, 6],

[7, 8, 9]]

a2=[[1, 1, 1],

[2, 2, 2],

[3, 3, 3]]

for i in range(len(a1)):

for j in range(len(a1[0])):

a1[i][j] = a1[i][j] - a2[i][j]

print(a1)

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023