
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Two Matrix Using Multi-Dimensional Arrays in C++
A matrix is a rectangular array of numbers that is arranged in the form of rows and columns.
An example of a matrix is as follows.
A 4*3 matrix has 4 rows and 3 columns as shown below −
3 5 1 7 1 9 3 9 4 1 6 7
A program that adds two matrices using multidimensional arrays is as follows.
Example
#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
In the above program, first the two matrices a and b are defined. This is shown as follows.
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; }
The two matrices are added using a nested for loop and the result is stored in matrix sum[][]. This is shown in the following code snippet.
for(i=0;i<r;++i) for(j=0;j<c;++j) sum[i][j]=a[i][j]+b[i][j];
After the sum of the two matrices is obtained, it is printed on screen. This is done as follows −
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; }
Advertisements