Given matrices and , compute their sum — the matrix , where
Algorithm implementation
Declare the matrices and .
#define MAX 101
int a[MAX][MAX], b[MAX][MAX], c[MAX][MAX];Read the input data — matrices and .
scanf("%d %d", &n, &m);
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
scanf("%d", &a[i][j]);
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
scanf("%d", &b[i][j]);Compute the sum of the matrices: C = A + B.
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
c[i][j] = a[i][j] + b[i][j];Print the resulting matrix.
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
printf("%d ", c[i][j]);
printf("\n");
}Algorithm implementation – double pointer
Declare the matrices , and as double pointers.
int **a, **b, **c;The function Read reads the matrix .
void Read(int **&matr, int n, int m)
{
matr = new int* [n];
for (i = 0; i < n; i++)
{
matr[i] = new int[m];
for (j = 0; j < m; j++)
scanf("%d", &matr[i][j]);
}
}The function Sum computes the sum of the matrices A + B and stores it in matrix .
void Sum(int **a, int **b, int **&c, int n, int m)
{
c = new int* [n];
for (i = 0; i < n; i++)
{
c[i] = new int[m];
for (j = 0; j < m; j++)
c[i][j] = a[i][j] + b[i][j];
}
}The function Print prints matrix .
void Print(int **a)
{
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
printf("%d ", a[i][j]);
printf("\n");
}
}The main part of the program. Read the dimensions of the matrices and .
scanf("%d %d", &n, &m);Read the matrices and .
Read(a, n, m);
Read(b, n, m);Compute the sum of the matrices C = A + B.
Sum(a, b, c, n, m);Print the resulting matrix.
Print(c);