Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 1: Write a C++ program to calculate and print the product of two matrices.

#include<iostream>
using namespace std;

class MATRIX
{
	int row,col;
	public:
		int **a;
		MATRIX(int m,int n)
		{
			a=new int*[m];
			for(int i=0;i<m;i++)
			{
				a[i]=new int[n];
			}	
			row=m;
			col=n;
		}

		int get_row()
		{
			return row;
		}

		int get_col()
		{
			return col;
		}

		void initialization()
		{
			for(int i=0;i<row;i++)
			{
				for(int j=0;j<col;j++)
				{
					cin>>a[i][j];
				}
			}
		}

		void print()
		{
			for(int i=0;i<row;i++)
			{
				for(int j=0;j<col;j++)
				{
					cout<<a[i][j]<<"\t";
				}
				cout<<endl;
			}
		}

		void multiplication(MATRIX a1,MATRIX a2,int m)
		{
			for(int i=0;i<row;i++)
			{
				for(int j=0;j<col;j++)
				{
					for(int k=0;k<m;k++)
					{
						a[i][j]+=a1.a[i][k]*a2.a[k][j];	
					}
				}
			}
		}
};

int main()
{
	int m,n;
	cout<<"\nenter the no. of rows and columns of matrix a1 : ";
	cin>>m>>n;
	MATRIX a1(m,n);
	cout<<"\nenter the elements of array a1 : ";
	a1.initialization();
	cout<<"entered matrix is : \n";
	a1.print();
	int flag=0;

	while(flag==0)
	{
		cout<<"\nenter the no. of rows and columns of matrix a2 : ";
		cin>>m>>n;
		if(m!=a1.get_col())
		{
			cout<<"\nno. of rows of 2nd array must be equal to the no. of col.s of array 1st ";
		}
		else
			flag=1;	
	}

	MATRIX a2(m,n),a3(a1.get_row(),a2.get_col());
	cout<<"\nenter the elements of array a2 : ";
	a2.initialization();
	cout<<"entered matrix is : \n";
	a2.print();
	cout<<"\nmultiplication of two matrices is : \n";
	a3.multiplication(a1,a2,a1.get_col());
	a3.print();
	return 0;
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.