Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Friday, October 23, 2020

Java Program to Add Two Matrix Using Multi-dimensional Arrays

1. Overview

In this tutorial, You'll learn how to add two matrix in java using arrays. You should know the basic mathematic problem solving which you learnt in the schooling level for Matrix Addition.

This can be implemented using two for loops easily in java programming.

In the previous article, we have shown how to multiply two matrices in java using threads.

Java Program to Add Two Matrix Using Multi-dimensional Arrays


2. Example Program To Add Two Matrices

Let us write a simple java program that takes two arrays as input and executes the core logic for addition. Finally, output array is printed onto the console.

Key note here is the order of two matrices should be same otherwise can not be computed the output.

package com.javaprogramto.programs.arrays.matrix;

public class MatrixAddition {

	public static void main(String[] args) {
		// creating the first matric using arrays
		int[][] matrix1 = { { 1, 2, 3 }, { 4, 5, 6 } };

		// creating the second matrix using two dimension array
		int[][] matrix2 = { { 1, 2, 3 }, { 4, 5, 6 } };

		// output array for storing the addition result
		int[][] output = new int[matrix1.length][matrix2[1].length];

		// matrix addition core logic
		for (int i = 0; i < matrix1.length; i++) {
			for (int j = 0; j < matrix2[1].length; j++) {
				output[i][j] = matrix1[i][j] + matrix2[i][j];
			}
		}

		// printing the result
		for (int i = 0; i < output.length; i++) {
			for (int j = 0; j < output[1].length; j++) {
				System.out.print(output[i][j]+ " ");
			}
			System.out.println();
		}

	}

}

 

Output:

2 4 6 
8 10 12 

 

Here, First created two 2 dimensions arrays for storing the matrix1 and matrix2.  Next, need to find the rows and columns using matrix1 and matrix 2. 

We initialized the new array with the rows and columns size. This is used to store the result of addition.

Core logic is loop through the two matrices and add the values at the same index from both arrays.

At last, printed the output array using simple for loop.


3. Conclusion

In this article, you've seen how to find the addition of two matrices in java using arrays.

As usual, example shown is over GitHub.

Ref How to initialize the array in java

No comments:

Post a Comment

Please do not add any spam links in the comments section.