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 …

K&R C Exercise 2-7: invert — Flip n Bits at Position p

K&R C Exercise 2-7 — invert(x, p, n) Exercise 2-7: Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed to 0 and vice versa), leaving the others unchanged. Approach XOR is the natural bit-flip operator: b ^ 1 = ~b and b ^ 0 …

K&R C Exercise 2-6: setbits — Set n Bits at Position p

K&R C Exercise 2-6 — setbits(x, p, n, y) Exercise 2-6: Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged. Approach K&R numbers bit positions from the right starting at 0, so bit 0 is …