This is the second program in the series of matrices-related programming exercises in Java. In the last program, you have learned matrix multiplication and in this program, you will learn how to perform addition and subtraction of two matrices in Java. We'll create methods to calculate both sum and difference of two matrices in the Java program. In Mathematics, a matrix is a rectangular array with two dimensions known as rows and columns. In Java, you can use a two-dimensional array to represent a matrix because it also has two dimensions rows, and columns.
Since a 2D array is nothing but an array of the array in Java, the length of the outer array is equal to the number of rows, and the length of the sub-array is equal to the number of columns.
For example, to represent a 2x3 matrix in Java you need to create a two-dimensional integer array with two rows and three columns e.g. int[][] matrix = new int[2][3]. By default, each value in the two-dimensional array is populated with the default value for that data type i.e. zero for an integer array.
In order to calculate sum of two matrices, you need to loop through array and add respective elements from each matrix e.g. if given matrices are X and Y then addition of these matrices will z[i][j] = x[i][j] + y[i][j]. For subtraction just use the minus sign instead of the plus sign.
That's why the dimension of both matrices should be the same to perform addition e.g. both must have the same row and same columns.
For example, to represent a 2x3 matrix in Java you need to create a two-dimensional integer array with two rows and three columns e.g. int[][] matrix = new int[2][3]. By default, each value in the two-dimensional array is populated with the default value for that data type i.e. zero for an integer array.
In order to calculate sum of two matrices, you need to loop through array and add respective elements from each matrix e.g. if given matrices are X and Y then addition of these matrices will z[i][j] = x[i][j] + y[i][j]. For subtraction just use the minus sign instead of the plus sign.
How to add two matrices in Java
In order to add two matrices in maths, you just need to add the numbers in the matching positions e.g. number in the first row and column of the first matrix should be added to the first number in the second matrix as well, as shown in the following diagram:That's why the dimension of both matrices should be the same to perform addition e.g. both must have the same row and same columns.
How to subtract two matrices in Java
In order to calculate the difference between the two matrices, you just need to subtract numbers in the matching position like subtracting the first number of the first matrix with the first number of the second matrix. Actually, subtraction is nothing but the addition of a negative matrix e.g. to subtract matrix A and B, you perform the addition of A + (-B).Here is a nice diagram that explains subtraction of matrices:
Now, let's see our program to calculate the sum and difference of two matrices in Java. Btw, if you are also interested in programming exercises, you could try solving problems asked in various technical interviews like Amazon or Facebook, or any startups.
Now, let's see our program to calculate the sum and difference of two matrices in Java. Btw, if you are also interested in programming exercises, you could try solving problems asked in various technical interviews like Amazon or Facebook, or any startups.
You can also find a good collection of those questions in the Cracking the Coding Interview book. The 6th edition contains more than 189 problems and their solutions.
This is not really an object-oriented approach but it's good for such tasks. All program is coded into a single class MatrixAdditionSubtractionDemo, which also has methods to perform addition and subtraction of matrices, a method to print matrices into the command prompt and a method to read user input from the command prompt and populate the matrices. We are also using Scanner to read user input from the command prompt.
The code to test the add() and subtract() method is inside the main() method, which creates two matrices in form of a two-dimensional array and passes it to these methods for calculating sum and difference.
You can see the sum and difference of matrices are correctly calculated as per the formula we have discussed in the second paragraph. One of the important lessons I learned while doing this exercise was about the Scanner class. Earlier, I was creating and closing Scanner on the read() method itself as shown below:
When I had this code, I was getting the following Exception consistently while reading second matrices from the command prompt:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Pattern.read(Pattern.java:66)
at Pattern.main(Pattern.java:29)
This was coming because I was closing Scanner after reading the first matrices and creating another instance for reading the second matrices, this all looks good on code but Java doesn't allow that. Once you close the Scanner you cannot open it again for the same stream, in our case we are using System.in, which is an InputStream for reading data entered on the command prompt.
To solve this error, I am creating Scanner once in the program and supplying that to read method for reading purposes and once I read both matrices from the command line I close the Scanner in the main() method itself. Even after working in Java for so many years, I didn't know this detail. So, even a simple program can teach us some useful things :-)
That's all about how to add and subtract two matrices in Java. If you are interested in more programming exercises you can check out the post listed below or you can also start solving problems from the "57 Challenges to Develop Your Coding Skills", a good book with lots of programs to improve your programming skills.
Other Java Programs for Beginners for Practice
Also, what is your favorite Java programming exercise? Palindrom, Prime Number, Fibonacci series, Binary Search, or this one? Do let me know in comments.
Java Program to add and subtract two matrices in Java
Here is our complete Java program to perform the addition and subtraction of two matrices. Unlike the last article where we have created a class called Matrix to represent matrices in Java which had rows and columns and holds matrix data into a two-dimensional array, in this program, we'll perform addition and subtraction of matrices using static methods, which takes two matrices and return their sum and difference.This is not really an object-oriented approach but it's good for such tasks. All program is coded into a single class MatrixAdditionSubtractionDemo, which also has methods to perform addition and subtraction of matrices, a method to print matrices into the command prompt and a method to read user input from the command prompt and populate the matrices. We are also using Scanner to read user input from the command prompt.
The code to test the add() and subtract() method is inside the main() method, which creates two matrices in form of a two-dimensional array and passes it to these methods for calculating sum and difference.
import java.util.Scanner; /* * Java Program to add and subtract two matrices. * A matrix can be represented as two dimensional array in Java */ public class MatrixAdditionSubtractionDemo { public static void main(String[] args) { System.out.println("Welcome to Java program for calculating sum and difference of two matrices"); // we need a Scanner to read input from Console Scanner scnr = new Scanner(System.in); System.out.print("Please Enter number of rows: "); int rows = scnr.nextInt(); System.out.print("Please Enter number of columns: "); int columns = scnr.nextInt(); System.out.println(); System.out.println("Please Enter first matrix"); int[][] a = read(scnr, rows, columns); System.out.println(); System.out.println("Please Enter second matrix"); int[][] b = read(scnr, rows, columns); scnr.close(); // adding two matrices int[][] sum = add(a, b); // subtracting two matrices int[][] difference1 = subtract(a, b); int[][] difference2 = subtract(b, a); System.out.println("The sum of two matrices is: "); System.out.println("A + B ="); printMatrix(sum); System.out.println("The differnece of two matrices is: "); System.out.println("A - B ="); printMatrix(difference1); System.out.println("Subtraction of matrix in opposite order"); System.out.println("B - A ="); printMatrix(difference2); scnr.close(); } /** * a method to populate a matrix by reading input from console in Java * * @param rows * @param columns * @return matrix filled by user input from console */ public static int[][] read(Scanner s, int rows, int columns) { int[][] result = new int[rows][columns];; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.println("Enter value of [" + (i+1) + "][" + (j+1) +"]"); result[i][j] = s.nextInt(); } } return result; } /** * Java Program to calculate sum of two matrices * * @param a * @param b * @return return sum of given matrices */ public static int[][] add(int[][] a, int[][] b) { int rows = a.length; int columns = a[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] = a[i][j] + b[i][j]; } } return result; } /** * Java Program to calculate difference of two matrices * * @param a * @param b * @return difference of given matrix */ public static int[][] subtract(int[][] a, int[][] b) { int rows = a.length; int columns = a[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] = a[i][j] - b[i][j]; } } return result; } /** * a Java method to print result in matrix format. * * @param matrix */ public static void printMatrix(int[][] matrix) { int rows = matrix.length; int columns = matrix[0].length; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } } Output Welcome to Java program for calculating sum and difference of two matrices Please Enter number of rows: 2 Please Enter number of columns: 2 Please Enter first matrix Enter value of [1][1] 1 Enter value of [1][2] 2 Enter value of [2][1] 3 Enter value of [2][2] 4 Please Enter second matrix Enter value of [1][1] 5 Enter value of [1][2] 6 Enter value of [2][1] 7 Enter value of [2][2] 8 The sum of two matrices is: A + B = 6 8 10 12 The difference of two matrices is: A - B = -4 -4 -4 -4 Subtraction of matrix in opposite order B - A = 4 4 4 4
You can see the sum and difference of matrices are correctly calculated as per the formula we have discussed in the second paragraph. One of the important lessons I learned while doing this exercise was about the Scanner class. Earlier, I was creating and closing Scanner on the read() method itself as shown below:
public static int[][] read(int rows, int columns) { int[][] result = new int[rows][columns]; Scanner s = new Scanner(System.in); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.println("Enter value of [" + i + "][" + j +"]"); result[i][j] = s.nextInt(); } } s.close(); return result; }
When I had this code, I was getting the following Exception consistently while reading second matrices from the command prompt:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Pattern.read(Pattern.java:66)
at Pattern.main(Pattern.java:29)
This was coming because I was closing Scanner after reading the first matrices and creating another instance for reading the second matrices, this all looks good on code but Java doesn't allow that. Once you close the Scanner you cannot open it again for the same stream, in our case we are using System.in, which is an InputStream for reading data entered on the command prompt.
To solve this error, I am creating Scanner once in the program and supplying that to read method for reading purposes and once I read both matrices from the command line I close the Scanner in the main() method itself. Even after working in Java for so many years, I didn't know this detail. So, even a simple program can teach us some useful things :-)
That's all about how to add and subtract two matrices in Java. If you are interested in more programming exercises you can check out the post listed below or you can also start solving problems from the "57 Challenges to Develop Your Coding Skills", a good book with lots of programs to improve your programming skills.
Other Java Programs for Beginners for Practice
- How to find if given Integer is Palindrome in Java? (solution)
- How to implement binary search using recursion in Java? (solution)
- How to check if two rectangles intersect with each other in Java? (solution)
- How to implement Linear Search in Java? (solution)
- How to reverse words in a given String in Java? (solution)
- How to calculate Area of Triangle in Java? (program)
- How to remove duplicate characters from String in Java? (solution)
- How to count vowels and consonants in a given String in Java? (solution)
- How to remove duplicate elements from the array in Java? (solution)
- How to check if given number is prime in Java (solution)
- How to print Fibonacci series in Java (solution)
- How to reverse a String in place in Java? (solution)
- How to find the highest occurring word from a given file in Java? (solution)
- How to check if a year is a leap year in Java? (solution)
- How to check if given String is palindrome or not in Java? (solution)
- How to check if two given Strings are Anagram in Java? (solution)
- How to find all permutations of a given String in Java? (solution)
- How to check if a String contains duplicate characters in Java? (solution)
- How to calculate the sum of all elements of an array in Java? (program)
- How to calculate the square root of a given number in Java? (solution)
- How to reverse an array in place in Java? (solution)
- How to calculate the average of all numbers of an array in Java? (program)
Also, what is your favorite Java programming exercise? Palindrom, Prime Number, Fibonacci series, Binary Search, or this one? Do let me know in comments.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.