typestar

matrix.c in C

Multiply two 3x3 integer matrices and print the result.

#include <stdio.h>

#define N 3

void multiply(int a[N][N], int b[N][N], int out[N][N]) {
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++) {
            out[i][j] = 0;
            for (int k = 0; k < N; k++)
                out[i][j] += a[i][k] * b[k][j];
        }
}

int main(void) {
    int a[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int id[N][N] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
    int result[N][N];
    multiply(a, id, result);
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            printf("%4d", result[i][j]);
        putchar('\n');
    }
    return 0;
}

How it works

  1. The triple loop computes each output cell.
  2. Multiplying by the identity echoes the input.
  3. printf lays the result out in a grid.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
502
Tokens
271
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 155 seconds.

Type this snippet

Step 1 of 2 in Encore, step 19 of 20 in Data structures & algorithms.

← Previous Next →