Program To Add Two Matrices Using For Loop In Java

LEVEL: Beginner

Whats in this post?

1. Code
2. Output
3. Background and Explanation of the code

Code


To copy code: Click View Source “View Source” on the right of this code snippet.

Background and Explanation of the code


This program calculates the sum of two matrices containing its rows and columns.The matrix values are predefined in the program. For implementing the two matrices in this program, two dimensional arrays of type integer has been declared. The program calculates the length of both the arrays and then using nested for loops, the sum of the two arrays is calculated. The output is hence displayed using the println() method.

Output
run:
Number of Row= 2
Number of Column= 7

Matrix 1 :

4 5 6 2 3 4 5
6 8 9 1 2 4 5

Matrix 2 :

5 4 6 3 4 5 2
5 6 7 3 4 5 7

Addition of both matrix :

9 9 12 5 7 9 7
11 14 16 4 6 9 12