Pages

Sunday, 12 July 2015

Matrix multiplication

Matrix multiplication in c
Coding:
#include<stdio.h>

int main()
{
    int a[10][10],b[10][10],c[10][10],i,j,k,row1,col1,row2,col2;
    printf("Enter the dimaension of first matrix:");
    scanf("%d%d",&row1,&col1);
    printf("Enter the dimaension of second matrix:");
    scanf("%d%d",&row2,&col2);
    if(col1==row2)
    {
        printf("Enter the elements of the first matrix:\n");
        for(i=0;i<row1;i++)
            for(j=0;j<col1;j++)
                scanf("%d",&a[i][j]);
        printf("\nEnter the elements of the second matrix:\n");
        for(i=0;i<row2;i++)
            for(j=0;j<col2;j++)
                scanf("%d",&b[i][j]);
        printf("\nBefore addition:");
        printf("\nFirst matrix:");
        for(i=0;i<row1;i++)
        {
            printf("\n");
            for(j=0;j<col1;j++)
                printf("%d ",a[i][j]);
        }
        printf("\nSecond matrix:");
        for(i=0;i<row2;i++)
        {
            printf("\n");
            for(j=0;j<col2;j++)
                printf("%d ",b[i][j]);
        }
        printf("\nAfter matrix multiplication:");
        for(i=0;i<row1;i++)
        {
            printf("\n");
            for(j=0;j<col2;j++)
            {
                c[i][j]=0;
                for(k=0;k<col1;k++)
                {
                    c[i][j]+=a[i][k]*b[k][j];
                }
               printf("%d ",c[i][j]);
            }
        }
    }
    else
    {
        printf("Matrix addition not possible");
    }
    return 0;
}
Output:
Enter the dimaension of first matrix:2 3
Enter the dimaension of second matrix:3 2
Enter the elements of the first matrix:
1 2 3
4 5 6

Enter the elements of the second matrix:
1 2
3 4
5 6

Before addition:
First matrix:
1 2 3
4 5 6
Second matrix:
1 2
3 4
5 6
After matrix multiplication:
22 28
49 64