Open In App

Java Program to Add Two Matrix Using Iterative Approach

Improve
Improve
Like Article
Like
Save
Share
Report

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, 1}, 
                {1, 1}}
Output: {{2, 4}, 
         {3, 5}}

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

Iterative 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 to Add Two 
// Matrix Using Iterative Approach
import java.io.*;
class Main {
    
    // Print matrix using iterative approach
    public static void printMatrix(int[][] a)
    {
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[0].length; j++)
                System.out.print(a[i][j] + " ");
            System.out.println();
        }
    }
    // Sum of two matrices using Iterative approach
    public static void matrixAddition(int[][] a, int[][] b)
    {
        int[][] sum = new int[a.length][a[0].length];
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[0].length; j++)
                sum[i][j] = a[i][j] + b[i][j];
        }
        
        // printing the matrix
        printMatrix(sum);
    }
    public static void main(String[] args)
    {
        int[][] firstMat = { { 1, 3 }, { 2, 4 } };
        int[][] secondMat = { { 1, 1 }, { 1, 1 } };
        System.out.println("The sum is ");
  
        // calling the function
        matrixAddition(firstMat, secondMat);
    }
}


Output

The sum is 
2 4 
3 5 

Time Complexity: O(n*m), where N X M is the dimension of the matrix.

Space Complexity:- O(n*m)



Last Updated : 29 Oct, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads