I need to use the same user defined function in C, for adding and subtracting matrices in C.
This should be the code I need to declare
void matrixAddSub(int arrayone[10][10], int arraytwo[10][10], int rows, int colums);
right now I'm declaring two functions
void matrixAdd(int arrayone[10][10], int arraytwo[10][10], int rows, int colums);
void matrixSub(int arrayone[10][10], int arraytwo[10][10], int rows, int colums);
When I debug my code it does the work but I need to reduce the amount of code that I have type. Here's my code definition.
void matrixAdd(int arrayone[10][10], int arraytwo[10][10], int rows, int colums){
int i, j;
int sumM[10][10];
for (i = 0; i < rows; i++){
for (j = 0; j < colums; j++){
sumM[i][j] = arrayone[i][j] + arraytwo[i][j];
printf("\t%d", sumM[i][j]);
}
printf("\n");
}
}
void matrixSub(int arrayone[10][10], int arraytwo[10][10], int rows, int colums){
int i, j;
int sumM[10][10];
for (i = 0; i < rows; i++){
for (j = 0; j < colums; j++){
sumM[i][j] = arrayone[i][j] - arraytwo[i][j];
printf("\t%d", sumM[i][j]);
}
printf("\n");
}
}
UPDATE
dasblinkenlight Here's what I end up doing with your suggestions:
Declared in main function int add =1; int sub = -1;
//user defined functions declaration
void matrixAddSub(int arrayone[10][10], int arraytwo[10][10], int rows, int colums, int mul);
//user defined function definition
void matrixAddSub(int arrayone[10][10], int arraytwo[10][10], int rows, int colums, int mul){
int i, j;
int sumM[10][10];
int scaM[10][10];
for (i = 0; i < rows; i++){
for (j = 0; j < colums; j++){
scaM[i][j] = mul * arraytwo[i][j];
}
}
for (i = 0; i < rows; i++){
for (j = 0; j < colums; j++){
sumM[i][j] = arrayone[i][j] + scaM[i][j];
printf("\t%d", sumM[i][j]);
}
printf("\n");
}
}
Consider:
-1
. Use these two facts to unify addition and subtraction. Write the following function:
static void matrixAddOrSubtract(
int arrayone[10][10]
, int arraytwo[10][10]
, size_t rows
, size_t columns
, int mul); // Multiply arraytwo[i][j] by mul before adding to arrayone[i][j]
Now both of your functions could be re-written as single-line invocations of matrixAddOrSubtract
:
void matrixAdd(int arrayone[10][10], int arraytwo[10][10], size_t rows, size_t columns) {
matrixAddOrSubtract(arrayone, arraytwo, rows, columns, 1);
}
void matrixSub(int arrayone[10][10], int arraytwo[10][10], size_t rows, size_t columns) {
matrixAddOrSubtract(arrayone, arraytwo, rows, columns, -1);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.