K&R C Programs Exercise 7-5

Exercise 7-5. Rewrite the postfix calculator of Chapter 4 to use scanf and/or sscanf to do the input and number conversion. The original Chapter 4 calculator used a custom getop() that read characters one at a time with getch/ungetch to recognise numbers vs operators. With scanf we replace that with a simpler approach: read one …

K&R C Programs Exercise 7-3

Exercise 7-3. Revise minprintf to handle more of the other facilities of printf. K&R’s minprintf (Section 7.3) handles only %d and %s. The cleanest way to extend it: as we parse the format string, collect the complete format specifier (flags, width, precision, length modifier, conversion character) into a local buffer, then call printf with that …

K&R C Programs Exercise 7-2

Exercise 7-2. Write a program that will print arbitrary input in a sensible way. As a minimum it should print non-graphic characters in octal or hex (according to local custom), and fold long lines. The rules: Printable characters (isprint) pass through as-is \n resets the column counter; \t and other non-printable characters are shown as …

K&R C Programs Exercise 6-6

Exercise 6-6. Implement a simple version of the #define processor (i.e., no arguments) suitable for use with C programs, based on the routines of this section. You may also find getch and ungetch useful. The processor reads C source line by line. When it sees #define NAME replacement it calls install from the hash table …

K&R C Programs Exercise 6-5

Exercise 6-5. Write a function undef that will remove a name and definition from the table maintained by lookup and install. K&R Section 6.6 presents a hash table with separate chaining: an array of HASHSIZE buckets, each being the head of a linked list of struct nlist nodes. install adds a name/definition pair; lookup finds …

K&R C Programs Exercise 6-4

Exercise 6-4. Write a program that prints the distinct words in its input sorted into decreasing order of frequency of occurrence. Precede each word by its count. Count words using K&R’s binary tree (Section 6.5), then collect all nodes into an array and sort by count descending using qsort. The key insight: the tree is …