In this tutorial, we will learn how to write a program to add two matrices in Java. As this program is based on Array and uses of for loop so you may go through the following first.
Matrices mean having two-dimension that is there are columns and rows in the following java example.
The Program takes the input for both the column and row elements from the user using the scanner class and a third two-dimensional array is created to store the sum result of two matrices. And lastly displays the final result.
Java Program to Add Two Matrices
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | //Addition of a matrix import java.util.Scanner; public class AdditionOfMatrix { public static void main(String args[]) { int row, col, i, j; Scanner sc= new Scanner(System.in); System.out.println("Enter the number of rows"); row = sc.nextInt(); System.out.println("Enter the number columns"); col = sc.nextInt(); int mat1[][] = new int[row][col]; int mat2[][] = new int[row][col]; int result[][] = new int[row][col]; //First matrix Input System.out.println("Enter the elements of matrix1"); for ( i= 0 ; i < row ; i++ ) { for ( j= 0 ; j < col ;j++ ) mat1[i][j] = sc.nextInt(); } //Second matrix Input System.out.println("Enter the elements of matrix2"); for ( i= 0 ; i < row ; i++ ) { for ( j= 0 ; j < col ;j++ ) mat2[i][j] = sc.nextInt(); } //Addition for ( i= 0 ; i < row ; i++ ) for ( j= 0 ; j < col ;j++ ) result[i][j] = mat1[i][j] + mat2[i][j] ; System.out.println("Result of Addition:-"); for ( i= 0 ; i < row ; i++ ) { for ( j= 0 ; j < col ;j++ ) System.out.print(result[i][j]+"\t"); System.out.println(); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | Enter the number of rows 3 Enter the number columns 2 Enter the elements of matrix1 1 1 1 1 1 1 Enter the elements of matrix2 1 1 1 1 1 1 Result of Addition:- 2 2 2 2 2 2 |