Java Program to Add two Matrices
We can add two arrays in Java using the binary + operator. An array is also known as an array of arrays. We can add, subtract, and multiply matrices. To subtract two matrices, use the - operator. Let's see a simple example to add two matrices with 3 rows and 3 columns.
Java Program to Add two Matrices
Create a Java file with the name of Main.java and paste the given code in your Java file.
public class Main{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,4,3},{4,2,3},{5,4,3}};
int b[][]={{3,1,4},{2,4,5},{1,3,4}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//adding and printing addition of 2 matrices
for(int i=0;i <3;i++){
for(int j=0;j < 3;j++){
c[i][j]=a[i][j]+b[i][j]; //use - for subtraction
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Output:
That’s all in this post, If your code does not work or you’ve faced any problem then comment down your problem.