Write a Java Program to Add Two 2D Matrix

Write a Java Program to Add Two 2D Matrix thumbnail
7K
By Dhiraj Ray 10 January, 2018

Description

A matrix is a rectangular array of numbers or expressions arranged in rows and columns.Below is the java program to add two 2D matrices.We can change the dimension variables accordingly for 3D and 4D matrix.

MatrixAddition.java
public class MatrixAddition {

	public static void main(String[] args) {
		
		int[][] matrix1 ={ {10,12},{10,12} };
		int[][] matrix2 ={ {10,12},{10,12} };
		addMatrices(matrix1, matrix2);
		
	}
	public static int[][] addMatrices(int[][] matrix1 , int[][] matrix2){
		int m=2 ;
		int n =2;
		int sum[][] = new int[m][n];
		for (int c = 0 ; c < m ; c++ ){
	        for (int d = 0 ; d < n ; d++ ){
	           sum[c][d] = matrix1[c][d] + matrix2[c][d];
	        }
		}
		 for ( int  c = 0 ; c < m ; c++ )
	      {
	         for ( int d = 0 ; d < n ; d++ )
	            System.out.print(sum[c][d]+"\t");
	 
	         System.out.println();
	      }
		return sum;
		
	} 

Explanation

In the above program we have two 2D matrix.Hence, the resulting matrix will have two cols and two rows.Here m and n stands for the rows and columns respectively. The first for loop continues for each row the inner loop continues for the columns present in a row. [{00}] elmement in sum matrix is the result of matrix1[{00}] and matrix2[{00}]

Share

Support This Free Tool!

Buying me a coffee helps keep the project running and supports new features.

cards
Powered by paypal

Thank you for helping this blog thrive!

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.