1.Write a C++ program that accepts two 4X4 matrices, and calculates:
A.Sum of the matrices
B.Product of the matrices
Define your functions to do the tasks.
#include <iostream>
using namespace std;
void multiplyMatrix(){
int arr[10][10], brr[10][10], multip[10][10], x1, y1, x2, y2, i, j, k;
cout << "Put number of rows and columns for the first matrix: ";
cin >> x1 >> y1;
cout << "Put the number rows and columns for the second matrix: ";
cin >> x2 >> y2;
cout << endl << "Enter items of the first matrix :" << endl;
for(i = 0; i < x1; ++i)
for(j = 0; j < y1; ++j)
{
cout << "Enter items a" << i + 1 << j + 1 << " : ";
cin >> arr[i][j];
}
cout << endl << "Enter items of the second matrix :" << endl;
for(i = 0; i < x2; ++i)
for(j = 0; j < y2; ++j)
{
cout << "Enter item b" << i + 1 << j + 1 << " : ";
cin >> brr[i][j];
}
for(i = 0; i < x1; ++i)
for(j = 0; j < y2; ++j)
{
multip[i][j]=0;
}
for(i = 0; i < x1; ++i)
for(j = 0; j < y2; ++j)
for(k = 0; k < y1; ++k)
{
multip[i][j] += arr[i][k] * brr[k][j];
}
cout << endl << "Output Matrix: " << endl;
for(i = 0; i < x1; ++i)
for(j = 0; j < y2; ++j)
{
cout << " " << multip[i][j];
if(j == y2-1)
cout << endl;
}
}
void addMatrix(){
int x, m, arr[50][50], br[50][50], sumArr[50][50], a, j;
cout << "Enter the rows number between 1 and 50): ";
cin >> x;
cout << "Enter the columns number between 1 and 50): ";
cin >> m;
cout << endl << "Enter items of the first matrix: " << endl;
for(a = 0; a < x; ++a)
for(j = 0; j < m; ++j)
{
cout << "Enter item a" << a + 1 << j + 1 << " : ";
cin >> arr[a][j];
}
cout << endl << "Enter items of the second matrix: " << endl;
for(a = 0; a < x; ++a)
for(j = 0; j < m; ++j)
{
cout << "Enter item " << a + 1 << j + 1 << " : ";
cin >> br[a][j];
}
for(a = 0; a < x; ++a)
for(j = 0; j < m; ++j)
sumArr[a][j] = arr[a][j] + br[a][j];
cout << "\n"<< "Sum of these two matrices is: " << endl;
for(a = 0; a < x; ++a)
for(j = 0; j < m; ++j)
{
cout << sumArr[a][j] << " ";
if(j == m - 1)
cout << endl;
}
}
int main()
{
multiplyMatrix();
addMatrix();
return 0;
}
Comments
Leave a comment