In this post, you will learn how to Add Two Matrices Using Multi-dimensional Arrays using C++.
This lesson will teach you how to Add Two Matrices Using Multi-dimensional Arrays, using mathematical function, and the for loop statement using the C++ Language. Let’s look at the below source code.
How to Add Two Matrices Using Multi-dimensional Arrays?
RUN CODE SNIPPETSource Code
#include <iostream> using namespace std; int main() { int r=2, c=4, sum[2][4], i, j; int a[2][4] = {{1,5,9,4} , {3,2,8,3}}; int b[2][4] = {{6,3,8,2} , {1,5,2,9}}; cout<<"The first matrix is: "<<endl; for(i=0; i<r; ++i) { for(j=0; j<c; ++j) cout<<a[i][j]<<" "; cout<<endl; } cout<<endl; cout<<"The second matrix is: "<<endl; for(i=0; i<r; ++i) { for(j=0; j<c; ++j) cout<<b[i][j]<<" "; cout<<endl; } cout<<endl; for(i=0;i<r;++i) for(j=0;j<c;++j) sum[i][j]=a[i][j]+b[i][j]; cout<<"Sum of the two matrices is:"<<endl; for(i=0; i<r; ++i) { for(j=0; j<c; ++j) cout<<sum[i][j]<<" "; cout<<endl; } return 0; }
Output
The first matrix is: 1 5 9 4 3 2 8 3 The second matrix is: 6 3 8 2 1 5 2 9 Sum of the two matrices is: 7 8 17 6 4 7 10 12
The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code.
Now we can look into the working and layout of the code’s function.
- Initialize the variables r, c, sum, i, j, a, b as integers and assign the variables r and c with the values to be calculated and declare the variables sum, a and b as arrays.
- Assign the values for the arrays a and b using the curly braces { }. Using the output function cout display the first array.
- Declare a for loop with the condition
(i=0; i<r; ++i)
and in the body of the loop declare another for loop with the condition(j=0; j<c; ++j)
with the output statement to display the array a. - The above nested for loop is used to display the first array. This is followed by a similar section of code to display the second array.
- Next declare two for loops to verify the values in the array, and insert the following mathematical function to find the sum of the two arrays
sum[i][j]=a[i][j]+b[i][j]
. - Using the for loop and the cout function display the sum of the two arrays as the answer.
- In each nested for loop the first condition verifies the size of the loop, that is it checks the size of the row and the column, where the assigned size of the row and the column must be similar to the size of the row and column of the arrays and the second condition verifies the elements in the array.