The Wayback Machine - https://web.archive.org/web/20240907092828/https://www.geeksforgeeks.org/java-program-to-add-two-matrices/
Open In App

Java Program to Add two Matrices

Last Updated : 04 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two matrices A and B of same size, the task to add them in Java. 
Examples: 

Input: A[][] = {{1, 2}, 
{3, 4}}
B[][] = {{1, 1},
{1, 1}}
Output: {{2, 3},
{4, 5}}

Input: A[][] = {{2, 4},
{3, 4}}
B[][] = {{1, 2},
{1, 3}}
Output: {{3, 6},
{4, 7}}

Approach:  

  • Take the two matrices to be added
  • Create a new Matrix to store the sum of the two matrices
  • Traverse each element of the two matrices and add them. Store this sum in the new matrix at the corresponding index.
  • Print the final new matrix

Below is the implementation of the above approach: 

Java
// Java program for addition of two matrices

import java.io.*;

class GFG {

    // Function to print Matrix
    static void printMatrix(int M[][],
                            int rowSize,
                            int colSize)
    {
        for (int i = 0; i < rowSize; i++) {
            for (int j = 0; j < colSize; j++)
                System.out.print(M[i][j] + " ");

            System.out.println();
        }
    }

    // Function to add the two matrices
    // and store in matrix C
    static int[][] add(int A[][], int B[][],
                       int size)
    {
        int i, j;
        int C[][] = new int[size][size];

        for (i = 0; i < size; i++)
            for (j = 0; j < size; j++)
                C[i][j] = A[i][j] + B[i][j];

        return C;
    }

    // Driver code
    public static void main(String[] args)
    {
        int size = 4;

        int A[][] = { { 1, 1, 1, 1 },
                      { 2, 2, 2, 2 },
                      { 3, 3, 3, 3 },
                      { 4, 4, 4, 4 } };
        // Print the matrices A
        System.out.println("\nMatrix A:");
        printMatrix(A, size, size);

        int B[][] = { { 1, 1, 1, 1 },
                      { 2, 2, 2, 2 },
                      { 3, 3, 3, 3 },
                      { 4, 4, 4, 4 } };
        // Print the matrices B
        System.out.println("\nMatrix B:");
        printMatrix(B, size, size);

        // Add the two matrices
        int C[][] = add(A, B, size);

        // Print the result
        System.out.println("\nResultant Matrix:");
        printMatrix(C, size, size);
    }
}

Output
Matrix A:
1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 4 

Matrix B:
1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 4 

Resultant Matrix:
2 2 2 2 
4 4 4 4 
6 6 6 6 
8 8 8 8

Time Complexity: O(N2), where N is the row or column number of the matrix

Auxiliary Space: O(N2)



Previous Article
Next Article

Similar Reads

