HomeJavaJava Program to Add Two Matrices Using Multi-dimensional Arrays

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

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022