Explanation
This Java code implements a program to perform addition and multiplication of two matrices. It guides the user through entering the dimensions and elements of two matrices, then checks if the operations are mathematically possible based on their dimensions. If addition is possible (matrices have the same number of rows and columns), it calculates and displays their sum. Similarly, if multiplication is possible (the number of columns in the first matrix equals the number of rows in the second matrix), it calculates and displays their product.
The program is structured using several helper methods:
input(Scanner sc, String msg): A utility method to prompt the user for an integer value (like dimensions) and read it.
readMatrix(Scanner sc, int r, int c, String name): Takes matrix dimensions (rows r, columns c) and a name, then prompts the user to enter each element of the matrix.
printMatrix(int[][] m): Takes a 2D integer array (matrix) and prints its elements neatly row by row.
addMatrices(int[][] a, int[][] b): Performs element-wise addition of two matrices a and b, returning a new matrix representing their sum. It assumes compatible dimensions are already checked.
multiplyMatrices(int[][] a, int[][] b): Performs standard matrix multiplication of matrices a and b, returning a new matrix representing their product. It assumes compatible dimensions are already checked.
main(String[] args): This is the entry point of the program. It orchestrates the entire process: getting dimensions, validating them, reading matrix elements, printing the original matrices, checking conditions for addition and multiplication, calling the respective operation methods, and printing results or error messages.
The core logic involves nested loops for iterating through matrix elements, and specific conditions (rA == rB && cA == cB for addition, cA == rB for multiplication) to determine the feasibility of matrix operations.
Algorithm
The program follows these steps:
- Initialize Scanner: Create a
Scanner object to read user input from the console.
- Get Matrix Dimensions:
- Prompt the user to enter the number of rows (
rA) and columns (cA) for Matrix A.
- Prompt the user to enter the number of rows (
rB) and columns (cB) for Matrix B.
- Use the
input helper method for this.
- Validate Dimensions: Check if any of the entered dimensions (
rA, cA, rB, cB) are less than or equal to zero. If so, print an "Invalid dimensions" error and exit.
- Read Matrix Elements:
- Call
readMatrix to populate Matrix A with rA rows and cA columns.
- Call
readMatrix to populate Matrix B with rB rows and cB columns.
- Print Input Matrices:
- Print a label "Matrix A:" and then call
printMatrix to display Matrix A.
- Print a label "Matrix B:" and then call
printMatrix to display Matrix B.
- Perform Matrix Addition (Conditional):
- Check Condition: Verify if the dimensions for addition are compatible:
rA must be equal to rB AND cA must be equal to cB.
- If Compatible:
- Print a label "Sum:".
- Call
addMatrices(a, b) to calculate the sum.
- Call
printMatrix to display the resulting sum matrix.
- If Incompatible:
- Print an "Addition: dimensions mismatch." message.
- Perform Matrix Multiplication (Conditional):
- Check Condition: Verify if the dimensions for multiplication are compatible:
cA (columns of A) must be equal to rB (rows of B).
- If Compatible:
- Print a label "Product:".
- Call
multiplyMatrices(a, b) to calculate the product.
- Call
printMatrix to display the resulting product matrix.
- If Incompatible:
- Print a "Multiplication: invalid dimensions." message.
- Close Scanner: Close the
Scanner object to release system resources.
Sub-algorithms for Matrix Operations:
-
readMatrix(Scanner sc, int r, int c, String name):
- Create a new 2D integer array
m of size r x c.
- Use nested
for loops (outer for rows i from 0 to r-1, inner for columns j from 0 to c-1).
- Inside the inner loop, prompt the user to enter the element for
name[i+1][j+1] (using 1-based indexing for user-friendliness).
- Read the integer input using
sc.nextInt() and store it in m[i][j].
- Return the populated matrix
m.
-
printMatrix(int[][] m):
- Use an enhanced
for loop to iterate through each row in the matrix m.
- Inside, use another enhanced
for loop to iterate through each val in the current row.
- Print
val followed by a space.
- After printing all elements in a row, print a new line character to move to the next row.
-
addMatrices(int[][] a, int[][] b):
- Create a new 2D integer array
sum with the same dimensions as a (which are also the same as b).
- Use nested
for loops (outer for rows i from 0 to a.length-1, inner for columns j from 0 to a[0].length-1).
- Inside the inner loop, calculate
sum[i][j] = a[i][j] + b[i][j].
- Return the
sum matrix.
-
multiplyMatrices(int[][] a, int[][] b):
- Create a new 2D integer array
product with dimensions a.length (rows of A) x b[0].length (columns of B). Initialize all elements to 0 (default for int arrays).
- Use three nested
for loops:
- Outer loop for
i (row of product matrix, iterating from 0 to a.length-1).
- Middle loop for
j (column of product matrix, iterating from 0 to b[0].length-1).
- Innermost loop for
k (index for dot product calculation, iterating from 0 to b.length-1 which is also a[0].length-1).
- Inside the innermost loop, calculate
product[i][j] += a[i][k] * b[k][j]. This accumulates the sum of products for each element in the resulting matrix.
- Return the
product matrix.