**Java program to add two matrices** has been shown here. Two matrices $[A]_{m \times n}$ and $[B]_{p \times q}$ are considered for addition if the number of rows and columns are same in both of the matrices i.e. $m = p$ and $n = q$.

Algorithm, pseudocode and time complexity of the program have also been shown.

## 1. Java Program for matrix addition

/*************************************** alphabetacoder.com Java program for Matrix Addition ***************************************/ import java.util.Scanner; public class Addition{ public static void main(String args[]){ //System.in is a standard input stream // sc is the object Scanner sc= new Scanner(System.in); int m,n,p,q,i,j; //take input of the order of first matrix System.out.print("Enter the number of row and column of first matrix="); m=sc.nextInt(); n=sc.nextInt(); //declare first matrix int A[][]=new int[m][n]; //take input of the first matrix System.out.print("Enter the first matrix of order "+m+" x "+n+"=\n"); for(i=0;i<m;i++) for(j=0;j<n;j++) A[i][j]=sc.nextInt(); //take input of the order of second matrix System.out.print("Enter the number of row and column of second matrix="); p=sc.nextInt(); q=sc.nextInt(); //declare second matrix int B[][]=new int[p][q]; //take input of the second matrix System.out.print("Enter the second matrix of order "+p+" x "+q+"=\n"); for(i=0;i<p;i++) for(j=0;j<q;j++) B[i][j]=sc.nextInt(); // check if order of matrices are same // if not then addition of two matrices is not possible if(m!=p||n!=q) System.out.print("\nMatrices are of different order, hence addition is not possible"); else{ //add each corresponding elements // and print the resultant matrix System.out.print("The resultant matrix after addition:\n"); for(i=0;i<m;i++){ for(j=0;j<n;j++) System.out.print(" "+(A[i][j]+B[i][j])); System.out.print("\n"); } } } }

Output

**Case 1:**

Enter the number of row and column of first matrix=3 3

Enter the first matrix of order 3 x 3=

3 5 7

4 5 9

0 1 1

Enter the number of row and column of second matrix=2 3

Enter the second matrix of order 2 x 3=

9 4 5

3 7 8

1 2 3

The resultant matrix after addition:=

12 9 12

7 12 17

1 3 4

**Case 2:**

Enter the number of row and column of first matrix=3 3

Enter the first matrix of order 3 x 3=

3 5 7

4 5 9

0 1 1

Enter the number of row and column of second matrix=2 3

Enter the second matrix of order 2 x 3=

9 4 5

3 7 8

Matrices are of different order,hence addition is not possible

## No comments:

## Post a Comment

If you have any doubts or suggestions, please leave a note.