I am doing a project for my c programming class, and was hoping I could get some
ID: 3860513 • Letter: I
Question
I am doing a project for my c programming class, and was hoping I could get some help.
The Project:
Dynamic Arrays and File I/O with Matrix Operations
In this program we will create a program that performs matrix calculations on two matrices that are either read infrom a file, or randomly generated. If you were not in class when we did all these matrix calculations, the notes are posted online. Also these operations are very common then there are numerous resources to explain them online: https://web.stanford.edu/~wfsharpe/mia/mat/mia_mat2.htm
Step 1:
Create three pointers that will hold the three dynamically generated arrays used in the program. a and b are the arrays on which we will do operations, and c is the results array. Initialize these arrays to NULL.
int** a; int** b; int** c;
Also create integer variables to hold the row and column dimensions of these three arrays
int N_a, M_a, N_b, M_b, N_c, M_c;
Step 2: Create the menu given in the executable. It contains the following error checks:
-If the user selects a character not given in the list print:
printf("Error -- Invalid choice! Please select again... ");
-If choices a, b, c, d, e or w are chosen before choices f or r print the error message:
printf("Error -- no data inputted. Please enter data... ");
Step 3: Add the following function to your code. It releases memory from a dynamic array when you are done using it
void FreeArray(int** arr, int N)
{
int i;
if(arr == NULL) return;
if(arr != NULL)
{
for(i = 0; i<N; i++)
{ if(arr[i] != Null) free(arr[i]);
free(arr);
}
}
Step 4: Create a print function that will print any array given its pointer and dimensions
void PrintArray(int** arr, int N, int M);
Step 5: For option R, ask the user to enter a value N from which we will create and allocate two NxN arrays filled with random integers between 0-10. The pseudocode looks like this:
Set a flag variable dataReadSuccess to false/0.
If array a is not equal to NULL, free the memory of a (use the given function FreeArray)
If array b is not equal to NULL, free the memory of b (use the given function FreeArray)
Repeatedly ask the user to enter a size N until they give a value greater or equal to 2. When they give a value less than 2, print error printf("Error -- enter a positive size greater than 2."); Assume they give you numerical values.
Set N_a, M_a, N_b and M_b all equal to N
Set a flag variable errorInAlloc = 0
Allocate the row dimension of a to the size of N_a (for the following instructions for allocation it should look just like the book example we did in class).
If this allocation was not successful set errorInAlloc = 1
If this was successful, allocate all the individual rows of a to size M_a.
For each of these rows, fill the values with random integers between 0 - 10
If any of these row allocations are not successful, set errorInAlloc to 1.
If no error in allocation occurred when setting a (errorInAlloc ==0) print a and repeat the exact same steps to fill b.
If at any point in the above steps errorInAlloc got set to 1 print the error message at the end of the steps printf("Error -- Unable to allocate arrays ");
Otherwise set dataReadSuccess to true/1 (you can use this in your checks for whether data has been entered prior to calling a,b,c,d,e or w).
Step 6: Create a function to add together two arrays (a, b) and save their result in array c.
void MatrixAddition(int** a, int** b, int** result, int N, int M)
Step 7: In your menu for choice a, call the function MatrixAddition as follows. You can only do matrix addition between a and b if their dimensions are the same. Understand this code fragment well, as the steps will be very similar for all the other options
else if(choice == 'a' || choice == 'A') //addition
{
if(N_a == N_b && M_a == M_b)
{
if(c != NULL) FreeArray(c, N_c);
N_c = N_a; M_c = M_a;
c = (int**) calloc(N_c, sizeof(int*));
for(i = 0; i< N_c; i++) c[i] = (int*) calloc(M_c,
sizeof(int));
MatrixAddition(a,b,c, N_a, M_a);
printf("A + B = ");
PrintArray(c, N_c, M_c);
}
else
{
printf("Error -- Size mismatch between array 1 and array 2 ");
}
}
Step 8: Create a function MatrixSubtraction that subtracts two matrices from one another. Call this function from the menu choice b. You can only do subtraction if arrays a and b are the same size.
void MatrixSubtraction(int** a, int** b, int** result, int N, int M);
Step 9: Create a function MatrixTranspose that returns the transpose of a matrix. Call this function from choice d.
void MatrixTranspose(int** a, int** result, int N, int M);
Step 11: Create a function MatrixMultiplication that multiples arrays a and b together. Call this function from choice e. You can only multiply a and b together if the number of columns in a are equal to the number of rows in b. The resulting matrix will have a size equal to (the number of rows of a) x (the number of columns b).
void MatrixMultiplication(int** a, int** b, int** result, int N_a,int M_a, int N_b, int M_b);
Step 12: When choice w is selected write the values currently stored in w to a file named resultMatrix.txt. To do this you will follow the below steps:
If c is NULL print an error message printf("Error -- results array not allocated ");
Otherwise, open a file resultMatrix.txt with the intent to write to the file (“w”).
If the file was not able to be opened print out error message printf("Error -- unable to open write file! ");
Otherwise, on the first line of the file print the number of rows in c, and then the number of columns.
Next print out the matrix one row at a time
Close the file
Print out the success message
Step 13: Create two text files and fill them with the following information: the first row will contain the number of rows and then the number of columns in a matrix separated by one space. The next rows of the file will contain all the elements in the matrix. We are going to assume that these files are always properly formatted in exactly this way (although this is rarely the case with input files!). Here is a picture of a sample file:
Sample outp[ut of sample file:
2 5
7 7 0 4 5
1 20 1 4 7
Step 14: For choice f, we are going to read in matrices to a and b from files given by the users. The outline of this will be very similar to the psuedocode given for step 5 (the random filled matrices), expect that now the values are coming from the file.
To store the user’s given filename we need a string variable char fname[128];
And we will fill this variable in the following way: printf("Enter file name for matrix 1: "); scanf("%s",fname); The user has to type in the extension of the file as well when they enter “.txt”
You can now open this file by trying
FILE *inputf; if((inputf=fopen(fname,"r")) == NULL) … //error occured
If the file cannot be opened print
printf("Error -- Unable to openfile! ");
Otherwise read the sizes of the matrices from line 1 of the file, and then allocate the arrays to the appropriate size, filling each row as you go by reading from the file.
Don’t forget to close the file when you are done.
You must include the following functions for full credit:
void PrintArray(int** arr, int N, int M);
void MatrixAddition(int** a, int** b, int** result, int N, int M);
void MatrixSubtraction(int** a, int** b, int** result, int N, int M);
void ScalarMultiplication(int scalar, int** a, int** result, int N,int M);
void MatrixMultiplication(int** a, int** b, int** result, int N_a, int M_a, int N_b, int M_b);
void MatrixTranspose(int** a, int** result, int N, int M);
void FreeArray(int** arr, int N);
Feel free to add another other functions that you find helpful, but be careful! Remember that memory allocated locally inside a functions can be garbage collected after your code “leaves” the function. So you may want to keep any parts of your code that allocate memory in the main.
ALLE PROGRAMMING MUST GBE IN THE C PROGRAMMING LANGUAGE
W> Write result matrix to file Q Quit Enter file name for matrix 1: matrixi.txt The fist array is: he first array is: 4 7 84 10 9 20 1 4 7 Ente file name for matrix 2: matrix1.txt The second array is: 47 8 4 10 9 20 1 4 7 Please select from the following: er file naneExplanation / Answer
Given below is the code fot the question. Please don't forget to rate the answer if it helped. Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void PrintArray(int** arr, int N, int M);
int** CreateArray(int N, int M);
void FreeArray(int** arr, int N);
void FillRandom(int **arr, int N, int M);
void MatrixAddition(int** a, int** b, int** result, int N, int M);
void MatrixSubtraction(int** a, int** b, int** result, int N, int M);
void ScalarMultiplication(int scalar, int** a, int** result, int N,int M);
void MatrixMultiplication(int** a, int** b, int** result, int N_a, int M_a, int N_b, int M_b);
void MatrixTranspose(int** a, int** result, int N, int M);
int WriteToFile(char *filename, int **arr, int N, int M);
int** LoadFromFile(char *filename, int *N, int *M);
int main()
{
int** a = NULL; int** b = NULL; int** c = NULL;
int N_a = 0, M_a = 0, N_b = 0, M_b = 0, N_c = 0, M_c = 0, N = 0;
int dataReadSuccess = 0;
int scalar;
char filename[30];
char choice[2];
srand(time(0));
while(choice[0] != 'Q' && choice[0] != 'q')
{
printf(" A) Matrix Addition ");
printf("B) Matrix Subtraction ");
printf("C) Scalar Multiplication ");
printf("D) Transpose ");
printf("E) Matrix Multiplication ");
printf("F) Fill matrices from file ");
printf("R) Fill matrices with random values ");
printf("W) Write result matrix to file ");
printf("Q) Quit ");
printf("Enter your choice: ");
scanf("%s", choice);
switch(choice[0])
{
case 'a':
case 'A': //addition
if(dataReadSuccess)
{
if(N_a == N_b && M_a == M_b)
{
if(c != NULL ) { FreeArray(c, N_c); c = NULL;}
N_c = N_a; M_c = M_a;
c = CreateArray(N_c, M_c);
MatrixAddition(a,b,c, N_a, M_a);
printf("A + B = ");
PrintArray(c, N_c, M_c);
}
else
{
printf("Error -- Size mismatch between matrix A and matrix B ");
}
}
else
printf("Error -- no data inputted. Please enter data... ");
break;
case 'b':
case 'B': //subtraction
if(dataReadSuccess)
{
if(N_a == N_b && M_a == M_b)
{
if(c != NULL ) { FreeArray(c, N_c); c = NULL;}
N_c = N_a; M_c = M_a;
c = CreateArray(N_c, M_c);
MatrixSubtraction(a,b,c, N_a, M_a);
printf("A - B = ");
PrintArray(c, N_c, M_c);
}
else
{
printf("Error -- Size mismatch between matrix A and matrix B ");
}
}
else
printf("Error -- no data inputted. Please enter data... ");
break;
case 'c':
case 'C': //scalar multiplication
if(dataReadSuccess)
{
if(c != NULL )
{ FreeArray(c, N_c); c = NULL;}
N_c = N_a; M_c = M_a;
c = CreateArray(N_c, M_c);
printf("Enter a scalar value: ");
scanf("%d", &scalar);
ScalarMultiplication(scalar, a, c, N_a, M_a);
printf("%d x A = ", scalar);
PrintArray(c, N_c, M_c);
}
else
printf("Error -- no data inputted. Please enter data... ");
break;
break;
case 'd':
case 'D'://transpose
if(dataReadSuccess)
{
if(c != NULL )
{ FreeArray(c, N_c); c = NULL;}
N_c = M_a; M_c = N_a;
c = CreateArray(N_c, M_c);
MatrixTranspose(a,c, N_a, M_a);
printf("A Transpose = ");
PrintArray(c, N_c, M_c);
}
else
printf("Error -- no data inputted. Please enter data... ");
break;
case 'e':
case 'E': //multiplication
if(dataReadSuccess)
{
if(M_a == N_b)
{
if(c != NULL ) { FreeArray(c, N_c); c = NULL;}
N_c = N_a; M_c = M_b;
c = CreateArray(N_c, M_c);
MatrixMultiplication(a,b,c, N_a, M_a,N_b, M_b);
printf("A x B = ");
PrintArray(c, N_c, M_c);
}
else
{
printf("Error -- No. of cols in matrix A should be same as number of rows in matrix B ");
}
}
else
printf("Error -- no data inputted. Please enter data... ");
break;
case 'r':
case 'R': //random matrices
dataReadSuccess = 0;
if(a != NULL ) {FreeArray(a, N_a); a = NULL;}
if(b != NULL ) {FreeArray(b, N_b); b= NULL;}
while(1)
{
printf("Enter value of N: ");
scanf("%d", &N);
if(N < 2)
printf("Error -- enter a positive size greater than equal to 2.");
else
break;
}
N_a = M_a = N_b = M_b = N;
a = CreateArray(N_a, M_a);
b = CreateArray(N_b, M_b);
if(a == NULL || b == NULL)
{
printf("Error -- Unable to allocate arrays ");
}
else
{
dataReadSuccess = 1;
FillRandom(a, N_a, M_a);
FillRandom(b, N_b, M_b);
printf("Matrix 1 ");
PrintArray(a, N_a, M_a);
printf("Matrix 2 ");
PrintArray(b, N_b, M_b);
}
break;
case 'f':
case 'F': //load from file
dataReadSuccess = 0;
if(a != NULL ) {FreeArray(a, N_a); a = NULL;}
if(b != NULL ) {FreeArray(b, N_b); b = NULL;}
printf("Enter file for matrix 1: ");
scanf("%s", filename);
a = LoadFromFile(filename, &N_a, &M_a);
printf("The first matrix is: ");
PrintArray(a, N_a, M_a);
printf("Enter file for matrix 2: ");
scanf("%s", filename);
b = LoadFromFile(filename, &N_b, &M_b);
printf("The second matrix is: ");
PrintArray(b, N_b, M_b);
if(a != NULL && b != NULL)
dataReadSuccess = 1;
break;
case 'w':
case 'W': //write to file
if(c == NULL)
printf("Error -- results array not allocated ");
else
{
if(WriteToFile("resultMatrix.txt", c, N_c, M_c))
printf("Result matrix written to file resultMatrix.txt ");
}
break;
case 'q':
case 'Q':
break;
default:
printf("Error -- Invalid choice! Please select again... ");
}
}
return 0;
}
int** CreateArray(int N, int M)
{
int i;
int **arr = NULL;
arr = (int **) malloc(N * sizeof(int *) ); //allocate space for rows
if(arr != NULL)
{
for(i = 0; i < N; i++)
{
arr[i] = (int *) malloc(M * sizeof(int));
if(arr[i] == NULL)
return NULL;
}
}
return arr;
}
void FreeArray(int** arr, int N)
{
int i;
if(arr == NULL) return;
if(arr != NULL)
{
for(i = 0; i<N; i++)
{
if(arr[i] != NULL) free(arr[i]);
}
free(arr);
}
}
void PrintArray(int** arr, int N, int M)
{
int i, j;
if(arr == NULL) return;
for(i = 0; i < N; i++)
{
for(j = 0; j < M; j++)
printf("%4d ", arr[i][j]);
printf(" ");
}
printf(" ");
}
void FillRandom(int **arr, int N, int M)
{
int i, j;
for(i = 0; i < N; i++)
for( j = 0; j < M; j++)
arr[i][j] = rand() % 10;
}
void MatrixAddition(int** a, int** b, int** result, int N, int M)
{
int i, j;
for(i = 0; i < N; i++)
for(j = 0; j < M; j++)
result[i][j] = a[i][j] + b[i][j];
}
void MatrixSubtraction(int** a, int** b, int** result, int N, int M)
{
int i, j;
for(i = 0; i < N; i++)
for(j = 0; j < M; j++)
result[i][j] = a[i][j] - b[i][j];
}
void ScalarMultiplication(int scalar, int** a, int** result, int N,int M)
{
int i, j;
for(i = 0; i < N; i++)
for(j = 0; j < M; j++)
result[i][j] = scalar * a[i][j];
}
void MatrixMultiplication(int** a, int** b, int** result, int N_a, int M_a, int N_b, int M_b)
{
int i, j, k;
for(i = 0; i < N_a; i++)
for(j = 0; j <M_b ; j++)
{
result[i][j] = 0;
for(k = 0; k < M_a; k++)
result[i][j] += a[i][k] * b[k][j];
}
}
void MatrixTranspose(int** a, int** result, int N, int M)
{
int i, j;
for(i = 0; i < N; i++)
for(j = 0; j < M; j++)
result[j][i] = a[i][j];
}
int WriteToFile(char *filename, int **arr, int N, int M)
{
FILE *fp = fopen(filename, "w");
int i, j;
if(fp == NULL)
{
printf("Error -- unable to open write file! ");
return 0;
}
else
{
fprintf(fp, "%d %d ", N, M);
for(i = 0; i < N; i++)
{
for(j = 0; j < M; j++)
fprintf(fp, "%4d ", arr[i][j]);
fprintf(fp, " ");
}
fclose(fp);
return 1;
}
}
int** LoadFromFile(char *filename, int *N, int *M)
{
int** arr = NULL;
int i, j;
int rows, cols;
FILE *fp = fopen(filename, "r");
if(fp == NULL)
printf("Could not load matrix from file %s ", filename);
else
{
fscanf(fp, "%d %d", &rows, &cols);
arr = CreateArray(rows, cols);
*N = rows;
*M = cols;
if(arr != NULL)
{
for(i = 0; i < rows; i++)
for(j = 0; j < cols; j++)
fscanf(fp,"%d", &arr[i][j]);
}
fclose(fp);
}
return arr;
}
output
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: a
Error -- no data inputted. Please enter data...
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: b
Error -- no data inputted. Please enter data...
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: c
Error -- no data inputted. Please enter data...
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: d
Error -- no data inputted. Please enter data...
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: e
Error -- no data inputted. Please enter data...
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: f
Enter file for matrix 1: matrix1.txt
The first matrix is:
1 2 3 4 5
6 7 8 9 0
Enter file for matrix 2: matrix2.txt
The second matrix is:
2 3 4 5 6
4 5 6 7 8
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: a
A + B =
3 5 7 9 11
10 12 14 16 8
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: b
A - B =
-1 -1 -1 -1 -1
2 2 2 2 -8
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: c
Enter a scalar value: 3
3 x A =
3 6 9 12 15
18 21 24 27 0
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: d
A Transpose =
1 6
2 7
3 8
4 9
5 0
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: e
Error -- No. of cols in matrix A should be same as number of rows in matrix B
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: r
Enter value of N: 2
Matrix 1
1 9
2 9
Matrix 2
1 3
1 0
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: e
A x B =
10 3
11 6
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: w
Result matrix written to file resultMatrix.txt
A) Matrix Addition
B) Matrix Subtraction
C) Scalar Multiplication
D) Transpose
E) Matrix Multiplication
F) Fill matrices from file
R) Fill matrices with random values
W) Write result matrix to file
Q) Quit
Enter your choice: q
output file: resultMatrix.txt
2 2
10 3
11 6
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.