Matrix addition in java using function

Let’s learn matrix addition in java using function.

Matrix addition in java using function

  1. first two matrices matrix1 and matrix2 is 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 program.

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) 
      {
         System.out.println("First matrix: ");
         displayMatrix(matrix1);
         System.out.println("Second matrix: ");
         displayMatrix(matrix2);
         System.out.println("Matrix addition 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:

First matrix:
2 4 6
8 2 4
Second matrix:
1 3 5
7 9 1
Matrix addition using function:
3 7 11
15 11 5


Also read – java overview