K&R C Programs Exercise 4-1

Exercise 4-1. Write the function strindex(s,t) that returns the position of the rightmost occurrence of t in s, or -1 if there is none. The K&R strindex in Section 4.1 returns the leftmost match by scanning left-to-right and returning at the first hit. For the rightmost match there are two symmetric approaches: scan right-to-left and …

K&R C Exercise 3-6: itoa with Minimum Field Width

Exercise 3-6. Write a version of itoa that 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. This is exactly what printf‘s %6d format does — the 6 is a minimum field …

K&R C Exercise 3-5: itob — Integer to Any Base String

Exercise 3-5. Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s. In particular, itob(n,s,16) should produce in s a hexadecimal string. itob generalises itoa from base 10 to any base 2–36. The only change to the digit-extraction loop is replacing n % 10 with n …

K&R C Exercise 3-4: itoa — Handle INT_MIN in Integer to String

Exercise 3-4. In a two’s complement number representation, our version of itoa does not handle the largest negative number, that is, the value of n equal to −(2wordsize−1). Explain why not. Modify it to print that value correctly, regardless of the machine on which it runs. This exercise has two parts: explain the bug, then …

K&R C Exercise 3-3: expand — Expand a-z Shorthand into Full Range

Exercise 3-3. Write a function expand(s1,s2) that expands shorthand notations like a-z in the string s1 into the equivalent complete list abc…xyz in s2. Allow for letters or digits on either end of a range, and take care of cases like a-b-c and a-z0-9 and -a. Arrange that a leading or trailing – is taken …

K&R C Exercise 3-2: escape — Convert Special Characters to Escape Sequences

Exercise 3-2. Write a function escape(s,t) that converts characters like newline and tab into visible escape sequences like \n and \t as it copies the string t to s. Use a switch. Write a function for the other direction as well, converting escape sequences into the real characters. Two functions walking their input strings character …