//C.S.P0035 #include #include #define MIN_VALUE -10000 #define MAX_VALUE 10000 int getInt(int, int); void importData(int *matrixA, int *matrixB, int, int); void add2Matrix(int *matrixA, int *matrixB, int *matrixC, int, int); void displayMatrix(int *matrixC, int, int); int main() { //the number of Matrix int nRow, nCol; int *matrixA, *matrixB, *matrixC; printf("Matrix Add\n"); printf("Accept size: \n"); printf("The number of row: "); nRow = getInt(0, 100); printf("The number of Column: "); nCol = getInt(0, 100); //declare 2 dimensional array by pointer (Matrix)- Func Malloc //virtual matrix matrixA = (int *) malloc(nRow * nCol * sizeof (int *)); matrixB = (int *) malloc(nRow * nCol * sizeof (int *)); matrixC = (int *) malloc(nRow * nCol * sizeof (int *)); //Import Data to matrix A, B importData(matrixA, matrixB, nRow, nCol); //add & display sum of 2 matrix add2Matrix(matrixA, matrixB, matrixC, nRow, nCol); displayMatrix(matrixC, nRow, nCol); return 0; } int getInt(int minValue, int maxValue) { int value; char check; //42a do { int rc = scanf("%d%c", &value, &check); // fflush(stdin); fpurge(stdin); if (rc != 2 || check != '\n') { printf("Invalid value!\n"); } else if (value < minValue || value > maxValue) { printf("Value out of range!\n"); } else { // rc == 2 && check == '\n' return value; //break out of function } } while (1); } void importData(int *matrixA, int *matrixB, int nRow, int nCol) { int iRow, iCol; //Input value to matrix //MatrixA printf("Accept matrix m1:\n"); for (iRow = 0; iRow < nRow; iRow++) { for (iCol = 0; iCol < nCol; iCol++) { printf("matrixA[%d][%d] = ", iRow, iCol); *(matrixA + iRow * nCol + iCol) = getInt(MIN_VALUE, MAX_VALUE); } } //MatrixB printf("Accept matrix m2:\n"); for (iRow = 0; iRow < nRow; iRow++) { for (iCol = 0; iCol < nCol; iCol++) { printf("matrixB[%d][%d] = ", iRow, iCol); *(matrixB + iRow * nCol + iCol) = getInt(MIN_VALUE, MAX_VALUE); } } } void add2Matrix(int *matrixA, int *matrixB, int *matrixC, int nRow, int nCol) { int iRow, iCol; for (iRow = 0; iRow < nRow; iRow++) { for (iCol = 0; iCol < nCol; iCol++) { *(matrixC + iRow * nCol + iCol) = *(matrixA + iRow * nCol + iCol) + *(matrixB + iRow * nCol + iCol); } } } void displayMatrix(int *matrixC, int nRow, int nCol) { int iRow, iCol; printf("m = m1 + m2:\n"); for (iRow = 0; iRow < nRow; iRow++) { for (iCol = 0; iCol < nCol; iCol++) { printf("%-7d", *(matrixC + iRow * nCol + iCol)); } printf("\n"); } }