Javatpoint Logo
Javatpoint Logo

Program to calculate the addition of 2 matrices

Explanation

In this program, we need to add two matrices and print the resulting matrix.

Matrix:

Matrix is a rectangular two-dimensional array of numbers arranged in rows and columns. A matrix with m rows and n columns can be called as m n matrix. Individual entries in the matrix are called element and can be represented by aij which suggests that the element a is present in the ith row and jth column.

Program to calculate the addition of 2 matrices

Addition of two matrices:

Two matrices A and B can be added if and only if they have same dimensions that are, the same number of rows and columns. It is not possible to add a 2 3 matrix with a 3 2 matrix. Addition of two matrices can be performed by adding their corresponding elements as

(A + B)ij= Aij + Bij
Program to calculate the addition of 2 matrices

Addition of two matrices can be performed by looping through the first and second matrix. Add the corresponding elements of both matrices and store the result in the third matrix.

Algorithm

  1. Declare and initialize 2 two-dimensional arrays a and b.
  2. Calculate the number of rows and columns present in the array a (as dimensions of both the arrays are same) and store it in variables rows and cols respectively.
  3. Declare another array sum with the similar dimensions.
  4. Loop through the arrays a and b, add the corresponding elements
    e.g a11 + b11 = sum11
  5. Display the elements of array sum.

Solution

Python

Output:

Addition of two matrices: 
2 1 2 

6 8 7 

2 7 4 

C

Output:

Addition of two matrices: 
2 1 2 
6 8 7 
2 7 4  

JAVA

Output:

Addition of two matrices: 
2 1 2 
6 8 7 
2 7 4

C#

Output:

Addition of two matrices: 
2 1 2 
6 8 7 
2 7 4

PHP

Output:

Addition of two matrices: 
2 1 2 
6 8 7 
2 7 4

Next Topic#





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA