 C Tutorial

# C program to compute matrix multiplication using two dimensional array

## C program to compute matrix multiplication using two dimensional array

This c program is used to compute the multiplication of two matrix using two dimensional array and nested for loops.

Defined the macro for row nad column size using define driective.

```a b c           g h i           (a*g)+(b*j)+(c*m)    (a*h)+(b*k)+(c*n)    (a*i)+(b*l)+(c*o)
d e f      *    j k l      =     (d*g)+(e*j)+(f*m)    (d*h)+(e*k)+(f*n)    (d*i)+(e*l)+(f*o)
g h i           m n o           (g*g)+(h*j)+(i*m)    (g*h)+(h*k)+(i*n)    (g*i)+(h*l)+(i*o)
```

Here two matrix row and column size is common.

```#include<stdio.h>

#define COLUMN 3
#define ROW 3

void main()
{
int matrix1[ROW][COLUMN], matrix2[ROW][COLUMN], matrix3[ROW][COLUMN];
int i,j,k, mul;

printf("\nEnter Matrix1: \n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COLUMN;j++)
{
matrix3[i][j] = 0;
scanf("%d", &matrix1[i][j]);
}
}
printf("\nEnter Matrix2: \n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COLUMN;j++)
{
scanf("%d", &matrix2[i][j]);
}
}
if(ROW!=COLUMN)
{
printf("\nError: First matrix column and second matrix row size is not same.");
return;
}
for(i=0;i<ROW;i++)
{
for(j=0;j<COLUMN;j++)
{
for(k=0;k<ROW;k++)
{
mul = matrix1[i][k] * matrix2[k][j];
matrix3[i][j] = matrix3[i][j] + mul;
}
}
}
printf("\nMatrix Multiplication: \n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COLUMN;j++)
{
printf("%d\t", matrix3[i][j]);
}
printf("\n");
}
}
```

Output:

```\$ cc matrix_multiplication.c
\$ ./a.out

Enter Matrix1:
3 4 2
4 5 6
7 8 9

Enter Matrix2:
13 4 5
8 2 1
6 5 6

Matrix Multiplication:
83	30	31
128	56	61
209	89	97
```

## C program to compute matrix multiplication with diffent rows and columns using two dimensional array

Above program, having same rows and columns in both matrix to do the matrix multiplication, let us discuss how we need to do the changes in above program to make functional when we have two different matrix with different size of rows and columns.

```#include<stdio.h>

#define COLUMN1 3
#define ROW1 1
#define COLUMN2 3
#define ROW2 3

void main()
{
int matrix1[ROW1][COLUMN1], matrix2[ROW2][COLUMN2], matrix3[ROW1][COLUMN1];
int i,j,k, mul;

printf("\nEnter Matrix1: \n");
for(i=0;i<ROW1;i++)
{
for(j=0;j<COLUMN1;j++)
{
matrix3[i][j] = 0;
scanf("%d", &matrix1[i][j]);
}
}
printf("\nEnter Matrix2: \n");
for(i=0;i<ROW2;i++)
{
for(j=0;j<COLUMN2;j++)
{
scanf("%d", &matrix2[i][j]);
}
}
if(COLUMN1!=ROW2)
{
printf("\nError: First matrix column and second matrix row size is not same.");
return;
}
for(i=0;i<ROW1;i++)
{
for(j=0;j<COLUMN2;j++)
{
for(k=0;k<ROW2;k++)
{
mul = matrix1[i][k] * matrix2[k][j];
matrix3[i][j] = matrix3[i][j] + mul;
}
}
}
printf("\nMatrix Multiplication: \n");
for(i=0;i<ROW1;i++)
{
for(j=0;j<COLUMN1;j++)
{
printf("%d\t", matrix3[i][j]);
}
printf("\n");
}
}
```

Output:

```\$ cc matrix_multiplication.c
\$ ./a.out

Enter Matrix1:
3 4 2

Enter Matrix2:
13 9 7
8 7 4
6 4 0

Matrix Multiplication:
83	63	37
```     