using namespace std;
int main()
{
int matrix1[3][3]; int matrix2[3][3];
int sparse1[10][3]; int sparse2[10][3]; int result[10][3];
int k1 = 0; int k2 = 0; int k3 = 0;
// Input Matrix 1
cout << "Enter first 3 x 3 matrix:" << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cin >> matrix1[i][j];
}
}
// Input Matrix 2
cout << "Enter second 3 x 3 matrix:" << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cin >> matrix2[i][j];
}
}
// Convert Matrix 1 into Sparse Matrix
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (matrix1[i][j] != 0)
{
sparse1[k1][0] = i; // Row
sparse1[k1][1] = j; // Column
sparse1[k1][2] = matrix1[i][j]; // Value
k1++;
}
}
}
// Convert Matrix 2 into Sparse Matrix
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (matrix2[i][j] != 0)
{
sparse2[k2][0] = i; // Row
sparse2[k2][1] = j; // Column
sparse2[k2][2] = matrix2[i][j]; // Value
k2++;
}
}
}
// Add two sparse matrices
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
int value = matrix1[i][j] + matrix2[i][j];
if (value != 0)
{
result[k3][0] = i; // Row
result[k3][1] = j; // Column
result[k3][2] = value; // Value
k3++;
}
}
}
// Display Sparse Matrix 1
cout << "\nSparse Matrix 1:" << endl;
cout << "Row\tColumn\tValue" << endl;
for (int i = 0; i < k1; i++)
{
cout << sparse1[i][0] << "\t"
<< sparse1[i][1] << "\t"
<< sparse1[i][2] << endl;
}
// Display Sparse Matrix 2
cout << "\nSparse Matrix 2:" << endl;
cout << "Row\tColumn\tValue" << endl;
for (int i = 0; i < k2; i++)
{
cout << sparse2[i][0] << "\t"
<< sparse2[i][1] << "\t"
<< sparse2[i][2] << endl;
}
// Display Result
cout << "\nAddition of Two Sparse Matrices:" << endl;
cout << "Row\tColumn\tValue" << endl;
for (int i = 0; i < k3; i++)
{
cout << result[i][0] << "\t"
<< result[i][1] << "\t"
<< result[i][2] << endl;
}
return 0;
}