0% found this document useful (0 votes)
2 views3 pages

5 - Matrix Class Using Class Templates

The document presents a C++ program that implements a Matrix class using templates for object-oriented programming. It includes methods for reading, displaying, adding, subtracting, and multiplying matrices. The main function demonstrates the usage of the Matrix class with both integer and float types.

Uploaded by

sasikumarmc67
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

5 - Matrix Class Using Class Templates

The document presents a C++ program that implements a Matrix class using templates for object-oriented programming. It includes methods for reading, displaying, adding, subtracting, and multiplying matrices. The main function demonstrates the usage of the Matrix class with both integer and float types.

Uploaded by

sasikumarmc67
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

19CSE201- Advanced Programming

Object Oriented Programming- Matrices using Classes in C++

#include <iostream>
using namespace std;

template <class T>


class Matrix{
private:
int rows;
int columns;
T** data;
public:
Matrix(int r, int c): rows(r),columns(c){
data= new T*[rows];
for(int i=0;i<rows;i++){
data[i]= new T[columns];
for(int j=0;j<columns;j++){
data[i][j]=0;
}
}
}

~Matrix(){
for(int i=0;i<rows;i++){
delete [] data[i];
}
}

void read(){
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
cin>>data[i][j];
}
}
}

void display(){
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
cout<<data[i][j]<<"\t";
}
cout<<endl;
}
}

void add (const Matrix &m1){


Matrix m2(rows,columns);
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
[Link][i][j]=data[i][j]+[Link][i][j];
}
}
[Link]();
}

void sub (const Matrix &m1){


Matrix m2(rows,columns);
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
[Link][i][j]=data[i][j]-[Link][i][j];
}
}
[Link]();
}

void mult (const Matrix &m1){


Matrix m2(rows,columns);
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
for(int k=0;k<columns;k++){
[Link][i][j]+=data[i][k]*[Link][k][j];
}
}
}
[Link]();
}

};

int main() {
Matrix<int> m1(2,2);
Matrix<int> m2(2,2);
[Link]();
cout<<"M1= \n";
[Link]();
[Link]();
cout<<"M2= \n";
[Link]();
cout<<"M1+M2= \n";
[Link](m2);
cout<<"M1-M2= \n";
[Link](m2);
cout<<"M1*M2= \n";
[Link](m2);

Matrix<float> m3(2,2);
Matrix<float> m4(2,2);
[Link]();
cout<<"M3= \n";
[Link]();
[Link]();
cout<<"M4= \n";
[Link]();
cout<<"M3+M4= \n";
[Link](m4);
cout<<"M3-M4= \n";
[Link](m4);
cout<<"M3*M4= \n";
[Link](m4);
return 0;

You might also like