Answer on Question#49934 - <programming> - <c++>
Program
#include <iostream>
#define N 3
#define M 3
using namespace std;
void getInput(int **mass)
{
int i, j;
for(i=0; i<N; i++)
for(j=0; j<M; j++)
cin >> mass[i][j];
}
void print(int **mass)
{
int i, j;
for(i=0; i<N; i++)
{
for(j=0; j<M; j++)
cout << mass[i][j] << " ";
cout << endl;
}
}
void addMat(int **mas1, int **mas2, int **res)
{
int i, j;
for(i=0; i<N; i++)
for(j=0; j<M; j++)
res[i][j] = mas1[i][j] + mas2[i][j];
}
void multMat(int **mas1, int **mas2, int **res)
{
int i, j, k;
for(i=0; i<N; i++)
for(j=0; j<M; j++)
{
res[i][j] = 0;
for(k=0; k<N; k++)
res[i][j] += mas1[i][k] * mas2[k][j];
}
}
int main()
{
int **mat1 = new int*[N], **mat2 = new int*[N], **res = new int*[N];
int i;
for(i=0; i<N; i++)
{
mat1[i] = new int[M];
mat2[i] = new int[M];
res[i] = new int[M];
}
cout << "Please enter a 3x3 matrix: ";
getInput(mat1);
cout << "Please enter a 3x3 matrix: ";
getInput(mat2);
addMat(mat1, mat2, res);
cout << "\nSum of matrices: " << endl;
print(res);
multMat(mat1, mat2, res);
cout << "\nProduct of matrices: " << endl;
print(res);
return 0;
}Example of execute program:
Please enter a 3x3 matrix: Input element [0][0]: 1
Input element [0][1]: 2
Input element [0][2]: 3
Input element [1][0]: 4
Input element [1][1]: 5
Input element [1][2]: 6
Input element [2][0]: 7
Input element [2][1]: 8
Input element [2][2]: 9
Please enter a 3x3 matrix: Input element [0][0]: 1
Input element [0][1]: 0
Input element [0][2]: 0
Input element [1][0]: 0
Input element [1][1]: 1
Input element [1][2]: 0
Input element [2][0]: 0
Input element [2][1]: 0
Input element [2][2]: 1
Sum of matrices:
2 2 3
4 6 6
7 8 10
Product of matrices:
1 2 3
4 5 6
7 8 9
Process returned 0 (0x0) execution time : 191.484 s
Press any key to continue.
Comments