Home » Java solved programs » Core java programs

Java program to find addition and subtraction of two matrices



Here, we have two java programs that are using to find addition and subtraction of two matrices.
Submitted by Preeti Jain, on March 11, 2018

Given two matrices and we have to find their addition and subtraction.

1) Java program to find addition of two matrices

class AddMatrixClass{  
	public static void main(String args[]){  
		/*initialize two matrices*/   
		int m1[][]={{1,1,1},{2,2,2},{3,3,3}};    
		int m2[][]={{4,4,4},{5,5,5},{6,6,6}};    

		/*creating third matrix to store 
		the sum of m1 and m2 matrices */   
		int m3[][]=new int[3][3];  

		/*add and print addition of m1 and m2 matrices */   
		for(int i=0;i<3;i++){    
			for(int j=0;j<3;j++){    
				m3[i][j]=m1[i][j]+m2[i][j];      
				System.out.print(m3[i][j]+" ");    
			}    
			System.out.println();  
		}
	}
}

Output

D:\Java Articles>java AddMatrixClass
5 5 5
7 7 7
9 9 9

2) Java program to find subtraction of two matrices

class SubstractMatrixClass{  
	public static void main(String args[]){  
		/*initialize two matrices*/   
		int m1[][]={{1,1,1},{2,2,2},{3,3,3}};    
		int m2[][]={{4,4,4},{5,5,5},{6,6,6}};    

		/*creating third matrix to store 
		the substraction of m1 and m2 matrices */   
		int m3[][]=new int[3][3];  

		/* substract and print substraction of m1 and m2 matrices */   
		for(int i=0;i<3;i++){    
			for(int j=0;j<3;j++){    
				m3[i][j]=m1[i][j]-m2[i][j];      
				System.out.print(m3[i][j]+" ");    
			}    
			System.out.println();  
		}    
	}
}

Output

D:\Java Articles>java SubstractMatrixClass
-3 -3 -3
-3 -3 -3
-3 -3 -3





Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.