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
Write a structure to represent an element of the form a+sqrt(-2)b for integer values a and b. Write a C function that takes two such complex numbers and returns the product of these numbers in the same form.
Solution 1
typedef struct { int a; int b; } comp2; comp2 mul ( comp2 z1 , comp2 z2 ) { comp2 z; z.a = (z1.a)*(z2.a) - 2*(z1.b)*(z2.b); z.b = (z1.a)*(z2.b) + (z1.b)*(z2.a); return z; }Exercise 2
Consider the following type definitions.
typedef struct { char name[80]; char rollno[8]; float cgpa; } stud1; typedef struct { char *name; char *rollno; float cgpa; } stud2; typedef stud1 *stud1ptr; typedef stud2 *stud2ptr; typedef stud1 stud1arr[100]; typedef stud2 stud2arr[100];Assume that a pointer is of size 32 bits. Determine the following sizes:
sizeof(stud1) sizeof(stud2) sizeof(stud1ptr) sizeof(stud2ptr) sizeof(stud1arr) sizeof(stud2arr)Solution 2
sizeof(stud1) = 80 + 8 + 4 = 92 sizeof(stud2) = 4 + 4 + 4 = 12 sizeof(stud1ptr) = 4 sizeof(stud2ptr) = 4 sizeof(stud1arr) = 92 x 100 = 9200 sizeof(stud2arr) = 12 x 100 = 1200Exercise 3
Write a C function that accepts a non-empty array of complex numbers and returns the array element having the maximum magnitude.
Solution 3
typedef struct { double re; double im; } complex; complex maxmag ( complex A[] , int n ) { int i, maxidx; double t, max; max = A[0].re * A[0].re + A[0].im * A[0].im; maxidx = 0; for (i = 1; i < n; ++i) { t = A[i].re * A[i].re + A[i].im * A[i].im; if (t > max) { max = t; maxidx = i; } } return A[maxidx]; }Exercise 4
Consider a student record of the form:
typedef struct { char *name; char *rollno; float cgpa; } strud;Write a C function that accepts two strings and a floating point number, allocates the exact amount of memory in a stud data type in order to store the name and the roll number, populates the structure with the arguments and returns the structure. Also show a sample way of calling this function with some constant arguments.
Solution 4
stud init ( char *nptr, char *rptr, float c ) { stud s; s.name = (char *)malloc((strlen(nptr)+1)*sizsof(char)); s.rollno = (char *)malloc((strlen(rptr)+1)*sizsof(char)); strcpy(s.name,nptr); strcpy(s.rollno,rptr); s.cgpa = c; return s; } ... init("Foolan Barik", "07FB1331", 9.89);Exercise 5
Consider a linked list with each node containing the following fields:
typedef struct _node { int key; int flag; struct _node *next; } node; typedef node *nodep;Write a function that accepts a header of type nodep to a linked list and that finds the sum of the key values stored in only those nodes in the linked list for which the flag values are non-zero.
Solution 5
int sum ( nodep p ) { int sum = 0; while (p != NULL) { if (p -> flag) sum += p -> key; p = p -> next; } return sum; }