Write a Java program that prompts the user to input numbers in two matrices of the same size and compute the sum of the matrices
import java.util.Scanner;
public class App {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Input number of rows of matrix: ");
int numberRows = in.nextInt();
System.out.print("Input number of columns of matrix: ");
int columnsMatrix = in.nextInt();
int matrix1[][] = new int[numberRows][columnsMatrix];
int matrix2[][] = new int[numberRows][columnsMatrix];
int matrixSum[][] = new int[numberRows][columnsMatrix];
System.out.println("Input elements of first matrix: ");
for (int i = 0; i < numberRows; i++) {
for (int j = 0; j < columnsMatrix; j++) {
matrix1[i][j] = in.nextInt();
}
}
System.out.println("Input the elements of second matrix: ");
for (int i = 0; i < numberRows; i++) {
for (int j = 0; j < columnsMatrix; j++) {
matrix2[i][j] = in.nextInt();
}
}
for (int i = 0; i < numberRows; i++) {
for (int j = 0; j < columnsMatrix; j++) {
matrixSum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
System.out.println("Sum of the matrices:");
for (int i = 0; i < numberRows; i++) {
for (int j = 0; j < columnsMatrix; j++) {
System.out.print(matrixSum[i][j] + "\t");
}
System.out.println();
}
in.close();
}
}
Comments
Leave a comment