Java Program to Add or Sub Two Matrices

If we want to add two matrices we can serve this purpose using this program.Matrix addition is a complex task and Java Program to add two matrices is most frequently asked interview and coding exam question,therefore its necessary to understand logic to implement this program.

In this topic we will take two examples. In Example-1 we will be take Static Inputs and Example-2 we will take User defined Inputs.

Matrix-1=  | 1 2 3 |     Matrix-2= | 1 2 3 |
           | 4 5 6 |               | 4 5 6 |
           | 7 8 9 |               | 7 8 9 |
 
Matrix-3 =   | 1+1 2+2 3+3 |       | 2  4   6  |
Matrix 1+2   | 4+4 5+5 6+6 |    =  | 8  10  12 |
             | 7+7 8+8 9+9 |       | 14 16  18 |

From the above program it is very clear what we have to do in this program.

Example-1 Using Static Inputs

Algorithm/Program Explanation

  1. Start
  2. Initialize 3- 3X3 Matrix
    • int matrix1[][]={{1,2,3},{4,5,6},{7,8,9}};
    • int matrix2[][]={{1,2,3},{4,5,6},{7,8,9}};
    • int matrix3[][]=new int[3][3];
  3. Define two loop
    • for(int i=0;i<3;i++)
    • for(int j=0;j<3;j++)
      • condition-matrix3[i][j]=matrix1[i][j]+ matrix2[i][j]; //for subtraction change + sign with – sign
    • Print matrix3
  4. End

Note: For Subtraction just change + with – Sign

/*
Java Program to Add/sub Two Matrices */
import java.util.*;
public class MatrixAddition{
 public static void main(String args[]){
  int matrix1[][]={{1,2,3},{4,5,6},{7,8,9}};
  int matrix2[][]={{1,2,3},{4,5,6},{7,8,9}};
  int matrix3[][]=new int[3][3];
  System.out.println( " Matrix After Addition: ");
  for(int i=0;i<3;i++){
   for(int j=0;j<3;j++){
    matrix3[i][j]=matrix1[i][j]+ matrix2[i][j];//for subtraction change + sign with + sign
    System.out.print(matrix3[i][j]+ " " );
   }
   System.out.println();
  }
 }
}
Output:
Matrix After Addition: 
2 4 6 
8 10 12 
14 16 18

Example 2- Taking User Defined Inputs

/*
Java Program to Add Two Matrices */
import java.util.*;
public class MatrixAddition{
 public static void main(String args[]){
  int matrix1[][]=new int [3][3];
  int matrix2[][]=new int[3][3];
  int matrix3[][]=new int[3][3];
  Scanner sc=new Scanner(System.in);

  System.out.println("Enter Input for Matrix-1 3X3");
  for(int i=0;i<3;i++){
   for(int j=0;j<3;j++){
    matrix1[i][j]=sc.nextInt();
   }

  }
  System.out.println("Enter Input for Matrix-2 3X3");
  for(int i=0;i<3;i++){
   for(int j=0;j<3;j++){
    matrix2[i][j]=sc.nextInt();
   }

  }
  System.out.println( " Matrix After Addition: ");
  for(int i=0;i<3;i++){
   for(int j=0;j<3;j++){
    matrix3[i][j]=matrix1[i][j]+ matrix2[i][j];// for subtraction just change + sign with - sign
    System.out.print(matrix3[i][j]+ " " );
   }
   System.out.println();
  }
 }
}
Output:
Enter Input for Matrix-1 3X3
 1 2 3
 4 5 6
 7 8 9
Enter Input for Matrix-2 3X3
1 2 3 
4 5 6
7 8 9
 Matrix After Addition: 
2 4 6 
8 10 12 
14 16 18 

Related Topics:

Leave a Comment