//Write a C++ program using the concept of OOP for the multiplication of two square Matrices
#include <iostream>
// Matrix class
class Matrix
{
private:
int size;
int** data;
public:
// Constructor that takes the size of the matrix as a parameter and creates a matrix with the given size
Matrix(int size) : size(size)
{
// Allocate memory for the matrix
data = new int*[size];
for (int i = 0; i < size; i++)
data[i] = new int[size];
}
// Destructor that frees the memory allocated for the matrix
~Matrix()
{
for (int i = 0; i < size; i++)
delete[] data[i];
delete[] data;
}
// Function to fill the matrix with values
void fill(int value)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
data[i][j] = value;
}
// Function to print the matrix
void print()
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
std::cout << data[i][j] << " ";
std::cout << std::endl;
}
}
// Function to multiply the matrix by another matrix
Matrix operator*(Matrix& other)
{
Matrix result(size);
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
for (int k = 0; k < size; k++)
result.data[i][j] += data[i][k] * other.data[k][j];
return result;
}
};
int main()
{
// Create two matrices with 3 rows and 3 columns
Matrix matrix1(3);
Matrix matrix2(3);
// Fill the matrices with the values 1, 2, 3, 4, 5, 6, 7, 8, 9
matrix1.fill(1);
matrix2.fill(2);
// Print the matrices
std::cout << "Matrix 1:" << std::endl;
matrix1.print();
std::cout << "Matrix 2:" << std::endl;
matrix2.print();
// Multiply the matrices
Matrix result = matrix1 * matrix2;
// Print the result
std::cout << "Result:" << std::endl;
result.print();
return 0;
}
/*
==========Output===========
Matrix 1:
1 1 1
1 1 1
1 1 1
Matrix 2:
2 2 2
2 2 2
2 2 2
Result:
6 6 6
6 6 6
6 6 6
*/
No comments:
Post a Comment