Q7

Question 7

Question - 8 Write java program for the following matrix operations:

**a. Addition of two matrices

b. Multiplication of two matrices

c. Transpose of a matrix -- Take input of elements of matrices from user

Code Insights

Created java_2.java, a new java class file and imported java.util.Scanner package to take user input, defined all array and integer variables to store values, method printMatrix takes input of array of integers, its rows and columns and just displays/prints to terminal in desired matrix manner.

In the main method Scanner class object takes the desired input of rows and columns for the two matrices on which the operations will be performed, then takes matrix value inputs (all elements in one-line separated by space " ".).

For Addition: Used nested for-loops to get sum of each indexed value of matrix (array).

For Multiplication: Checks if multiplication is possible for the two matrices and then uses nested for loops to do matrix multiplication corresponding row-wise and column-wise.

For Transposition: Uses two nested for loops to go through each element and swap row and column indexes to transpose the given matrix.

Possible Error Handling

Browse Source Code

Code

5KB
Open
Download java_2.java

Output

Image-1/4 output for java_2.java
Image-2/4 output for java_2.java
Image-4/4 output for java_2.java
Image-3/4 output for java_2.java
Live Demo java_2.java

Last updated