/* matrix.c - Let's practice matrix operations. * The user supplies the number of rows/cols of a SQUARE matrix. * The program will generate random values for two n*n matrices. * We'll add and multiply them. * This is a only a serial implementation. */ #include #include #include // Each number is printed in a field width of 4. // Feel free to reduce this for larger arrays. void print_array(int ** a, int size) { int i, j; for (i = 0; i < size; ++i) { for (j = 0; j < size; ++j) printf("%4d", a[i][j]); printf("\n"); } printf("\n"); } main(int argc, char **argv) { int n, **a, **b, **sum, **prod, i, j, k; if (argc != 2) { printf("You need to tell me the matrix size.\n"); exit(1); } n = atoi(argv[1]); srand(time(NULL)); // Initialize a = (int **) malloc (n * sizeof (int *)); b = (int **) malloc (n * sizeof (int *)); sum = (int **) malloc (n * sizeof (int *)); prod = (int **) malloc (n * sizeof (int *)); for (i = 0; i < n; ++i) { a[i] = (int *) malloc (n * sizeof (int)); b[i] = (int *) malloc (n * sizeof (int)); sum[i] = (int *) malloc (n * sizeof (int)); prod[i] = (int *) malloc (n * sizeof (int)); for (j = 0; j < n; ++j) { a[i][j] = rand() % 4; b[i][j] = rand() % 4; // If desired, could also initialize sum and prod entries to zero. } } // Sum for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) sum[i][j] = a[i][j] + b[i][j]; // Product for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) { prod[i][j] = 0; for (k = 0; k < n; ++k) prod[i][j] += a[i][k] * b[k][j]; } // Output print_array(a, n); print_array(b, n); print_array(sum, n); print_array(prod, n); // De-allocate or free the memory! for (i = 0; i < n; ++i) { free(a[i]); free(b[i]); free(sum[i]); free(prod[i]); } free(a); free(b); free(sum); free(prod); } /* Example output: 3 2 3 3 1 0 2 1 1 1 2 2 0 2 2 0 3 0 4 4 5 3 3 2 2 4 1 3 19 10 3 8 8 2 9 6 */