Python Program to Add Two Matrices
Given two matrices X and Y, the task is to compute the sum of two matrices and then print it in Python. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Output : result= [[10,10,10], [10,10,10], [10,10,10]]Add Two Matrices Using for loopHere we will use for loop with two matrices for adding the elements [GFGTABS] P
4 min read
Python program to add two matrices
Prerequisite : Arrays in Python, Loops, List Comprehension Program to compute the sum of two matrices and then print it in Python. We can perform matrix addition in various ways in Python. Here are a two of them. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Output : result= [[10,10,10], [10,10,10], [10,10,10]]U
2 min read
Java Program to Subtract the Two Matrices
Given below the two matrices A and B, the task is to subtract them, and for subtracting the matrices the size of both the matrix should be the same i.e. both the matrix must have N X M dimension. Example: Input : A[][] = {{3, 1}, {2, 4}} B[][] = {{1, 1}, {2, 1}}Output: {{2, 0}, {0, 3}}Input : A[][] = {{1, 2}, {3, 4}} B[][] = {{6, 4}, {1, 3}} Output
3 min read
Java Program to Check the Multiplicability of Two Matrices
Given two matrices, the task to check Multiplicability of them. Matrices can either be square or rectangular. Matrices must have the same datatype. Multiplicablity of the matrix depends on their ROWS and COLUMNS. If the Columns of the first matrix are equal to the Rows of the second matrix then both the matrices are multiplicable. Example: Input :
2 min read
Java Program to multiply two matrices
Given two matrices, the task to multiply them. Matrices can either be square or rectangular. Examples:  Input : mat1[][] = {{1, 2}, {3, 4}} mat2[][] = {{1, 1}, {1, 1}} Output : {{3, 3}, {7, 7}} Input : mat1[][] = {{2, 4}, {3, 4}} mat2[][] = {{1, 2}, {1, 3}} Output : {{6, 16}, {7, 18}}Recommended: Please solve it on "PRACTICE" first, before moving o
4 min read
Java Program for Kronecker Product of two matrices
Given a [Tex]{m} imes{n} [/Tex]matrix A and a [Tex]{p} imes{q} [/Tex]matrix B, their Kronecker product C = A tensor B, also called their matrix direct product, is an [Tex]{(mp)} imes{(nq)} [/Tex]matrix. A tensor B = |a11B a12B| |a21B a22B| = |a11b11 a11b12 a12b11 a12b12| |a11b21 a11b22 a12b21 a12b22| |a11b31 a11b32 a12b31 a12b32| |a21b11 a21b12 a22
3 min read
Java Program to Multiply two Matrices of any size
In Java, Matrix Multiplication is a complex operation, unlike multiplying two constant numbers. In this article, we will learn How to multiply two matrices in Java. Example of Multiplication of Two Matrices Note: Two matrices are multiplicable if the number of coloumns in the first matrix is equal to the number of rows in the second matrix. Approac
3 min read
Python List Equality | Program to check if two given matrices are identical
We are given two square matrices of same order. Check if two given matrices are identical. Examples: Input : A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] Output: Matrices are identical We have existing solution for this problem please refer C Program to check if two give
3 min read
Program to concatenate two given Matrices of same size
Given two matrices A and B of size M x N, the task is to concatenate them into one matrix.Concatenation of matrix: The process of appending elements of every row of the matrix one after the other is known as the Concatenation of matrix. Examples: Input: A[][] = {{1, 2}, {3, 4}}, B[][] = {{5, 6}, {7, 8}} Output: 1 2 5 6 3 4 7 8 Explanation: Elements
6 min read
Program for addition of two matrices
Given two N x M matrices. Find a N x M matrix as the sum of given matrices each value at the sum of values of corresponding elements of the given two matrices. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: Below is the idea to solve the problem. Iterate over every cell of matrix (i, j), add the corres
7 min read
Program to check if two given matrices are identical
The below program checks if two square matrices of size 4*4 are identical or not. For any two matrices to be equal, a number of rows and columns in both the matrix should be equal and the corresponding elements should also be equal. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Implementation: C/C++ Code // C++
6 min read
Javascript Program for Kronecker Product of two matrices
Given a [Tex]{m} imes{n} [/Tex]matrix A and a [Tex]{p} imes{q} [/Tex]matrix B, their Kronecker product C = A tensor B, also called their matrix direct product, is an [Tex]{(mp)} imes{(nq)} [/Tex]matrix. A tensor B = |a11B a12B| |a21B a22B| = |a11b11 a11b12 a12b11 a12b12| |a11b21 a11b22 a12b21 a12b22| |a11b31 a11b32 a12b31 a12b32| |a21b11 a21b12 a22
3 min read
Python program to multiply two matrices
Given two matrix the task is that we will have to create a program to multiply two matrices in python. Examples: Input : X = [[1, 7, 3], [3, 5, 6], [6, 8, 9]] Y = [[1, 1, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] Output : [55, 65, 49, 5] [57, 68, 72, 12] [90, 107, 111, 21]Using Simple Nested Loops: In this program we have to use nested for loops to iterat
4 min read
Program to multiply two matrices
Given two matrices, the task is to multiply them. Matrices can either be square or rectangular: Examples:  (Square Matrix Multiplication) Input: mat1[m][n] = { {1, 1}, {2, 2} }mat2[n][p] = { {1, 1}, {2, 2} }Output: result[m][p] = { {3, 3}, {6, 6} } (Rectangular Matrix Multiplication) Input: mat1[3][2] = { {1, 1}, {2, 2}, {3, 3} }mat2[2][3] = { {1,
14 min read
Javascript Program to multiply two matrices
Given two matrices, the task to multiply them. Matrices can either be square or rectangular. Example:  Input : mat1[][] = {{2, 4}, {1, 4}} mat2[][] = {{1, 4}, {1, 3}} Output : {{6, 16}, {7, 18}} Multiplication of Square Matrices : The below program multiplies two square matrices of size 4*4, we can change N for different dimensions. [GFGTABS] JavaS
3 min read
Find the intersection of two Matrices
Given two matrix A[][] and B[][] of same order m*n. The task is to find the intersection of both matrix as C, where: Cij = Aij if Aij = BijC = "*", otherwise. Examples: Input : A[N][N] = {{2, 4, 6, 8}, {1, 3, 5, 7}, {8, 6, 4, 2}, {7, 5, 3, 1}}; B[N][N] = {{0, 4, 3, 8}, {1, 3, 5, 7}, {8, 3, 6, 2}, {4, 5, 3, 4}}; Output : * 4 * 8 1 3 5 7 8 * * 2 * 5
6 min read
Check if it is possible to make two matrices strictly increasing by swapping corresponding values only
Given two n * m matrices A[][] and B[][], the task is to make both the matrices strictly increasing (both rows and columns) only by swapping two elements in different matrices if they are located in the corresponding position i.e. A[i][j] can only be swapped with B[i][j]. If possible then print Yes otherwise, No.Examples: Input: A[][] = {{2, 10}, B
7 min read
Check if the given two matrices are mirror images of one another
Given two matrices mat1[][] and mat2[][] of size NxN. The task is to find if the given two matrices are mirror images of one another. Print “Yes” if the given two matrices are mirror images, otherwise print “No”. Two matrices mat1 and mat2 of size N*N are said to be mirror images of one another if for any valid index (i, j) of the matrix: mat1[i][j
7 min read
Kronecker Product of two matrices
Given an m*n matrix A and a p*q matrix B, their Kronecker product C = A tensor B, also called their matrix direct product, is a (m*p) * (n*q) matrix. A tensor B = |a11B a12B| |a21B a22B| = |a11b11 a11b12 a12b11 a12b12| |a11b21 a11b22 a12b21 a12b22| |a11b31 a11b32 a12b31 a12b32| |a21b11 a21b12 a22b11 a22b12| |a21b21 a21b22 a22b21 a22b22| |a21b31 a21
10 min read
Count pairs from two sorted matrices with given sum
Given two sorted matrices mat1 and mat2 of size n x n of distinct elements. Given a value x. The problem is to count all pairs from both matrices whose sum is equal to x. Note: The pair has an element from each matrix. Matrices are strictly sorted which means that matrices are sorted in a way such that all elements in a row are sorted in increasing
15+ min read
Multiplication of two Matrices in Single line using Numpy in Python
Matrix multiplication is an operation that takes two matrices as input and produces single matrix by multiplying rows of the first matrix to the column of the second matrix.In matrix multiplication make sure that the number of columns of the first matrix should be equal to the number of rows of the second matrix. Example: Multiplication of two matr
3 min read
Program for subtraction of matrices
The below program subtracts of two square matrices of size 4*4, we can change N for a different dimension. Implementation: C/C++ Code // C++ program for subtraction of matrices #include &lt;bits/stdc++.h&gt; using namespace std; #define N 4 // This function subtracts B[][] from A[][], and stores // the result in C[][] void subtract(int A[][N], int
7 min read
Java Program to Add Two Matrix Using Iterative Approach
Given two matrices A and B, Add two matrices using iterative approaches in Java, like for loop, while loop, do-while loop. For the addition of two matrices, the necessary condition is that both the matrices must have the same size, and addition must take complete iteration to both the matrices. Examples Input: A[][] = {{1, 3}, {2, 4}} B[][] = {{1,
2 min read
Java Program to Add two Complex Numbers
Complex numbers are numbers that consist of two parts — a real number and an imaginary number. Complex numbers are the building blocks of more intricate math, such as algebra. The standard format for complex numbers is a + bi, with the real number first and the imaginary number last. General form for any complex number is: a+ib Where "a" is real nu
3 min read
Java Program to Add Two Binary Strings
When two binary strings are added, then the sum returned is also a binary string. Example: Input : x = "10", y = "01" Output: "11"Input : x = "110", y = "011" Output: "1001" Explanation: 110 + 011 =1001Approach 1: Here, we need to start adding from the right side and when the sum returned is more than one then store the carry for the next digits. L
3 min read
Java Program to Add Two numbers Without using Arithmetic Operator
Here, we need to write a function that returns the sum of two stated integers. And the function must not utilize any of the arithmetic operators such as +, ++, –, -, .. Etc.). It will be a very basic elementary level program to compute the sum by simply using the '+' operator and thereby simply printing and displaying out the resultant. But if we r
2 min read
Java Program To Add Two Numbers Represented By Linked Lists- Set 1
Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers. Example: Input: List1: 5->6->3 // represents number 563 List2: 8->4->2 // represents number 842 Output: Resultant list: 1->4->0->5 // represents number 1405 Explanation: 563 + 842 = 1405
4 min read
Java Program to Add Two Numbers
Given two integers num1 and num2, the task is to find the sum of the given two numbers in Java. Example of Addition of Two Numbers Input: A = 5, B = 6Output: sum = 11 Input: A = 4, B = 11 Output: sum = 15   Program to Add Two Numbers in Java Below is the implementation of adding two Numbers are mentioned below: Java Code // Java Program to implemen
4 min read
Add two integers of different base and represent sum in smaller base of the two
Given two integers X, Y in base B1 and B2 respectively, the task is to find the sum of integers X and Y and represent the result in min of ( B1 and B2 ). Example: Input: X = 123, Y = 234, B1 = 6, B2 = 8 Output: 543 Explanation: Integer in base 10: 51 and 156 Sum of Integers: 207 Minimum Base: 6 Sum of Integer in Base 6 = 543 Input: X = 16, Y = 24,
15+ min read
Add two numbers represented by two arrays
Given two array A[0....n-1] and B[0....m-1] of size n and m respectively, representing two numbers such that every element of arrays represent a digit. For example, A[] = { 1, 2, 3} and B[] = { 2, 1, 4 } represent 123 and 214 respectively. The task is to find the sum of both the number. In above case, answer is 337. Examples : Input : n = 3, m = 3
15+ min read
Practice Tags :