Skip to content

Instantly share code, notes, and snippets.

@complxalgorithm
Created May 7, 2016 22:48
Show Gist options
  • Save complxalgorithm/489f242550e3b3e57b8ade8548f4d893 to your computer and use it in GitHub Desktop.
Save complxalgorithm/489f242550e3b3e57b8ade8548f4d893 to your computer and use it in GitHub Desktop.
Uses a Matrix class to show a way to add, subtract, and multiply square matrices.
#include<iostream>
#include<conio.h>
#include<iomanip>
using namespace std;
const int ROW = 5;
const int COL = 5;
class matrix
{
int a[ROW][COL];
int row;
int col;
public:
matrix() : row(0), col(0)
{}
void read(int r, int c, matrix m1, matrix m2);
void display();
matrix add(matrix m1, matrix m2);
matrix subtract(matrix m1, matrix m2);
matrix multiply(matrix m1, matrix m2);
};
void matrix::read(int r, int c, matrix m1, matrix m2)
{
row = r;
col = c;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
cout << "A[" << i << "][" << j << "] : ";
cin >> a[i][j];
}
}
for (int i = 0; i < m1.row; i++)
{
for (int j = 0; j < m2.col; j++)
{
if (m1.a[i][j] != m2.a[i][j])
{
cout << "These matrices are not squares.\n"
<< "Please run the program again.\n";
break;
}
}
}
}
void matrix::display()
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
cout << setw(4) << a[i][j];
cout << endl;
}
}
matrix matrix::add(matrix m1, matrix m2)
{
matrix temp;
temp.row = m1.row;
temp.col = m2.col;
for (int i = 0; i < temp.row; i++)
{
for (int j = 0; j < temp.col; j++)
{
temp.a[i][j] = m1.a[i][j] + m2.a[i][j];
}
}
return temp;
}
matrix matrix::subtract(matrix m1, matrix m2)
{
matrix temp;
temp.row = m1.row;
temp.col = m2.col;
for (int i = 0; i < temp.row; i++)
{
for (int j = 0; j < temp.col; j++)
{
temp.a[i][j] = m1.a[i][j] - m2.a[i][j];
}
}
return temp;
}
matrix matrix::multiply(matrix m1, matrix m2)
{
matrix temp;
temp.row = m1.row;
temp.col = m2.col;
for (int i = 0; i < temp.row; i++)
{
for (int j = 0; j < temp.col; j++)
{
for (int k = 0; k < temp.col; k++)
{
temp.a[i][j] = 0;
temp.a[i][j] = temp.a[i][j] + (m1.a[i][k] * m2.a[k][j]);
}
}
}
return temp;
}
int main()
{
matrix m1, m2, m3, m4, m5, m6, m7, m8;
int r1, c1;
cout << "Enter the order of first matrix: ";
cin >> r1 >> c1;
int r2, c2;
cout << "Enter the order of second matrix: ";
cin >> r2 >> c2;
if (r1 != r2 && c1 != c2)
{
cout << "This matrix is not a square.\n"
<< "Please try again.\n";
}
else
{
cout << "Enter elements of first matrix:\n";
m1.read(r1, c1, m1, m2);
cout << "Enter elements of second matrix:\n";
m2.read(r2, c2, m1, m2);
m4 = m3.add(m1, m2);
cout << "Added matrix is:\n";
m4.display();
m6 = m5.subtract(m1, m2);
cout << "Subtracted matrix is:\n";
m6.display();
m8 = m7.multiply(m1, m2);
cout << "Resultant matrix is:\n";
m8.display();
}
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment