Javatpoint Logo
Javatpoint Logo
\

Add Two Matrix in C++

In C++, a matrix is a two-dimensional array consisting of rows and columns of elements. It can be created using various methods, such as using nested for loops or by dynamically allocating memory. One way to create a matrix in C++ is to declare a two-dimensional array using the following syntax:

Here, dataType is the data type of the elements in the matrix, matrixName is the name given to the matrix, rowSize is the number of rows in the matrix, and columnSize is the number of columns in the matrix. For example, to create a matrix with 3 rows and 4 columns of integer elements, we can use the following code:

This creates a matrix named matrix with 3 rows and 4 columns, where each element is initialized to 0 by default. Another way to create a matrix in C++ is to dynamically allocate memory using the new operator. This method is useful when the size of the matrix is not known at compile time and needs to be determined at runtime. To dynamically create a matrix, we first declare a pointer to a two-dimensional array using the following syntax:

Here, dataType is the data type of the elements in the matrix, and matrixName is the name given to the matrix pointer. Next, we allocate memory for the rows of the matrix using the new operator:

This creates an array of rowSize pointers to dataType arrays, where each dataType array represents a row in the matrix. Finally, we allocate memory for the columns of each row using another new operator:

This creates a columnSize-element array of dataType for each row in the matrix, effectively creating the entire matrix. For example, to create a matrix with 3 rows and 4 columns of double elements using dynamic memory allocation, we can use the following code:

This creates a matrix named matrix with 3 rows and 4 columns, where each element is initialized to 0.0 by default. In conclusion, matrices can be created in C++ using two-dimensional arrays or by dynamically allocating memory. The choice of method depends on the size of the matrix and whether it is known at compile time or needs to be determined at runtime. Both methods allow for the efficient storage and manipulation of large amounts of data in a structured manner, making them an essential tool for many programming applications.

C++ Code

Output

Matrix 1:
1 2 3
4 5 6
Matrix 2:
7 8 9
10 11 12
Result:
8 10 12
14 16 18

Explanation:

In this code, the addMatrices function takes two matrices as input (mat1 and mat2) and calculates their sum element-wise, storing the result in the result matrix. The matrices are passed to the function as 2D arrays, with their dimensions specified using the const keyword.







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