Advertisements
Hi Friend,
Try the following code:
import java.util.*; class MatrixAddition{ public static void main(String[] args) throws Exception { Scanner input=new Scanner(System.in); int[][] A = new int[2][2]; int[][] B = new int[2][2]; int[][] C = new int[2][2]; System.out.println("Enter elements for matrix A : "); for (int i=0 ; i < A.length ; i++) for (int j=0 ; j < A[i].length ; j++){ A[i][j] = input.nextInt(); } System.out.println("Enter elements for matrix B : "); for (int i=0 ; i < B.length ; i++) for (int j=0 ; j < B[i].length ; j++){ B[i][j] = input.nextInt(); } System.out.println("Matrix A: "); for (int i=0 ; i < A.length ; i++) { System.out.println(); for (int j=0 ; j < A[i].length ; j++){ System.out.print(A[i][j]+" "); } } System.out.println(); System.out.println("Matrix B: "); for (int i=0 ; i < B.length ; i++) { System.out.println(); for (int j=0 ; j < B[i].length ; j++){ System.out.print(B[i][j]+" "); } } System.out.println(); System.out.println("Sum of 2 matrices,Matrix C: "); for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ C[i][j]=A[i][j]+B[i][j]; System.out.print(C[i][j]+" "); } System.out.println(); } } }
Thanks