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

USE C PROGRAMMING LANGUAGE This program will test your ability to manage memory

ID: 3754385 • Letter: U

Question

USE C PROGRAMMING LANGUAGE

This program will test your ability to manage memory using malloc) and provide some experience dealing with 2D arrays in C. Your task is to create a program that multiplies two matrices and outputs the resulting matrix. The input matrices can be the same or different sizes. Input-Output format: Your program will take the file name as input. The first line in the file will provide the number of rows and columns in the matrix separated by a tab. The subsequent lines will provide the contents of the matrix. The numbers in the same row are tab separated and the rows are separated with new lines. This will be followed by the same format for the dimensions and content of the second matrix For example, a sample input file "filel.txt": 1 2 3 4 5 6 3 2 1 2 3 4 The first number (2) refers to the number of rows and the second number (3) refers to the number of columns in the matrix. The dimensions of the of the first matrix will be 2x3 and the second matrix will be 3x2. The output on executing the program with the above input is shown below. The outputted numbers should be tab separated in the same row with a newline between rows. There should not be extra tabs or spaces at the end of the line or at the end of the file $./fourth file1.txt 22 28 49 64 We will not give you improperly formatted files. You can assume all your input files will be in proper format as above with no matrix having 0 rows or columns For matrices that cannot be multiplied your program should output "bad-matrix

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

int main()
{
int **mat1,**mat2,**result;
int row1,col1,row2,col2;
int i,j,k,sum;
FILE *file;
file=fopen("file1.txt", "r");
fscanf(file, "%d", &row1);//row of first matrix
fscanf(file, "%d", &col1);//column of first matrix
mat1=(int **)malloc(row1 * col1 * sizeof(int));//create memory for first matrix
//reading data for first matrix
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
fscanf(file, "%d", &mat1[i][j]);
}
}
  
fscanf(file, "%d", &row2);//row of second matrix
fscanf(file, "%d", &col2);//column of second matrix
mat2=(int **)malloc(row2 * col2 * sizeof(int));//create memory for second matrix
//reading data for second matrix
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
fscanf(file, "%d", &(mat2[i][j]));
}
}
  
if (col1 != row2) //matrix multipication not posible if col1 is not equal to row2
{
printf("bad-matrix");
}
result = (int **)malloc(row1 * col2 * sizeof(int));//create memory for result matrix
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
result[i][j] = 0;
for(k=0;k<col1;k++)
{
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
  
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
printf("%d ",result[i][j]);
}
printf(" ");
}

return 0;
}