Chapter 2: Types, Operators, and Expressions covers C’s type system and operators in depth. The exercises focus on bitwise manipulation — rotating bits, setting and clearing fields, counting set bits — and type-conversion edge cases. Exercise 2-9 (x &= (x-1) deletes the rightmost 1-bit) is a classic bit-manipulation trick worth memorising.
These are worked solutions to all 10 exercises. Each solution compiles cleanly with gcc -ansi -Wall.
Book: The C Programming Language, 2nd Ed — Kernighan & Ritchie | All chapters index
Exercises
-
Exercise 2-1. Write a program to determine the ranges of
char,short,int, andlongvariables, bothsignedandunsigned, by printing appropriate values from standard headers and by direct computation. -
Exercise 2-2. Write a loop equivalent to the
forloop above without using&&or||. -
Exercise 2-3. Write the function
htoi(s), which converts a string of hexadecimal digits (including an optional0xor0X) into its equivalent integer value. The allowable digits are 0 through 9,athroughf, andAthroughF. -
Exercise 2-4. Write an alternate version of
squeeze(s1,s2)that deletes each character ins1that matches any character in the strings2. -
Exercise 2-5. Write the function
any(s1,s2), which returns the first location in the strings1where any character from the strings2occurs, or -1 ifs1contains no characters froms2. -
Exercise 2-6. Write a function
setbits(x,p,n,y)that returnsxwith the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged. -
Exercise 2-7. Write a function
invert(x,p,n)that returnsxwith the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged. -
Exercise 2-8. Write a function
rightrot(x,n)that returns the value of the integerxrotated to the right by n bit positions. -
Exercise 2-9. In a two’s complement number system,
x &= (x-1)deletes the rightmost 1-bit inx. Explain why. Use this observation to write a faster version ofbitcount. -
Exercise 2-10. Rewrite the function
lower, which converts upper case letters to lower case, with a conditional expression instead ofif-else.
See also: K&R C — All Chapters Index | Complete C Programs List