- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to overload addition operator to add two matrices
Suppose we have two matrices mat1 and mat2. We shall have to add these two matrices and form the third matrix. We shall have to do this by overloading the addition operator.
So, if the input is like
5 | 8 |
9 | 6 |
7 | 9 |
8 | 3 |
4 | 7 |
6 | 3 |
then the output will be
13 | 11 |
13 | 13 |
13 | 12 |
To solve this, we will follow these steps −
Overload the addition operator, this will take another matrix mat as second argument
define one blank 2d array vv
Define one 2D array vv and load current matrix elements into it
for initialize i := 0, when i < size of vv, update (increase i by 1), do:
for initialize j := 0, when j < size of vv[0], update (increase j by 1), do:
- vv[i, j] := vv[i, j] + mat.a[i, j]
- return a new matrix using vv
Let us see the following implementation to get better understanding −
Example
#include <iostream> #include <vector> using namespace std; class Matrix { public: Matrix() {} Matrix(const Matrix& x) : a(x.a) {} Matrix(const vector<vector<int>>& v) : a(v) {} Matrix operator+(const Matrix&); vector<vector<int>> a; void display(){ for(int i = 0; i<a.size(); i++){ for(int j = 0; j<a[i].size(); j++){ cout << a[i][j] << " "; } cout << endl; } } }; Matrix Matrix::operator+(const Matrix& m){ vector<vector<int>> vv = a; for (int i=0; i<vv.size(); i++){ for (int j=0; j<vv[0].size(); j++){ vv[i][j] += m.a[i][j]; } } return Matrix(vv); } int main(){ vector<vector<int>> mat1 = {{5,8},{9,6},{7,9}}; vector<vector<int>> mat2 = {{8,3},{4,7},{6,3}}; int r = mat1.size(); int c = mat1[0].size(); Matrix m1(mat1), m2(mat2), res; res = m1 + m2; res.display(); }
Input
{{5,8},{9,6},{7,9}}, {{8,3},{4,7},{6,3}}
Output
13 11 13 13 13 12
- Related Articles
- C++ program to overload addition operator to add two complex numbers
- C# program to add two matrices
- C++ program to overload extraction operator
- Java program to add two matrices.
- How to write Java program to add two matrices
- C# program to multiply two matrices
- Program to multiply two matrices in C++
- How to Add Two Matrices using Python?
- C++ Program to Check Multiplicability of Two Matrices
- How to overload python ternary operator?
- Overload unary minus operator in C++?
- C# program to check if two matrices are identical
- Java program to subtract two matrices.
- Java program to multiply two matrices.
- Python program to multiply two matrices

Advertisements