Java Program to perform addition of two matrix .
Objective
Write a Java program to perform the addition of two 3x3 matrices.
Algorithm / Approach
- Declare three 2D arrays (matrices) of size [3][3]:
m1,m2, andm3. - Use nested loops to read 9 integers into
m1, and another set of nested loops form2. - Use nested loops to add corresponding elements:
m3[i][j] = m1[i][j] + m2[i][j]. - Print the resulting
m3matrix in a grid format using spaces and newlines.
Matrix.java
import java.util.Scanner;
class Matrix {
void add() {
Scanner s=new Scanner(System.in);
int m1[][] = new int[3][3];
int m2[][] = new int[3][3];
int m3[][] = new int[3][3];
System.out.println("Enter Elements of Mat1: ");
for(int i = 0; i< 3; i++) {
for(int j = 0; j< 3; j++) {
m1[i][j] = s.nextInt();
}
}
System.out.println("Enter Elements of Mat2: ");
for(int i = 0; i< 3; i++) {
for(int j = 0; j< 3; j++) {
m2[i][j] = s.nextInt();
}
}
System.out.println("Sum of the matrix: ");
for(int i = 0; i< 3; i++) {
for(int j = 0; j< 3; j++) {
m3[i][j] = m1[i][j]+m2[i][j];
System.out.print(m3[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] a)
{
Matrix m = new Matrix();
m.add();
}
}
Expected Output
Enter Elements of Mat1: 1 2 3 4 5 6 1 2 3 Enter Elements of Mat2: 1 3 3 1 2 3 1 3 2 Sum of the matrix: 2 5 6 5 7 9 2 5 5
Explanation of the Program
- A 2D array in Java is essentially an "array of arrays" and represents a mathematical matrix.
- Matrix addition is straightforward: you add the element at row 1, column 1 of the first matrix to row 1, column 1 of the second matrix, and so on.
- Nested
forloops are required to navigate the grid: the outer loop handles the rows, and the inner loop handles the columns within that row.
Complexity
Time Complexity
O(r * c) - Where r is rows and c is columns (O(N2) for square matrices).
Space Complexity
O(r * c) - To store the resulting matrix.