Given two arrays A and B, use the iteration method in Java (such as for loop, while loop, do-while loop) to add two arrays. For the summation of two matrices, the necessary condition is that the sizes of the two matrices must be the same, and the summation must perform a complete iteration on the two 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
Below is the implementation of the above approach:
// 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)