You have to implement a matrix ADT using concepts of C++ classes taught in the lectures. The input matrices would be square matrices. Theclass must support the following functions:
1. Matrix Addition
2. Matrix Subtraction
3. Matrix Multiplication
Your program should take as input: dimension of a square matrix N, two matrices of size N x N with integer values, and one operator symbol (+, - ,*). It must perform the corresponding operation using member functions of Matrix class.
INPUT:
In the first line, one integer which is the dimension of the matrix and one operator (one of +, - or *)
Two NxN matrices one after the other, supplied one row at a time.
OUTPUT:
Resultant matrix after performing the specified operation, one row at a time. For subtraction, if A is the first matrix and B is the second matrix, perform A-B.
CONSTRAINTS:
The inputs will satisfy the following constraints:
1<=N<=10
1<=N<=10
There is no need to validate the value of N.
There are no constraints on the values of the entries of the matrices.#include <iostream> #include <cstring> using namespace std; struct matrixType{ int matDimension; int matValues[10][10]; }; class MatrixADT{ private: matrixType resultMatrix; public: void intializeResultMatrix(int); void add(matrixType, matrixType); void subtract(matrixType,matrixType); void multiply(matrixType,matrixType); void printResult(); }; void MatrixADT::add(matrixType M1, matrixType M2) { int i,j; for(i=0;i<resultMatrix.matDimension;i++) { for(j=0;j<resultMatrix.matDimension;j++) { resultMatrix.matValues[i][j] = M1.matValues[i][j] + M2.matValues[i][j]; } } } void MatrixADT::subtract(matrixType M1, matrixType M2) { int i,j; for(i=0;i<resultMatrix.matDimension;i++) { for(j=0;j<resultMatrix.matDimension;j++) { resultMatrix.matValues[i][j] = M1.matValues[i][j] - M2.matValues[i][j]; } } } void MatrixADT::multiply(matrixType M1, matrixType M2) { int i,j,k; for(i=0;i<resultMatrix.matDimension;i++) { for(j=0;j<resultMatrix.matDimension;j++) { for(k=0;k<resultMatrix.matDimension;k++) resultMatrix.matValues[i][j] += M1.matValues[i][k] * M2.matValues[k][j]; } } } void MatrixADT::intializeResultMatrix(int dim) { int i,j; resultMatrix.matDimension=dim; for(i=0;i<dim;i++) { for(j=0;j<dim;j++) { resultMatrix.matValues[i][j]=0; } } } int main(){ MatrixADT maX; matrixType M1, M2; char op; int dim,i,j; cin>>dim>>op; maX.intializeResultMatrix(dim); for(i=0;i<dim;i++) for(j=0;j<dim;j++) cin>>M1.matValues[i][j]; for(i=0;i<dim;i++) for(j=0;j<dim;j++) cin>>M2.matValues[i][j]; if(op=='+') maX.add(M1,M2); if(op=='-') maX.subtract(M1,M2); if(op=='*') maX.multiply(M1,M2); maX.printResult(); } void MatrixADT::printResult(){ int i,j; for (i=0;i<resultMatrix.matDimension;i++){ for (j=0; j<resultMatrix.matDimension-1;j++){ cout<<resultMatrix.matValues[i][j]<<" "; } cout <<resultMatrix.matValues[i][j]<<"\n"; } cout <<"Done"; }
No comments:
Post a Comment