Addition of two matrices is very simple: the sum of two matrices is the matrix composed of the sums of elements of the two matrices:
This definition is expressed in C in algorithm 4.1.
[hbtp]
1 void mm_add (int A[N][N], int B[N][N], int C[N][N])
2 {
3 int i, j;
4
5 for (i = 0; i < N; i++) {
6 for (j = 0; j < N; j++) {
7 C [i][j] = A [i][j] + B [i][j];
8 }
9 }
10 }
Algorithm 4.1 is clearly
.
The algorithm for multiplication is quite a bit different than might be expected- instead of simply multiplying the elements together, each element of the product is the result of several operations, as described in algorithm 4.2.
[hbtp]
1 void mm_mul (int A[N][N], int B[N][N], int C[N][N])
2 {
3 int i, j, k;
4 int sum;
5
6 for (i = 0; i < N; i++) {
7 for (j = 0; j < N; j++) {
8 sum = 0;
9 for (k = 0; k < N; k++) {
10 sum += A[i][k] * B[k][j];
11 }
12 C[i][j] = sum;
13 }
14 }
15 }
Algorithm 4.2 is clearly .