2. Program to Add Two Matrices
💡Code:
import java.util.Scanner;
public class AddMatrices {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get the number of rows and columns from the user
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int columns = scanner.nextInt();
// Create the first matrix
int[][] matrix1 = new int[rows][columns];
System.out.println("Enter elements for the first matrix:");
inputMatrix(matrix1, scanner);
// Create the second matrix
int[][] matrix2 = new int[rows][columns];
System.out.println("Enter elements for the second matrix:");
inputMatrix(matrix2, scanner);
// Add the matrices
int[][] sumMatrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Display the result
System.out.println("Sum of the matrices:");
printMatrix(sumMatrix);
// Close the scanner
scanner.close();
}
// Function to input elements into a matrix
private static void inputMatrix(int[][] matrix, Scanner scanner) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print("Enter element at position [" + (i + 1) + "][" + (j + 1) + "]: ");
matrix[i][j] = scanner.nextInt();
}
}
}
// Function to print a matrix
private static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // Move to the next row
}
}
}
📸Output :