×

Java Programs

Java Practice

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

Core Java Example Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.