9.4.20

product of two matrices


PRODUCT OF TWO MATRICES
#include <stdio.h>
void main()
{

    int m1[5][5],m2[5][5],m3[5][5]={0},r1,r2,c1,c2,i,j,k;
    printf("how many rows and cols for matrix 1");
    scanf("%d%d",&r1,&c1);
    printf("how many rows and cols for matrix 2");
    scanf("%d%d",&r2,&c2);
    if(c1!=r2)
    {

        printf("Multiplication rule violated -cannot be multiplied");
        exit(0);
    }

    printf("Enter elements into matrix 1:");
    for(i=0;i<r1;i++)
        for(j=0;j<c1;j++)
        scanf("%d",&m1[i][j]);

printf("Enter elements into matrix 2:");
    for(i=0;i<r2;i++)
        for(j=0;j<c2;j++)
        scanf("%d",&m2[i][j]);
        for(i=0;i<r1;i++)
            {


            for(j=0;j<c2;j++)
            {
                for(k=0;k<c1;k++)
                    m3[i][j]=m3[i][j]+m1[i][j]*m2[i][j];
            }
}
        printf("Product of two matrices:\n");
        for(i=0;i<r1;i++)
        {

            for(j=0;j<c2;j++)
                printf("%5d",m3[i][j]);
            printf("\n");




        }

}
OUTPUT
How many rows and cols for matrix 1 2
2
How may rows and cols for matrix 2  2
2
Enter element into matrix 1:1
2
3
4

Enter element into matrix 2:1
2
3
4

Product of two matrices:
2         8
18    32

No comments:

Post a Comment

JAVA program pattern 2

import java.util.Scanner; public class pattern3 { public static void main(String args[]) { int i,j; Scanner sc=new Scanner(System.in); Syste...