Matrix Multiply in C

August 06, 2020


This program multiples two matrices together. Matrix m1 and matrix m2 are randomly generated. The resulting matrix is initially set to all zeros to avoid having the values already set. The matrices and the answer are printed.

To compile:

make matrices
matrices.c:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int m1[5][5], m2[5][5], res[5][5];

    // Use current time as seed for random generator 
    srand(time(NULL));    

    //init result to 0
    for (int i = 0; i < 5; ++i) {
        for (int j = 0; j < 5; ++j)
            res[i][j] = 0;
    }

    // fill matrix with random numbers
    for (int i = 0; i < 5; ++i) {
        for (int j = 0; j < 5; ++j)
            m1[i][j] = rand() % 5;
    }

    for (int i = 0; i < 5; ++i) {
        for (int j = 0; j < 5; ++j)
            m2[i][j] = rand() % 5;
    }


    //multiply matrices
    for (int i = 0; i < 5; ++i) {
        for (int j = 0; j < 5; ++j) {
            for (int k = 0; k < 5; ++k) {
                res[i][j] += m1[i][k] * m2[k][j];
            }
        }
    }
    printf("m1:\n");
    for (int i = 0; i < 5; ++i) {
        for (int j = 0; j < 5; ++j) {
            printf("%d  ", m1[i][j]);
            if (j == 4)
                printf("\n");
        }
    }

    printf("m2:\n");
    for (int i = 0; i < 5; ++i) {
        for (int j = 0; j < 5; ++j) {
            printf("%d  ", m2[i][j]);
            if (j == 4)
                printf("\n");
        }
    }

    printf("Result:\n");
    for (int i = 0; i < 5; ++i) {
        for (int j = 0; j < 5; ++j) {
            printf("%d  ", res[i][j]);
            if (j == 4)
                printf("\n");
        }
    }
    return EXIT_SUCCESS;
}

Comments

©2013-2020 All Rights Reserved.