Java Program to find Matrix Addition

You are Here:

Find Matrix Addition

In the following example, we will add the two given matrices (two-dimensional arrays).

Example

Java Compiler
public class myClass { public static void main(String[] args) { int i, j; int[][] arr1 = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1} }; int[][] arr2 = { {2, 2, 2}, {2, 2, 2}, {2, 2, 2} }; int[][] arr3 = new int[3][3]; System.out.println("Matrix A (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) System.out.format("%d ", arr1[i][j]); System.out.println(); } System.out.println("\nMatrix B (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) System.out.format("%d ", arr2[i][j]); System.out.println(""); } System.out.println("\nMatrix Additon (A + B):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { arr3[i][j] = arr1[i][j] + arr2[i][j]; System.out.format("%d ", arr3[i][j]); } System.out.println(); } } }

Output

Matrix A (3 x 3): 1 1 1 1 1 1 1 1 1 Matrix B (3 x 3): 2 2 2 2 2 2 2 2 2 Matrix Additon (A + B): 3 3 3 3 3 3 3 3 3

In the following example, we will get the values for (3 x 3) Matrices A and B from the user and display the matrix addition.

Example

Java Compiler
import java.util.Scanner; public class myClass { public static void main(String[] args) { int i, j; int[][] arr1 = new int[3][3]; int[][] arr2 = new int[3][3]; int[][] arr3 = new int[3][3]; Scanner reader = new Scanner(System.in); System.out.println("Enter Matrix A (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) arr1[i][j] = reader.nextInt(); } System.out.println("Enter Matrix B (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) arr2[i][j] = reader.nextInt(); } System.out.println("\nMatrix Additon (A + B):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { arr3[i][j] = arr1[i][j] + arr2[i][j]; System.out.format("%d ", arr3[i][j]); } System.out.println(); } } }

Output

Enter Matrix A (3 x 3): 2 2 2 2 2 2 2 2 2 Enter Matrix B (3 x 3): 4 4 4 4 4 4 4 4 4 Matrix Additon (A + B): 6 6 6 6 6 6 6 6 6

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Java with examples for quick and easy learning.

We are working to cover every Single Concept in Java.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author