Java Program to add two matrices

We can add two matrices in java using add(+) operator.

  • There two matrices a and b of same size.
  • Create rows and columns from sc.nextInt() method.
  • Declare first matrix from two for loop,one for row and another for columns.storing data in matrix b.
  • Declare second matrix from two for loop,one for row and another for columns.storing data in matrix c.
  • Create a new Matrix to store the sum of the two matrices
  • Traverse each element of the two matrices and add them. Store this sum in the new matrix at the corresponding index.
  • Print the final new matrix
				
					import java.util.Scanner;

public class AddMatrix {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int x, y;
		int a[][] = new int[4][4];
		int b[][] = new int[4][4];
		int c[][] = new int[4][4];

		System.out.println("enter the number of rows :");
		x = sc.nextInt();
		
		System.out.println("enter the number of columns :");
		y = sc.nextInt();
		
		System.out.println("enter the first matrix :");
		for (int i = 0; i < x; i++) {
			for (int j = 0; j < y; j++) {
				b[i][j] = sc.nextInt();
			}
		}
		System.out.println("enter the second matrix :");
		for (int i = 0; i < x; i++) {
			for (int j = 0; j < y; j++) {
				c[i][j] = sc.nextInt();
			}
		}

		System.out.println("Sum of two matrices is :");
		for (int i = 0; i < y; i++) {
			for (int j = 0; j < y; j++) {
				a[i][j] = b[i][j] + c[i][j];
				System.out.print(a[i][j] + " ");
			}
			System.out.println();
		}

	}

}
				
			

Output :-

enter the number of rows :
2
enter the number of columns :
2
enter the first matrix :
1
2
3
4
enter the second matrix :
5
6
7
8
Sum of two matrices is :
6   8
10 12