简体   繁体   中英

Why my program of Matrix multiplication using C doesn't work?

I wrote a program to calculate the matrix multiplication .I takes user input to define the size of the array and the elements contained.(My knowledge on programming should be considered as a beginner).When I execute the program it prints a null array. When I tested the code line by line. I found out that the program works correctly till the calculation of the matrix.(Taking user input and calling the function). I couldn't find the source of the problem. I have included part of the code which contains the multiplication function.

#include <stdio.h>
#define MAX 100
void matrix_mul(int, int, int, int, int [MAX][MAX], int [MAX][MAX]);

int main()
{

int mat_1[MAX][MAX] ,mat_2[MAX][MAX];
int row1, row2, column1, column2;

printf("Input number of rows for the first matrix:  ");
scanf("%d", &row1);
printf("Input number of columns for the first matrix:  ");
scanf("%d", &column1);

printf("Input number of rows for the second matrix:  ");
scanf("%d", &row2);
printf("Input number of columns for the second matrix:  ");
scanf("%d", &column2);

if(column1 != row2 || column2 != row1)
{
    printf("Incompatible matrices. Try Again! ");
    return 0;
}

printf("Enter elements for matrix 1 of order %d x %d\n", row1, column1);

for(int i=0; i<row1; i++)
{
    for(int j=0; j<column1; j++)
        scanf("%d", &mat_1[i][j]);
}

printf("\n\nEnter elements for matrix 1 of order %d x %d\n", row2, column2);

for(int i=0; i<row2; i++)
{
    for(int j=0; j<column2; j++)
        scanf("%d", &mat_2[i][j]);
}
 matrix_mul(row1, row2, column1, column2, mat_1, mat_2);

}

// for testing r1 = 3 c1 =2 r2 =2 c2 =3
void matrix_mul(int row1, int row2, int column1, int column2, int ar1[MAX][MAX], int ar2[MAX][MAX])
{

    int arr [MAX][MAX]; 

    for(int i=0 ; i<row1; i++)
    {

        for(int j=0; j<column2; j++)
        {
            int sum = 0;
            for(int k=0; k<column1; k++)
                sum += ar1[row1][k] * ar2[column1][row1];
            printf("%d", sum);
            arr[row1][column2] = sum;
        }
    }

    for(int i=0; i<row1; i++)
    {
        for(int j=0; j<column2; j++)
            printf("%d ", arr[i][j]);
        printf("\n");
    }

}

You're mixing up your loop values with your boundaries. Here's the corrected versions of the relevant lines:

            sum += ar1[i][k] * ar2[k][j];
        arr[i][j] = sum;

You're seeing 88888 instead of 8 because you left a debugging statement in:

printf("%d", sum);

Remove that and you'll only see the correct output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM