Java Program to Add Two Matrices Using Multi-dimensional Arrays

In this Java program, you’ll learn how to Add Two Matrices Using Multi-dimensional Arrays using the Java programming language. 

How to Add Two Matrices Using Multi-dimensional Arrays using JAVA? 

Example 1: Program to add two Matrices 

RUN CODE SNIPPET
public class Main  
{ 
    public static void main(String[] args)  
    { 
        int rows = 2, columns = 3; 
        int[][] firstMatrix = { {5, 4, 4}, {5, 4, 4} }; 
        int[][] secondMatrix = { {6, 5, 3}, {5, 6, 3} }; 
        int[][] sum = new int[rows][columns]; 
        for(int i = 0; i < rows; i++)  
        { 
            for (int j = 0; j < columns; j++) 
             { 
                sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]; 
            } 
        } 
        System.out.println("Sum of two matrices is: "); 
        for(int[] row : sum) { 
            for (int column : row) { 
                System.out.print(column + "    "); 
            } 
            System.out.println(); 
        } 
    } 
}

OUTPUT 

Sum of two matrices is:  
11    9    7     
10    10    7

In the above program, the two arrays are stored in the firstmatrix and secondmatrix. The number of rows and columns are stored in the variables row and columns. 

The addition of the given two matrix are stored in the array called sum. To add and store the results loop through each index of the given array

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024