Skip to content Skip to footer

Write java program to find sum of two matrices. Define appropriate class, constructor and methods in your program. Make necessary assumptions.

class Matrix {
private int[][] data;
private int rows;
private int cols;

// Constructor
public Matrix(int[][] data) {
    this.data = data;
    this.rows = data.length;
    this.cols = data[0].length;
}

// Method to add two matrices
public Matrix add(Matrix other) {
    if (this.rows != other.rows || this.cols != other.cols) {
        System.out.println("Matrices should have the same dimensions for addition.");
        return null;
    }

    int[][] resultData = new int[rows][cols];
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            resultData[i][j] = this.data[i][j] + other.data[i][j];
        }
    }
    return new Matrix(resultData);
}

// Method to display the matrix
public void display() {
    for (int[] row : data) {
        for (int cell : row) {
            System.out.print(cell + " ");
        }
        System.out.println();
    }
}

}

public class Main {
public static void main(String[] args) {
// Define matrices
int[][] data1 = { {1, 2, 3}, {4, 5, 6} };
int[][] data2 = { {7, 8, 9}, {10, 11, 12} };

    Matrix matrix1 = new Matrix(data1);
    Matrix matrix2 = new Matrix(data2);

    // Display original matrices
    System.out.println("Matrix 1:");
    matrix1.display();
    System.out.println("\nMatrix 2:");
    matrix2.display();

    // Add matrices and display result
    Matrix sum = matrix1.add(matrix2);
    if (sum != null) {
        System.out.println("\nSum of the matrices:");
        sum.display();
    }
}

}

Leave a comment

Open chat
1
Scan the code
Prachar Bharat
Hello
How can we help you?