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 …

K&R C Exercise 3-1: Binary Search with One Comparison Per Loop

Exercise 3-1. Our binary search makes two tests inside the loop, when one would suffice (at the cost of more tests outside). Write a version with only one test inside the loop and measure the difference in run-time. The standard K&R binsearch performs two comparisons per iteration — it checks x < v[mid], then x …

K&R C Exercise 2-10: lower — Convert to Lowercase with Ternary

Exercise 2-10. Rewrite the function lower, which converts upper case letters to lower case, with a conditional expression instead of if-else. This exercise looks trivial on the surface — it is a one-liner. The real lesson is about the conditional (ternary) operator and what it means to choose it over if-else. K&R introduce the ternary …

K&R C Exercise 2-9: Count Set Bits Using x &= (x-1)

K&R C Exercise 2-9 — Faster bitcount Using x &= (x-1) Exercise 2-9: In a two’s complement number system, x &= (x-1) deletes the rightmost 1-bit in x. Explain why. Use this observation to write a faster version of bitcount. Why Does x &= (x-1) Delete the Rightmost 1-Bit? This is the conceptual heart of …

K&R C Exercise 2-8: rightrot — Rotate Bits Right

K&R C Exercise 2-8 — rightrot(x, n) Exercise 2-8: Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n bit positions. Approach A right rotation is different from a right shift. When you shift right by n, the n bits that fall off the right end are …