Java program to add two Matrices

Write a Java program to add two Matrices with an example. Or write a Java program to add two multi dimensional arrays.

In this Java add two Matrices example, we declared two integer matrixes with random values. Next, we used the For Loop to iterate those matrix values and add them. Later, we used another for loop to print the final output.

public class addTwoMatrix {

	public static void main(String[] args) {
		int[][] x = {{10, 20, 30}, {40, 50, 60}, {70, 80, 90}};
		int[][] y = {{ 5, 15, 25}, {35, 45, 55}, {65, 75, 85}};
		
		int[][] sum = new int[3][3];
		int i, j;
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				sum[i][j] = x[i][j] + y[i][j];
			}
		}
		System.out.println("------ The addition of two Matrices ------");
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				System.out.format("%d \t", sum[i][j]);
			}
			System.out.println("");
		}
	}
}
Java program to add two Matrices 1

Java program to add two Matrices example 2

This Java matrix addition example is the same as above. However, this Java code allows the user to enter the total number of rows and columns of the matrix, and then, it asks for the items. Please refer C Program to Sum Mats article to understand the iteration-wise program execution.

import java.util.Scanner;

public class Example {
	private static Scanner sc;
	public static void main(String[] args) {
		int i, j, rows, columns;
		
		sc= new Scanner(System.in);
		
		System.out.println("\n Please Enter Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] arr1 = new int[rows][columns];
		int[][] arr2 = new int[rows][columns];
		
		System.out.println("\n Please Enter the First Mat Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr1[i][j] = sc.nextInt();
			}		
		}
		System.out.println("\n Please Enter the Second Mat Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr2[i][j] = sc.nextInt();
			}		
		}
		System.out.println("\n-----The Sum of two Matrixes----- ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				System.out.format("%d \t", (arr1[i][j] + arr2[i][j]));
			}
			System.out.println("");
		}
	}
}
 Please Enter Rows and Columns :  
3 3

 Please Enter the First Mat Items :  
10 15 20
30 35 40
45 50 60

 Please Enter the Second Mat Items :  
7 17 27
37 47 57
67 77 87

-----The Sum of two Matrixes----- 
17 	32 	47 	
67 	82 	97 	
112 	127 	147