Sarah
Sarah

Reputation: 125

Multiplying matrices in general

I wrote a programm for multiplying matrices together. For testing I entered:

A [1 0, 0 1] and B=[2 2, 2 2]

The result should be: [2 2, 2 2]. However, I got [2122123 2, 2 2]. Why does this happen? Maybe the value is an address in the storage?

#include <stdio.h>

int main(){
    int A[10][10], B[10][10], C[10][10];
    int n,m,r,s,k,sum,j,i=0;

    printf("Enter the number of rows and columns of first matrix\n");
    scanf("%d%d", &n,&m);
    getchar();
    printf("Enter values:\n");

    for(i=0; i<n;i++){
        for(j=0; j<m; j++){
            scanf("%d", &A[i][j]);
            getchar();
        }
    }

    printf("Enter the number of rows and columns of second matrix\n");
    scanf("%d%d", &r,&s);
    getchar();
    if ( m != r )
        printf("Matrices with entered orders can't be multiplied with each other.\n");

    else{
        printf("Enter values\n");
        for(i=0; i<r;i++){
            for(j=0; j<s; j++){
                scanf("%d", &B[i][j]);
                getchar();
            }
        }
    
        for(i=0; i<n; i++){
            for(j=0; j<s;j++){
                for(k=0;k<r; k++){
                    sum=sum+ A[i][k]*B[k][j];
                }
                C[i][j]=sum;
                sum=0;
            }
        }
        printf("Product of entered matrices:-\n");
        for(i=0; i<n;i++){
            for(j=0; j<s; j++){
                printf("%d\t",C[i][j] );
            }
            printf("\n");
        }
    }

    return 0;
}

All in all I consider matrices of dimension nxm and rxs.

Upvotes: 0

Views: 71

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114230

The line int n,m,r,s,k,sum,j,i=0; does not initialize sum to 0. It only sets i.

Set sum = 0; immediately before the loop over k, not after.

Upvotes: 3

Related Questions