Sunday, 10 January 2016

Multiplication of Two Matrices (Algorithm 4.7)


Before seeing the solution make sure that you tried enough. Don’t paste the whole code, just find out the logic. If you stuck in trouble, just inform me on comment.


/**Bismillahir Rahmanir Rahim.**/

#include <stdio.h>
int main()
{
    int M, P, N, i, j, k;
    scanf("%d%d%d", &M,&P,&N);
    int A[M][P], B[P][N], C[P][N];
    for(i=0; i<M; i++)
    {
        for(j=0; j<P; j++) scanf("%d", &A[i][j]);
    }
    for(i=0; i<M; i++)
    {
        for(j=0; j<N; j++)
            scanf("%d", &B[i][j]);
    }
    for(i=0; i<M; i++)
    {
        for(j=0; j<N; j++)
        {
            C[i][j] = 0;
            for(k=0; k<P; k++) C[i][j] += A[i][k]*B[k][j];
        }
    }
    printf("\n\n");
    for(i=0; i<P; i++)
    {
        for(j=0; j<N; j++)
            printf("%d   ", C[i][j]);
        printf("\n");
    }

    return 0;
}
Here, A, (M*P) size matrix. M column, P row.
Here, B, (P*N) size matrix. P column, N row.
First input Value of M. ex.   2
Second input Value of P. ex.   2
Third input Value of N (N>=M). ex.   3
Forth input  A[M][P] ex.    1     3

                                            2     4

Fifth input  B[P][N] ex.    2     0    -4
                                          3     2     6

Output:          11     6     14
                      16     8     16

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.