Matrix addition.
Here’s a Java program that performs matrix addition:
import java.util.Scanner; public class MatrixAddition { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of rows: "); int rows = scanner.nextInt(); System.out.print("Enter the number of columns: "); int columns = scanner.nextInt(); int[][] matrix1 = new int[rows][columns]; int[][] matrix2 = new int[rows][columns]; System.out.println("Enter the elements of the first matrix:"); enterMatrixElements(scanner, matrix1); System.out.println("Enter the elements of the second matrix:"); enterMatrixElements(scanner, matrix2); int[][] resultMatrix = addMatrices(matrix1, matrix2); System.out.println("The sum of the matrices is:"); displayMatrix(resultMatrix); } public static void enterMatrixElements(Scanner scanner, int[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print("Enter element [" + (i + 1) + "][" + (j + 1) + "]: "); matrix[i][j] = scanner.nextInt(); } } } public static int[][] addMatrices(int[][] matrix1, int[][] matrix2) { int rows = matrix1.length; int columns = matrix1[0].length; int[][] result = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { result[i][j] = matrix1[i][j] + matrix2[i][j]; } } return result; } public static void displayMatrix(int[][] matrix) { for (int[] row : matrix) { for (int element : row) { System.out.print(element + " "); } System.out.println(); } } }
In this program, the `main` method asks the user to enter the number of rows and columns for the matrices. It then creates two matrices (`matrix1` and `matrix2`) based on the user input.
The `enterMatrixElements` method is used to prompt the user to enter the elements for each matrix. It takes a `Scanner` object and the matrix as parameters and populates the matrix with the user’s input.
The `addMatrices` method performs the actual matrix addition. It takes two matrices as input, creates a new matrix called `result`, and fills it with the sum of the corresponding elements from `matrix1` and `matrix2`.
The `displayMatrix` method is used to print the elements of a matrix in a readable format.
After the matrices are created and filled, the program calls `addMatrices` to compute the sum and then displays the result using the `displayMatrix` method.
I hope this helps! Let me know if you have any further questions.