From 2efe4c7e3d5b38c71e76e1e8860586f792cb0bc9 Mon Sep 17 00:00:00 2001 From: rajan98 Date: Wed, 4 Oct 2023 21:37:14 +0530 Subject: [PATCH] Added code for MatrixAddition --- Programs/matrix/MatrixAddition.java | 49 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 Programs/matrix/MatrixAddition.java diff --git a/Programs/matrix/MatrixAddition.java b/Programs/matrix/MatrixAddition.java new file mode 100644 index 0000000..2cfc4c3 --- /dev/null +++ b/Programs/matrix/MatrixAddition.java @@ -0,0 +1,49 @@ +public class MatrixAddition { + public static void main(String[] args) { + int[][] matrixA = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + + int[][] matrixB = { + {9, 8, 7}, + {6, 5, 4}, + {3, 2, 1} + }; + + int rows = matrixA.length; + int cols = matrixA[0].length; + + int[][] resultMatrix = new int[rows][cols]; + + // Perform matrix addition + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + resultMatrix[i][j] = matrixA[i][j] + matrixB[i][j]; + } + } + + // Display the result + System.out.println("Matrix A:"); + printMatrix(matrixA); + + System.out.println("\nMatrix B:"); + printMatrix(matrixB); + + System.out.println("\nMatrix A + Matrix B:"); + printMatrix(resultMatrix); + } + + public static void printMatrix(int[][] matrix) { + int rows = matrix.length; + int cols = matrix[0].length; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + } +} diff --git a/README.md b/README.md index cb3d676..fe13b70 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,7 @@ It is very easy to contribute, you may follow these steps - 99.[RotateLinkedList](https://github.com/PrajaktaSathe/Java/blob/main/Programs/RotateLinkedList.java)-Program to demo rotating a linked list 100. [ReverseString](https://github.com/PrajaktaSathe/Java/blob/main/ReverseString.java) -Program to reverse a String using the java method substring. 101.[Overriding](https://github.com/PrajaktaSathe/Java/blob/main/Programs/Overriding.java)-Program to demo overriding in java +102. [MatrixAddition](https://github.com/PrajaktaSathe/Java/blob/main/Programs/matrix/MatrixAddition.java) - Perform element-wise addition between two matrices of the same dimensions. # Contributors - ## A big thank you to all our contributors!!!