Java Program to Add Two Matrix Using Iterative Approach
Last Updated :
29 Oct, 2020
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
import java.io.*;
class Main {
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();
}
}
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];
}
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 " );
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...