Chapter 4: Functions and Program Structure is where K&R builds a non-trivial program: a reverse Polish notation (RPN) calculator. The exercises extend it — adding modulo, unary minus, variables, and last-printed-value recall. Other exercises cover recursive printd, recursive itoa, and the C preprocessor. Exercise 4-12 (recursive itoa) and 4-13 (recursive reverse) are elegance tests.
These are worked solutions to all 14 exercises. Each solution compiles cleanly with gcc -ansi -Wall.
Book: The C Programming Language, 2nd Ed — Kernighan & Ritchie | All chapters index
Exercises
-
Exercise 4-1. Write the function
strindex(s,t)that returns the position of the rightmost occurrence oftins, or -1 if there is none. -
Exercise 4-2. Extend
atofto handle scientific notation of the form123.45e-6where a floating-point number may be followed byeorEand an optionally signed exponent. -
Exercise 4-3. Given the basic framework, it’s straightforward to extend the calculator. Add the modulus (
%) operator and provisions for negative numbers. -
Exercise 4-4. Add commands to print the top element of the stack without popping it, to duplicate it, and to swap the top two elements. Add a command to clear the stack.
-
Exercise 4-5. Add access to library functions like
sin,cos,exp, andpow. See<math.h>in Appendix B, Section 4. -
Exercise 4-6. Add commands for handling variables. (It’s easy to provide twenty-six variables with single-letter names.) Add a variable for the most recently printed value.
-
Exercise 4-7. Write a routine
ungets(s)that pushes the entire stringsback onto the input. Shouldungetsknow aboutbufandbufp, or should it just useungetch? -
Exercise 4-8. Suppose that there will never be more than one character of pushback. Modify
getchandungetchaccordingly. -
Exercise 4-9. Our
getchandungetchdo not handle a pushed-backEOFcorrectly. Decide what their properties should be if anEOFis pushed back, then implement your decision. -
Exercise 4-10. An alternate organization uses
getlineto read an entire input line; this makesgetchandungetchunnecessary. Revise the calculator to use this approach. -
Exercise 4-11. Modify
getopso that it doesn’t need to useungetch. Hint: use an internal static variable. -
Exercise 4-12. Adapt the ideas of
printdfor writing a recursive version ofitoa; that is, convert an integer into a string by calling a recursive routine. -
Exercise 4-13. Write a recursive version of the function
reverse(s), which reverses the stringsin place. -
Exercise 4-14. Define a macro
swap(t,x,y)that interchanges two arguments of typet. (Block structure will help.)
See also: K&R C — All Chapters Index | Complete C Programs List