In this post, we will learn how to add two (2D arrays) matrices and print them in the form of a single Matrix of the same size. Before moving directly to the program, let's first understand how this addition of two matrices happened and what the conditions record required for this operation.
Note: A matrix can be used for addition or subtraction with another matrix only if both matrices have the same dimensions which means that both matrices should have an equal number of rows and the equal number of columns. (alert-success)
Example:
![]() |
Matrix Addition |
Below is the C++ Code Implementation:
Output:
//C++ Program to for Addition of 2D Array (Matrix) #include<iostream> using namespace std; int main(){ int arr1[50][50], arr2[50][50], sum[50][50]; int row, col; cout<<"Enter number of rows: "; cin>>row; cout<<"Enter number of column: "; cin>>col; //Taking input for first matrix cout<<"Enter the elements of first Array: "<<endl; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ cout<<"Enter element for position arr["<<i<<"]["<<j<<"] = "; cin>>arr1[i][j]; } } //Taking input for second matrix cout<<"Enter the elements of second Array: "<<endl; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ cout<<"Enter element for position arr["<<i<<"]["<<j<<"] = "; cin>>arr2[i][j]; } }
//Addition of Matrix for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ sum[i][j] = arr1[i][j] + arr2[i][j]; } } cout<<"Displaying Sum of Two Matrix: "<<endl; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ cout<<sum[i][j]<<" "; } cout<<endl; } return 0; }
Enter number of rows: 3
Enter number of column: 3
Enter the elements of first Array:
Enter element for position arr[0][0] = 2
Enter element for position arr[0][1] = 3
Enter element for position arr[0][2] = 6
Enter element for position arr[1][0] = 1
Enter element for position arr[1][1] = 4
Enter element for position arr[1][2] = 1
Enter element for position arr[2][0] = 9
Enter element for position arr[2][1] = 2
Enter element for position arr[2][2] = 5
Enter the elements of second Array:
Enter element for position arr[0][0] = 1
Enter element for position arr[0][1] = 2
Enter element for position arr[0][2] = 3
Enter element for position arr[1][0] = 4
Enter element for position arr[1][1] = 5
Enter element for position arr[1][2] = 6
Enter element for position arr[2][0] = 7
Enter element for position arr[2][1] = 8
Enter element for position arr[2][2] = 9
Displaying Sum of Two Matrix:
3 5 9
5 9 7
16 10 14
In the above code, we have taken two 3x3 matrices for addition, and after adding we have stored our result in a sum matrix which is of the same 3x3 size.
In the same way, you can write a program for the subtraction of two matrices, you just need to change the arithmetic operation from addition to subtraction and everything else will remain the same as it is.
Next:
No comments:
Post a Comment