0
6.0kviews
Write a C program to multiply 2 matrices after checking compatibility. Your program should make use of functions to accept element of matrix and multiply matrix

Mumbai university > FE > SEM 2 > Structured Programming Approach

Marks: 10M

Year: May 2014

1 Answer
0
193views

Program:

#include<stdio.h>
#include<conio.h>
int main() {
    int m, n, p, i, j, first[10][10], second[10][10];
    int MatMul( int first[10][10], int second[10][10],int m, int n, int p);
    printf("Enter the number of rows and columns of first matrix:\n");
    scanf("%d%d", &m, &n);
    printf("Enter the elements of first matrix:\n");

    for (i = 0; i <= m-1; i++)  {
        for (j = 0; j <= n-1; j++)  {
            printf("Enter a value:\n");
            scanf("%d", &first[i][j]);
        }
    }
    printf("The number of rows for matrix 2 will be %d\n", n);
    printf("Enter the columns of matrix 2:");
    scanf("%d", &p);

    printf("Enter the elements of matrix 2:\n");

    for (i = 0; i <= n-1; i++)  {
        for (j = 0; p <= n-1; j++)  {
            printf("Enter a value:\n");
            scanf("%d", &second[i][j]);
        }
    }
    MatMul(first, second, m, n, p);
    getch();
} //main ends

int MatMul(int first[10][10], int second[10][10], int m, int n, int p) 
{
    int i, j, k, c[10][10];
    for (i = 0; i <=m-1; i++)   
    {
        for (j = 0; j <=p-1; j++) 
        {
            c[i][j]=0;
            for (k = 0; k <=n-1; k++)   
            {
                c[i][j] = c[i][j] + first[i][k]*second[k][j];
            } //inner for loop ends
        } //middle for loop ends
    } //outer for loop ends

    printf("The resultant matrix is:\n");
    for(i=0; i<-m-1; i++);  
    {
        for(j=0; j<=p-1; j++);      
        {
            printf("%d\t", c[i][j]);
        }
        printf("\n");
    }
} //function MatMul ends

Output:

Enter the number of rows and columns of matrix 1: 3 2

Enter the elements of matrix 1:

Enter a value: 1 2 3 4 5 6

The number of rows for matrix 2 will be 2

Enter the column of matrix 2: 3

Enter the elements of matrix 2:

Enter a value: 1 2 3 4 5 6

The resultant matrix is:

9 12 15

19 26 33

29 40 51

Please log in to add an answer.