Pages

Write a program to multiply two matrix and show result on screen

Tuesday, 28 May 2013

#include <stdio.h>
#include <conio.h>
int main()
{
    int i, j, k, a1[5][5], a2[5][5], a3[5][5], r1, r2, c1, c2, sum;
    printf("Enter number of rows for fisrt metrix: ");
    scanf("%d", &r1);
    printf("Enter number of columns for fisrt metrix: ");
    scanf("%d", &c1);
    printf("Enter number of rows for second metrix: ");
    scanf("%d", &r2);
    printf("Enter number of columns for second metrix: ");
    scanf("%d", &c2);
    if(c1!=r2)
    {
           printf("Multiplication cannot take place, columns of first metrix should be equal to second row.");
    }
    else
    {
        // enter elements in metrix
        for(i=0; i<r1; i++)
                 {
                        for(j=0; j<c1; j++)
                        {
                                 printf("Enter element of row %d and colimn %d: ", i, j);
                                 scanf("%d",&a1[i][j]);
                        }
                 }
        for(i=0; i<r2; i++)
                 {
                        for(j=0; j<c2; j++)
                        {
                                 printf("Enter element of row %d and colimn %d: ", i, j);
                                 scanf("%d", &a2[i][j]);
                        }
                 }
                
        for(i=0; i<r1; i++)
        {
                 for(j=0; j<c2; j++)
                 {
                          sum=0;
                          for(k=0; k<c1; k++)
                          {
                                   sum=sum+a1[i][k]*a2[k][j];
                                   a3[i][j]=sum;
                          }
                 }
        }
             //show elements of metrix.
        printf("\n");
        for(i=0; i<r1; i++)
                 {
                        for(j=0; j<c1; j++)
                        {
                                 printf("%d\t", a1[i][j]);
                        }
                        printf("\n");
                 }
        printf("\n");
        for(i=0; i<r2; i++)
                 {
                        for(j=0; j<c2; j++)
                        {
                                 printf("%d\t", a2[i][j]);
                        }
                        printf("\n");
                 }
        printf("Multiplication of array: \n");
        for(i=0; i<r2; i++)
                 {
                        for(j=0; j<c2; j++)
                        {
                                 printf("%d\t", a3[i][j]);
                        }
                        printf("\n");
                 }
    }
    getch();
}
 

Search Box

Most Reading

Contact Form

Name

Email *

Message *