Java Online Compiler
Example: Matrix Addition in Java in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Matrix Addition in Java public class Main { // Method to add two matrices public static int[][] addMatrices(int[][] matrixA, int[][] matrixB) { // Step 1: Get dimensions of the matrices int rows = matrixA.length; int cols = matrixA[0].length; // Step 2: Create a result matrix with the same dimensions int[][] result = new int[rows][cols]; // Step 3: Iterate through each element and add corresponding values for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { result[i][j] = matrixA[i][j] + matrixB[i][j]; } } return result; } // Method to print a matrix public static void printMatrix(int[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } public static void main(String[] args) { // Step 1: Define two matrices for addition int[][] matrixA = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int[][] matrixB = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; System.out.println("Matrix A:"); printMatrix(matrixA); System.out.println("\nMatrix B:"); printMatrix(matrixB); // Step 2: Perform matrix addition // Ensure matrices have compatible dimensions (same rows and columns) if (matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { System.out.println("Matrices dimensions are not compatible for addition."); } else { int[][] sumMatrix = addMatrices(matrixA, matrixB); // Step 3: Print the result System.out.println("\nSum of Matrix A and Matrix B:"); printMatrix(sumMatrix); } } }
Output
Clear
ADVERTISEMENTS