Java Program to add Two Matrices.

There are following Java Program to add Two Matrices.

  • First we create Scanner class object to pass input value.
  • Create row and columns and store in a matrices.
  • Traverse the each element of the two matrices.
  • Now traverse the each row and column and store in a matrices.
  • Traverse the each element of the two matrices and add them. Store this sum in the new matrices c[i][j] at the corresponding index.
  • Now iterate this sum of two matrices with row and column.
  • Print the matrices value.
				
					import java.util.Scanner;

public class MatrixAddition {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter number of rows:- ");
		int rows = sc.nextInt();
		System.out.print("Enter number of columns:- ");
		int columns = sc.nextInt();
		
		int[][] a = new int[rows][columns];
		int[][] b = new int[rows][columns];
		
		System.out.println("Enter the first matrix value:- ");
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < columns; j++) {
				a[i][j] = sc.nextInt();
			}
		}
		System.out.println("Enter the second matrix value :- ");
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < columns; j++) {
				b[i][j] = sc.nextInt();
			}
		}
		int[][] c = new int[rows][columns];
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < columns; j++) {
				c[i][j] = a[i][j] + b[i][j];
			}
		}
		System.out.println("The sum of the two matrices is:- ");
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < columns; j++) {
				System.out.print(c[i][j] + " ");
			}
			System.out.println();
		}
	}
}

				
			

Output :-
Enter number of rows:- 2
Enter number of columns:- 2
Enter the first matrix value:-
3
4
5
6
Enter the second matrix value :-
7
8
9
2
The sum of the two matrices is:-
10 12
14 8