February 5, 2022

Matrix Addition Java Program

This post shows a Java program to add two matrices.

When you add two matrices you add the element at the same index in both matrices so you’ll add the element at index (0, 0) in the first matrix with the element at index (0, 0) in the second matrix to get the element at (0, 0) in the resultant matrix. Also note that both of the matrix have to be of the same order for addition.

For example– If you are adding two 3 X 3 matrices.

Matrix addition java program

Java program for matrix addition

import java.util.Scanner;
public class MatrixAddition {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter number of rows and columns in the matrix : ");
    int row = in.nextInt();
    int column = in.nextInt();
    // First matrix
    int[][] matrix1 = prepareMatrix(row, column);

    // Second matrix
    int[][] matrix2 = prepareMatrix(row, column);
    // addition result stored in this matrix
    int addedMatrix[][] = new int[row][column];
    // Addition logic 
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        addedMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
      }
    }
        
    System.out.println("Added Matrix : " );
    for(int i = 0; i < addedMatrix.length; i++){
      for(int j = 0; j < column; j++){
        System.out.print(" " +addedMatrix[i][j]+"\t");
      }
      System.out.println();
    }
  }
	
  private static int[][] prepareMatrix(int row, int column){
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter elements of Matrix : ");
    int matrix[][] = new int[row][column];
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        matrix[i][j] = sc.nextInt();
      }
    }
    System.out.println("Entered Matrix : " );
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        System.out.print(" " +matrix[i][j]+"\t");
      }
      System.out.println();
    }
    return matrix;
  }
}
Output
Enter number of rows and columns in the matrix : 3 3
Enter elements of Matrix : 1 3 5 7 9 11 13 15 17
Entered Matrix : 
 1	 3	 5	
 7	 9	 11	
 13	 15	 17	
Enter elements of Matrix : 2 4 6 8 10 12 14 16 18
Entered Matrix : 
 2	 4	 6	
 8	 10	 12	
 14	 16	 18	
Added Matrix : 
 3	 7	 11	
 15	 19	 23	
 27	 31	 35	

That's all for the topic Matrix Addition Java Program. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment