Search code examples
cloopsmatrixmultiplication

Matrix Multiplication in C - Problem with inputs


I've written a program which carries out matrix multiplication using functions. The function which i presume is wrong is as follows:

void obtainMatrixElems(int mtrx[][10], int row_elems, int col_elems){
    printf("Kindly enter matrix elements: \n");

    for(int x = 0; x < row_elems; x++){
        for(int y = 0; y < col_elems; y++){
            printf("Enter element at position %d,%d: \n", x+1, y+1);
            scanf("&d", &mtrx[x][y]);
        }
    }
}

Solution

  • It seems you are missing a "+" at multAns[x][y] = matrix1[x][y] * matrix2[x][y];.

    It should rather be:

    // Also note the change variables used for referencing cells ...
    multAns[x][y] += matrix1[x][z] * matrix2[z][y];
    

    In case your last operation result is 0 then this explains why you get a 0 matrix..

    EDIT:

    The sign is one of the problems .. There is also something wrong with the way you get input from the user.

        for(int x = 0; x < row_elems; x++){
            for(int y = 0; y < col_elems; y++){
                printf("Enter element at position %d,%d: \n", x+1, y+1);
                // Note the change of "&" to "%" and the extra sequence
                // "\r\n" which expects the user to press ENTER (i.e.:
                // new line) between input cells
                rc = scanf("%d\r\n", &mtrx[x][y]);
                if (rc != 1) {
                    printf("ERROR: scanf did not proceed as expected\r\n");
                }
            }
        }