Java Tutorial
In java programming, this program is used to accepts two matrix as user inputs and computes sum of two matrix.
Row and Column value for all the matrix is also user inputs.
import java.util.Scanner; class MatrixAddition { public static void main(String args[]) { int row, column; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows and columns of matrix: "); row = in.nextInt(); column = in.nextInt(); int matrixA[][] = new int[row][column]; int matrixB[][] = new int[row][column]; int sumMatrix[][] = new int[row][column]; System.out.println("Enter the elements of first matrix: "); for (int i = 0 ; i <row ; i++ ) for ( int j = 0 ; j <column ; j++ ) matrixA[i][j] = in.nextInt(); System.out.println("Enter the elements of second matrix: "); for (int i = 0 ; i <row ; i++ ) for ( int j = 0 ; j <column ; j++ ) matrixB[i][j] = in.nextInt(); System.out.println("Sum of Matrix"); for (int i = 0 ; i <row ; i++ ) for ( int j = 0 ; j <column ; j++ ) sumMatrix[i][j] = matrixA[i][j] + matrixB[i][j]; for (int i = 0 ; i <column; i++ ) { for (int j = 0 ; j < row; j++ ) { System.out.print(sumMatrix[i][j]+"\t"); } System.out.print("\n"); } } }Output:
D:\Java_Programs>javac MatrixAddition.java D:\Java_Programs>java MatrixAddition Enter the number of rows and columns of matrix: 2 2 Enter the elements of first matrix: 5 6 7 8 Enter the elements of second matrix: 1 2 3 4 Sum of Matrix 6 8 10 12
import java.util.Scanner; class MatrixAddition { public static void main(String args[]) { int row, column; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows and columns of matrix: "); row = in.nextInt(); column = in.nextInt(); int matrixA[][] = new int[row][column]; int matrixB[][] = new int[row][column]; int sumMatrix[][] = new int[row][column]; System.out.println("Enter the elements of first matrix: "); int i = 0 ; int j = 0 ; while ( i <row ){ j = 0 ; while ( j <column ) { matrixA[i][j] = in.nextInt(); j++; } i++; } System.out.println("Enter the elements of second matrix: "); i = 0 ; while ( i <row ){ j = 0 ; while ( j <column ) { matrixB[i][j] = in.nextInt(); j++; } i++; } System.out.println("Sum of Matrix"); i = 0 ; while ( i <row ){ j = 0 ; while ( j <column ) { sumMatrix[i][j] = matrixA[i][j] + matrixB[i][j]; j++; } i++; } i = 0 ; while ( i <row ){ j = 0 ; while ( j <column ) { System.out.print(sumMatrix[i][j]+"\t"); j++; } System.out.print("\n"); i++; } } }Output:
D:\Java_Programs>javac MatrixAddition.java D:\Java_Programs>java MatrixAddition Enter the number of rows and columns of matrix: 2 2 Enter the elements of first matrix: 5 6 7 8 Enter the elements of second matrix: 1 2 3 4 Sum of Matrix 6 8 10 12
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page