Matrix addition and subtraction in java

Let’s learn matrix addition and subtraction in java.

Matrix addition and subtraction in java

A matrix java represents a two-dimensional array. Here user enters the number of rows and columns.

Also read – for each loop in java

Nested for loop is used to read the input. Outer for loop “m” ranges from 0 to number of rows of the matrix.

Meanwhile inner for loop “n” ranges from 0 to number of columns of matrix. The input is read using “nextInt()” method of class Scanner and stored at x[m][n] and y[m][n] position.

Also read – access modifiers in java

After reading elements, two for loops is used to add two matrices with loop index. Then finally result is stored at z[m][n] position.

Here’s matrix addition in java and sum of matrix elements in java.

// matrix addition java
import java.util.Scanner;

public class MatrixAdditionDemo
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter number of rows : ");
      int row = sc.nextInt();
      System.out.println("Please enter number of columns : ");
      int col = sc.nextInt();

      int x[][] = new int[row][col];
      int y[][] = new int[row][col];

      System.out.println("Please enter first matrix - ");
      for(int m = 0; m < row; m++)
      {
         for(int n = 0; n < col; n++)
         {
            x[m][n] = sc.nextInt();
         }
      }

      System.out.println("Please enter second matrix - ");
      for(int m = 0; m < row; m++)
      {
         for(int n = 0; n < col; n++)
         {
            y[m][n] = sc.nextInt();
         }
      }

      // matrix java
      int z[][] = new int[row][col];
      for(int m = 0; m < row; m++)
      {
         for(int n = 0; n < col; n++)
         {
            // matrix addition in java
            z[m][n] = x[m][n] + y[m][n];
         }
      }

      System.out.println("The addition of two matrices is - ");     
      for(int m = 0; m < row; m++)
      {
         for(int n = 0; n < col; n++)
         {
            System.out.print(z[m][n] + " ");
         }
         System.out.println();
      }
      sc.close();
   }
}



Output:

matrix addition and subtraction in java

Similar to matrix addition in java we can write java program to subtract two matrices,

// subtraction java
import java.util.Scanner;

public class MatrixSubtractionDemo
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter number of rows : ");
      int row = sc.nextInt();
      System.out.println("Please enter number of columns : ");
      int col = sc.nextInt();

      int x[][] = new int[row][col];
      int y[][] = new int[row][col];

      System.out.println("Please enter first matrix - ");
      for(int m = 0; m < row; m++)
      {
         for(int n = 0; n < col; n++)
         {
            x[m][n] = sc.nextInt();
         }
      }

      System.out.println("Please enter second matrix - ");
      for(int m = 0; m < row; m++)
      {
         for(int n = 0; n < col; n++)
         {
            y[m][n] = sc.nextInt();
         }
      }

      int z[][] = new int[row][col];
      for(int m = 0; m < row; m++)
      {
         for(int n = 0; n < col; n++)
         {
            // subtraction java
            z[m][n] = x[m][n] - y[m][n];
         }
      }

      System.out.println("The subtraction of two matrices is - ");
      for(int m = 0; m < row; m++)
      {
         for(int n = 0; n < col; n++)
         {
            System.out.print(z[m][n] + " ");
         }
         System.out.println();
      }
   }
}



Output:

matrix addition and subtraction in java

Matrix addition in java using function

  1. first two matrices matrix1 and matrix2 are created.
  2. these two matrices are passed as parameters to matrixAddition() method.
  3. In matrixAddition() method we are checking for length and size of given array.
  4. if given matrix is not of same size then matrix not of same size is printed.
  5. After adding two matrices total is returned to the main method and displayed using displayMatrix() method.

Here’s the java prgoram for matrix addition in java using function or addition of two matrix in java using method.

public class MatrixAdditionUsingFunction 
{
   public static void main(String[] args) 
   {
      int[][] matrix1 = {{2, 4, 6}, {8, 2, 4}};
      int[][] matrix2 = {{1, 3, 5}, {7, 9, 1}};
      int[][] total = matrixAddition(matrix1, matrix2);
      if(total != null) 
      {
         displayMatrix(matrix1);
         System.out.println("---------");
         displayMatrix(matrix2);
         System.out.println("Matrix addition in java using function: ");
         displayMatrix(total);
      }
   }

   public static void displayMatrix(int[][] matrix)
   {
      for(int a = 0; a < matrix.length; a++) 
      {
         for(int b = 0; b < matrix[0].length; b++) 
         {
            System.out.print(" " + matrix[a][b]);
         }
         System.out.println();
      }
   }

   public static int[][] matrixAddition(int[][] x, int[][] y) 
   {
      int arr1 = x.length;
      int arr2 = x[0].length;
      int[][] total = null;
      if((arr1 != y.length) || (arr2 != y[0].length)) 
      {
         System.out.println("Matrices not of same size");
      } 
      else 
      {
         total = new int[arr1][arr2];
         for(int i = 0; i < arr1; i++) 
         {
            for(int j = 0; j < arr2; j++) 
            {
               total[i][j] = x[i][j] + y[i][j];
            }
         }
      }
      return total;
   }
}


Output:

2 4 6

8 2 4

1 3 5
7 9 1
Matrix addition in java using function:
3 7 11
15 11 5

3×3 matrix in java

Let’s see java program on addition of 3×3 matrix in java.

public class AdditionMatrixExample
{
   public static void main(String[] args) 
   {
      int[][] matrix1 = {{2, 4, 8},{1, 3, 5},{7, 9, 2}};    
      int[][] matrix2 = {{4, 6, 8},{1, 3, 5},{7, 9, 2}};      
      // create another matrix to store the sum of 2 matrices    
      int[][] matrix3 = new int[3][3];        
      // add and print 2 matrices
      System.out.println("Addition of 3x3 matrix in java: ");
      for(int a = 0; a < 3; a++)
      {    
         for(int b = 0; b < 3; b++)
         {    
            matrix3[a][b] = matrix1[a][b] + matrix2[a][b];  
            System.out.print(matrix3[a][b] + " ");    
         } 
         System.out.println();    
      }
   }
}


Output:

Addition of 3×3 matrix in java:
6 10 16
2 6 10
14 18 4

This is all about matrix addition and subtraction in java. Above discussed java programs will be useful in java interview for freshers.