CS 1723, FALL 1998, EXAM 2 ANSWERS -- ---- ---- ---- ---- - ------- PROBLEM 1: (a) 234*+ (* has precedence over +) (b) 43*2* (* associated left-to-right) 432^^ (^ associates right-to_left) -------------------------------------------------------- PROBLEM 2: runner% cat exam2_2.c #include #include #include struct lnode { char *word; struct lnode *next; }; struct lnode *insert(char *w, struct lnode *p); void printlist(struct lnode *); void printreverse(struct lnode *); void main(void) { struct lnode *p = NULL; char w[100]; while (scanf("%s", w) != EOF) p = insert(w, p); printlist(p); printreverse(p); printf("\n"); } struct lnode *insert(char *w, struct lnode *p) { struct lnode *r = (struct lnode *) malloc(sizeof(struct lnode)); r -> next = p; r -> word = malloc(strlen(w) + 1); strcpy(r -> word, w); return r; } void printlist(struct lnode *p) { while (p != NULL) { /* or just while (p) */ printf("%s ", p -> word); p = p -> next; } printf("\n"); } void printreverse(struct lnode *p) { if (p != NULL) { /* or just if (p) */ printreverse(p -> next); printf("%s ", p -> word); } } runner% cc -o exam2_2 exam2_2.c runner% exam2_2 Now is the time for all good men (ctrl-d) men good all for time the is Now Now is the time for all good men runner% -------------------------------------------------------- PROBLEM 3: runner% cat exam2_3.c * Weeks program */ #include void main(void) { int i; char *weeks[] = {"none", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", NULL}; char **p; for(i = 1; i < 8; i++) printf("%s ", weeks[i]); printf("\n"); for(i = 1; i < 8; i++) printf("%s ", *(weeks + i)); printf("\n"); p = &weeks[1]; /* or p = weeks + 1; */ while (*p != NULL) /* or while (*p) */ printf("%s ", *(p++)); /* or *p++ */ printf("\n"); } runner% cc -o exam2_3 exam2_3.c runner% exam2_3 Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun runner%