C program to multiply two matrices Using two-dimensional array



C program to multiply two matrices Using two-dimensional array.
To understand this example you should have knowledge of twodimensional array in .
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
void multiply (int [] [10], int [] [10], int, int, int);
void display (int [] [10], int, int);
void main ()
{
int rows_A, cols_A;
int rows_B, cols_B;
int I, j;
int a[10] [10], b[10] [10];
clrscr ();
printf (“Enter no. of rows in the first table(<10):”);
scanf (“%d”, &raws_A);
printf (“Enter no. of columns in the first table(>10):”);
scanf(“%d”,&cols_A);
printf (“Enter no. of rows in the second table(<10):”);
scanf (“%d”, &raws_B);
printf (“Enter no. of columns in the second table(>10):”);
scanf(“%d”,&cols_B);
if(cols_A!=rows_B)
{
printf(“Number of cols. of matrix A should be same as rows of B”);
exit(1);
}
else
{
printf (“ - - - - - Enter row wise %d integer of A - - - - - \n”,rows_A*cols_A);
for (i=0;i<rows_B;i++)
  for (j=0; j<cols_A; j++);
{
scanf (“%d”, &a[i] [j]);
}
display (a, rows_A, cols_A);
printf (“ - - - - - Enter row wise %d integer of B - - - - - \n”,rows_B*cols_B);
for (i=0; i<rows_B; i++)
  for (j=0; j<cols_B; j++)
{
scanf (“%d”, &b[i] [j]);
}
display (b, rows_B, cols_B);
multiply (a,b, rows_A, cols_B, cols_A);
}
getch ();
}
void multiply (int x[] [10], int y[] [10], int m, int q, int n)
{
int i, j, k;
int z[10] [10];
for (i=0; i<m; i++)
    for (j=0; j<q; j++)
{
z[i] [j] = 0;
for (k=0; k<n; k++)
{
  z[i] [j] += x[i] [k]*y[k][j];
}
}
printf (“\n - - - - - Result of multiplication - - - - - “);
display (z, m, q)
}
void display (int c[] [10], int m, int n)
{
int  i, j;
printf (“\n - - - - - Displaying %d by %d data - - - - - \n”, m, n);
for (i=0; i<m; i++)
{
for (j=0; j<n; j++)
  printf(“%d\t”, c[i] [j]);
printf (“\n”);
}
}
OUTPUT
Enter no. of rows in the first table (<10): 1
Enter no. of columns in the first table (<10): 2
Enter no. of rows in the second table (<10): 2
Enter no. of rows in the second table (<10): 3
- - - - - Enter row wise 2 integer of A - - - - -
2    4
- - - - - Displaying 1 by 2 data - - - - -
2        4
- - - - - Enter row wise 6 integer of B - - - - -
1    3    2    4    3    5
- - - - - Displaying 2 by 3 data - - - - -
1        3        2
4        3        5
- - - - - Result of multiplication - - - - -
- - - - - Displaying 1 by 3 data - - - - -
18        18        24
EXPLANATION:
In this program , we first enter elements of two matrices A and B. to find the product of two matrices we call the multiply() function. In this function, we take a local two dimensional array z in which product of each element of two matrices will be stored.




No comments

Powered by Blogger.