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




Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.