CS19002 Programming and Data Structures Laboratory, Section 5 |
Spring 2007 |
Exercise 1 | Exercise 2 | Exercise 3 | Exercise 4 | Exercise 5 | |
Solution 1 | Solution 2 | Solution 3 | Solution 4 | Solution 5 | |
Show all | Hide all |
Click on the links above
Exercise 1
Declare a structure to represent complex numbers. Dynamically allocate a memory of 100 complex structures. Store in the k-th index of the dynamic array the complex number k2 + i sqrt(k).
Solution 1
typedef struct { double re; double im; } complex; ... complex *p; int k; p = (complex *)malloc(100 * sizeof(complex)); for (k=0; k<100; ++k) { p[k].re = k * k; p[k].im = sqrt(k); }Exercise 2
Define the following structure to represent a 2-d integer matrix.
typedef struct { int r; int c; int elt[MAXDIM][MAXDIM]; } matrix;Write a function that accepts as input a dimension d (not bigger than MAXDIM) and returns the d x d identity matrix.
Solution 2
matrix setid ( int d ) { matrix M; int i, j; M.r = M.c = d; for (i=0; i<d; ++i) for (j=0; j<d; ++j) M.elt[i][j] = (i == j) ? 1 : 0; return M; }Exercise 3
Define a 2-d matrix with dynamic memory as follows:
typedef struct { int r; int c; int **elt; } matrix;Write a function that accepts as input a dimension d and returns the d x d identity matrix.
Solution 3
matrix setid ( int d ) { matrix M; int i, j; M.r = M.c = d; M.elt = (int **)malloc(d * sizeof(int *)); for (i=0; i<d; ++i) { M.elt[i] = (int *)malloc(d * sizeof(int)); for (j=0; j<0; ++j) M.elt[i][j] = (i == j) ? 1 : 0; } return M; }Exercise 4
Write a function that accepts two matrices and returns their product, provided that the input matrices are of compatible dimensions. Use the data type with static memory (as in Exercise 2).
Solution 4
matrix matmul ( matrix M, matrix N ) { int i, j, k; matrix P; if (M.c != N.r) { printf("Input matrices are of incompatible dimensions.\n"); P.r = P.c = 0; return P; } P.r = M.r; P.c = N.c; for (i=0; i<M.r; ++i) for (j=0; j<N.c; ++j) { P.elt[i][j] = 0; for (k=0; k<M.c; ++k) P.elt[i][j] += M.elt[i][k] * N.elt[k][j]; } return P; }Exercise 5
Write a main() function that supports the following command-line arguments: a positive integer n, and optionally another positive integer r. If r is not supplied, then the program takes the default value r=2. The program then prints the r-th root of n.
Solution 5
int main ( int argc, char *argv[] ) { int n, r; if (argc < 2) { fprintf(stderr,"Error: too few arguments\n"); exit(1); } n = atoi(argv[1]); if (argc > 2) r = atoi(argv[2]); else r = 2; printf("%d-th root of %d is %lf\n", r, n, pow((double)n,1.0/(double)r)); exit(0); }