Addition of matrices in Java

Java program to add two matrices

Here, we are supposed to enter two 2D arrays or rather Matrices. The 2D-arrays will be dynamic arrays of identical size (R*C). After entering into the arrays, we’ll have to calculate and print the Summation Matrix (Result After Addition of Second Matrix and First Matrix) and along with displaying both the original matrices.

The basic idea to be kept in mind is:
Two matrices can be added only if they are of identical dimensions.

The standard algorithm will be:
1. Enter the size of the two 2D-arrays.
2. Create the two matrices of the input sizes.
3. Using a loop construct, enter integer inputs in both the matrices.
4. Declare another matrix that will store the summation of the original matrices. The size will be (R*C).
5. Using loop construct, add both the original matrices and store the result in summation matrix.
6. After the loop terminates, print the result accordingly.

Java Code:

/* Program to enter two 2D arrays and print the Summation Matrix */

import java.util.*; class AddMatrix { public static void main() { Scanner inp=new Scanner(System.in); int r,c,i,j;

System.out.print("\n Enter Dimensions of Matrix (Row * Column) : "); r=inp.nextInt();
c=inp.nextInt();

int a[][]=new int[r][c]; //Creating Matrices of size R*C int b[][]=new int[r][c];

System.out.println("Enter into First Matrix: "); for(i=0;i<r;i++) { for(j=0;j<c;j++) { System.out.print("\n Enter: "); a[i][j]=inp.nextInt(); } }

System.out.println("Enter into Second Matrix: "); for(i=0;i<r;i++) { for(j=0;j<c;j++) { System.out.print("\n Enter: "); b[i][j]=inp.nextInt(); } }

int sum[][]=new int[r][c]; for(i=0;i<r;i++) { for(j=0;j<c;j++) { sum[i][j]=a[i][j]+b[i][j]; //Calculating summation of corresponding elements in both matrix } }

System.out.println(); System.out.println("First Matrix: "); // Displaying Result display(a,r,c); System.out.println("Second Matrix: "); display(b,r,c); //Function to display matrix when invoked. System.out.println("Resultant Matrix after Addition: "); display(sum,r,c); }

public static void display(int arr[][],int row,int col) { int i,j; for(i=0;i<row;i++) { for(j=0;j<col;j++) { System.out.print(arr[i][j]+" "); } System.out.println(); } }

}

Output:

Enter Dimensions of Matrix (Row * Column) : 
2
3

Enter into First Matrix: Enter: 1 Enter: 2 Enter: 3 Enter: 4 Enter: 5 Enter: 6

Enter into Second Matrix: Enter: 7 Enter: 8 Enter: 9 Enter: 6 Enter: 5 Enter: 4

First Matrix: 1 2 3 4 5 6

Second Matrix: 7 8 9 6 5 4

Resultant Matrix after Addition: 8 10 12 10 10 10

Addition of matrices in Java