Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write two functions (an iterative and a recursive function) which will perform t

ID: 3779484 • Letter: W

Question

Write two functions (an iterative and a recursive function) which will perform the multiplication of two matrices.
Write a main program that reads from the user the sizes and elements of two matrices and then, if possible, prints out the new matrix, which is the multiplication of the two matrices.
A sample program run is as follows:


Enter rows and colunns of first matrix:3 Enter row and columns of second matrix:2 s Enter first natrix 2 4 6 3 1 2 Enter second natrix: 3 4 1 3 3 8 The new matrix is: 18 20 34 27 33 30 9 10 17

Explanation / Answer

#include<stdio>

#include<conio>

#define INFY 999999999

long int m[20][20];

int s[20][20];

int p[20],i,j,n;

void print_optimal(int i,int j)

{

if (i == j)

                                printf(" A%d ",i);

                else

                {

                                printf(" ( ");

                                print_optimal(i, s[i][j]);

                                print_optimal(s[i][j] + 1, j);

                                printf(" ) ");

                }

}

void matmultiply(void)

{

                long int q;

                int k;

                for(i=n;i>0;i--)

{

for(j=i;j<=n;j++)

{

if(i==j)

m[i][j]=0;

                                                else

                                                {

                                                                for(k=i;k<j;k++)

                                                                {

                                                                                q=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];

                                                if(q<m[i][j])

                                                {

                                                                m[i][j]=q;

                                                                                s[i][j]=k;

                                                               }

                                                                }

                                                }

                                }

                }

}

void main()

{

                int k;

printf("Enter the no. of elements: ");

scanf("%d",&n);

for(i=1;i<=n;i++)

for(j=i+1;j<=n;j++)

{

m[i][i]=0;

m[i][j]=INFY;

s[i][j]=0;

}

printf(" Enter the dimensions: ");

for(k=0;k<=n;k++)

{

printf("P%d: ",k);

scanf("%d",&p[k]);

}

matmultiply();

printf(" Cost Matrix M: ");

for(i=1;i<=n;i++)

for(j=i;j<=n;j++)

printf("m[%d][%d]: %ld ",i,j,m[i][j]);

printf(" Matrix S for k values: ");

for(i=1;i<=n;i++)

                                for(j=i;j<=n;j++)

printf("m[%d][%d]: %d ",i,j,s[i][j]);

i=1,j=n;

printf(" MULTIPLICATION SEQUENCE : ");

print_optimal(i,j);

getch();

}