K&R C Programs Exercise 4-7

Exercise 4-7. Write a routine ungets(s) that will push back an entire string onto the input. Should ungets know about buf and bufp, or should it just use ungetch? The answer is: ungets should use ungetch, not access buf and bufp directly. This is the principle of information hiding — getch and ungetch own the …

K&R C Programs Exercise 4-6

Exercise 4-6. Add commands for handling variables. (It’s easy to provide for twenty-six variables with single-letter names.) Add a variable for the most recently printed value. Twenty-six variables map naturally to an array var[26] indexed by c – ‘a’. The protocol: a lowercase letter pushes its variable’s value; = assigns the top of the stack …

K&R C Programs Exercise 4-5

Exercise 4-5. Add access to library functions like sin, cos, exp, and pow. See <math.h> in Appendix B, Section 4. Math functions need the calculator to recognize words as well as single characters. getop currently returns one character at a time. The fix: if getop sees a letter, it reads the whole word into s[] …

K&R C Programs Exercise 4-4

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. Four new commands, each operating directly on the stack array. None requires new data structures — just index arithmetic on val[] and sp. …

K&R C Programs Exercise 4-3

Exercise 4-3. Given the basic framework, it’s straightforward to extend the calculator. Add the modulus (%) operator and provisions for negative numbers. This exercise extends the RPN desk calculator from K&R Section 4.3. Two independent additions: Modulus operator % — pop two operands, cast to int, apply %, push result. Floating-point modulus is mathematically well-defined …

K&R C Programs Exercise 4-2

Exercise 4-2. Extend atof to handle scientific notation of the form 123.45e-6 where a floating-point number may be followed by e or E and an optionally signed exponent. The K&R atof in Section 4.2 handles sign, integer part, and fractional part. Scientific notation adds a third stage: after the mantissa, look for e or E, …