C Beginner C Beginner - 1 year ago 119
C Question

Matrix Multiplication In C

I'm trying to solve a matrix multiplication problem with C. Matrix sizes given in problem (2x2)
I wrote this code but it doesn't print result as I expect. I think I'm missing a point about rules of C.

What is my mistake in this code ?

#include <stdio.h>
int main() {
int matA[2][2]={0,1,2,3};
int matB[2][2]={0,1,2,3};
int matC[2][2];
int i, j, k;
for (i = 0; i < 2; i++) {
for(j = 0; j < 2; j++) {
for(k = 0; k < 2; k++) {
matC[i][j] += matA[i][k] * matB[k][j];

Printing Result:


Answer Source

The problem is that in the line

matC[i][j] += matA[i][k] * matB[k][j];

you are adding things to matC, but when you create it, you don't initialize it, so it has garbage.

You sould do something like:

int matC[2][2] = {0} which will initialize all the matrix with 0's

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download