# C Program for Matrix Chain Multiplication

CServer Side ProgrammingProgramming

In this problem, we are given a sequence( array) of metrics. our task is to create a C program for Matrix chain multiplication. We need to find a way to multiply these matrixes so that, the minimum number of multiplications is required.

The array of matrices will contain n elements, which define the dimensions of the matrices as, arr[i-1] X arr[i].

Let’s take an example to understand the problem,

## Input

array[] = {3, 4, 5, 6}

## Explanation

the matrices will be of the order −

Mat1 = 3X4, Mat2 = 4X5, Mat3 = 5X6

For these three matrices, there can be two ways to multiply,

mat1*(mat2*mat3) -> (3*4*6) + (4*5*6) = 72 + 120 = 192
(mat1*mat2)*mat3 -> (3*4*5) + (3*5*6) = 60 + 90 = 150

The minimum number of mulitplications will be 150 in case of (mat1*mat2)*mat3.

The problem can be solved using dynamic programming as it posses both the properties i.e. optimal substructure and overlapping substructure in dynamic programming.

So here is C Program for Matrix Chain Multiplication using dynamic programming

## Example

Live Demo

#include <stdio.h>
int MatrixChainMultuplication(int arr[], int n) {
int minMul[n][n];
int j, q;
for (int i = 1; i < n; i++)
minMul[i][i] = 0;
for (int L = 2; L < n; L++) {
for (int i = 1; i < n - L + 1; i++) {
j = i + L - 1;
minMul[i][j] = 99999999;
for (int k = i; k <= j - 1; k++) {
q = minMul[i][k] + minMul[k + 1][j] + arr[i - 1] * arr[k] * arr[j];
if (q < minMul[i][j])
minMul[i][j] = q;
}
}
}
return minMul[1][n - 1];
}
int main(){
int arr[] = {3, 4, 5, 6, 7, 8};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Minimum number of multiplications required for the matrices multiplication is %d ",    MatrixChainMultuplication(arr, size));
getchar();
return 0;
}

## Output

Minimum number of multiplications required for the matrices multiplication is 444
Published on 17-Jul-2020 16:26:45