codescracker


c++

C++ Program to Multiply Two Matrices



« Previous Program Next Program »


Multiply Two Matrices in C++

To multiply two matrices in C++ programming, you have to ask to the user to enter the first and second matrix elements.Now start multiplying the two matrices and store the multiplication result inside any variable say sum and finally store the value of sum in the third matrix say mat3[ ][ ] as shown here in the following program.

C++ Programming Code to Multiply Two Matrices

Following C++ program ask to the user to enter the two 3*3 matrix elements, to multiply them to form a new matrix which is the multiplication result of the two entered 3*3 matrices, then display the result on the screen:

/* C++ Program - Multiply Two Matrices */
		
#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int mat1[3][3], mat2[3][3], mat3[3][3], sum=0, i, j, k;
	cout<<"Enter first matrix element (3*3) : ";
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			cin>>mat1[i][j];
		}
	}
	cout<<"Enter second matrix element (3*3) : ";
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			cin>>mat2[i][j];
		}
	}
	cout<<"Multiplying two matrices...\n";
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			sum=0;
			for(k=0; k<3; k++)
			{
				sum = sum + mat1[i][k] * mat2[k][j];
			}
			mat3[i][j] = sum;
		}
	}
	cout<<"\nMultiplication of two Matrices : \n";
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			cout<<mat3[i][j]<<" ";
		}
		cout<<"\n";
	}
	getch();
}

When the above C++ program is compile and executed, it will produce the following result:

C++ program multiply two matrices

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test