Saturday, 28 September 2019

Java Program to Perform Matrix Addition and Subtraction

          In the previous post, written code for matrix transpose. In the current post, I have written a java program to perform a simple matrix addition and subtraction. 

Below is the source code of the Java Program to Perform Matrix Multiplication,

MatrixAdditionSubtraction.java,

package com.example.demo;

public class MatrixAdditionSubtraction {

        public static void main(String[] args) {

                int[][] a = { { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } };
                int[][] b = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

                int rows = 3;
                int columns = 3;

                int[][] c = new int[rows][columns];

                for (int i = 0; i < rows; i++) {
                       for (int j = 0; j < columns; j++) {
                              c[i][j] = a[i][j] + b[i][j];
                       }
                }

                System.out.println("The sum of the two matrices is");

                for (int i = 0; i < rows; i++) {
                       for (int j = 0; j < columns; j++) {
                              System.out.print(c[i][j] + " ");
                       }
                       System.out.println();
                }

                for (int i = 0; i < rows; i++) {
                       for (int j = 0; j < columns; j++) {
                               c[i][j] = a[i][j] - b[i][j];
                       }
                }

                System.out.println("The subtraction of the two matrices is");

                for (int i = 0; i < rows; i++) {
                       for (int j = 0; j < columns; j++) {
                              System.out.print(c[i][j] + " ");
                       }
                       System.out.println();
                }

        }
}

Output:--
The sum of the two matrices is
5 7 9 
11 13 15 
17 19 21 
The subtraction of the two matrices is
3 3 3 
3 3 3 
3 3 3 

Related Posts:--
1) Java code to move all zero of an integer array to the end of the array
2) Java Program to Perform Matrix Multiplication
3) Write a Java program to print the Floyd's triangle
4) Java Code to Print the Numbers as Pyramid - Examples
5) Java Program to find the Missing Number in an Array
6) Java program to print the first n prime numbers
7) Swap two variables without using third variable in Java
8) Java program to find second largest number in an array
9) Sort a binary array using one traversal in Java
10) Difference between NoClassDefFoundError and ClassNotFoundException in Java

No comments:

Post a comment