Chapter 3: Control Flow covers C’s branching and looping constructs. It is short (6 exercises) but the exercises are non-trivial: exercise 3-3 implements expand(s1,s2) to expand shorthand like a-z into the full alphabet; 3-4 handles itoa for the most negative integer (a classic overflow trap); 3-5 converts integers to arbitrary bases.
These are worked solutions to all 6 exercises. Each solution compiles cleanly with gcc -ansi -Wall.
Book: The C Programming Language, 2nd Ed — Kernighan & Ritchie | All chapters index
Exercises
-
Exercise 3-1. Our binary search makes two tests inside the loop, when one would suffice (at the price of more tests outside). Write a version with only one test inside the loop and measure the difference in run-time.
-
Exercise 3-2. Write a function
escape(s,t)that converts characters like newline and tab into visible escape sequences like\nand\tas it copies the stringttos. Use aswitch. Write a function for the other direction as well, converting escape sequences into the real characters. -
Exercise 3-3. Write a function
expand(s1,s2)that expands shorthand notations likea-zin the strings1into the equivalent complete listabc...xyzins2. Allow for letters of either case and digits, and be prepared to handle cases likea-b-canda-z0-9and-a-z. -
Exercise 3-4. In a two’s complement number representation, our version of
itoadoes not handle the largest negative number, that is, the value ofnequal to-(2^(wordsize-1)). Explain why not. Modify it to print that value correctly, regardless of the machine it runs on. -
Exercise 3-5. Write the function
itob(n,s,b)that converts the integerninto a basebcharacter representation in the strings. In particular,itob(n,s,16)formatsnas a hexadecimal integer ins. -
Exercise 3-6. Write a version of
itoathat accepts three arguments instead of two. The third argument is a minimum field width; the converted number must be padded with blanks on the left if necessary to make it wide enough.
See also: K&R C — All Chapters Index | Complete C Programs List