Java Matrix Addition Example


 

Java Matrix Addition Example

In this tutorial, you will learn how to find the sum of two matrices.

In this tutorial, you will learn how to find the sum of two matrices.

Java Matrix Addition Example

In this tutorial, you will learn how to find the sum of two matrices.

You may have solved many Matrix Operations in Mathematics. A Matrix comprises of rows and columns. Here we are going to calculate the sum of two matrices of any order using the java language. In the given program, firstly we have allowed the user to enter the number of rows and columns to show in matrices and then accept the matrix elements as array elements. We have declared two 2-dimensional array of integer type to store the matrix elements. Now to calculate the sum of matrices, we have created a method matrixSum() that accepts the two arrays and the number of rows and columns and returns a 2-d array that stores the result of two matrices.

Example:

import java.util.*;
class MatrixAddition{
public static void matrixSum(int A[][],int B[][],int m, int n){
int[][] C = new int[m][n];
System.out.println("Matrix A: ");
for(int i=0 ; i < A.length ; i++){
System.out.println();
for(int j=0 ; j < A[i].length ; j++){
System.out.print(A[i][j]+" ");
}
}
System.out.println();
System.out.println();
System.out.println("Matrix B: ");
for(int i=0 ; i < B.length ; i++){ 
System.out.println();
for(int j=0 ; j < B[i].length ; j++){
System.out.print(B[i][j]+" ");
}
}
System.out.println();
System.out.println();
System.out.println("Addition Of Matrices: ");
for(int i=0;i<C.length;i++){
for(int j=0;j<C[i].length;j++){
C[i][j]=A[i][j]+B[i][j];
System.out.print(C[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter Number of rows: ");
int m = input.nextInt();

System.out.print("Enter Number of columns: ");
int n = input.nextInt();
int[][] A = new int[m][n];
int[][] B = new int[m][n];

System.out.println("Enter elements for matrix A : ");
for(int i=0 ; i < A.length ; i++)
for(int j=0 ; j < A[i].length ; j++){
A[i][j] = input.nextInt();
}
System.out.println("Enter elements for matrix B : ");
for (int i=0 ; i < B.length ; i++)
for (int j=0 ; j < B[i].length ; j++){
B[i][j] = input.nextInt();
}
MatrixAddition mx=new MatrixAddition();
mx.matrixSum(A,B,m,n);
}
}

Output

Enter Number of rows: 3
Enter Number of columns: 3
Enter elements for matrix A :
1
2
3
4
5
6
2
1
3
Enter elements for matrix B :
5
2
3
5
5
1
2
2
5
Matrix A:

1 2 3
4 5 6
2 1 3

Matrix B:

5 2 3
5 5 1
2 2 5

Addition Of Matrices:
6 4 6
9 10 7
4 3 8

Ads