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, …

K&R C Programs Exercise 4-1

Exercise 4-1. Write the function strindex(s,t) that returns the position of the rightmost occurrence of t in s, or -1 if there is none. The K&R strindex in Section 4.1 returns the leftmost match by scanning left-to-right and returning at the first hit. For the rightmost match there are two symmetric approaches: scan right-to-left and …

K&R C Exercise 3-6: itoa with Minimum Field Width

Exercise 3-6. Write a version of itoa that accepts three arguments instead of two. The third argument is a minimum field width; the converted number must be padded with blanks on the left if necessary to make it wide enough. This is exactly what printf‘s %6d format does — the 6 is a minimum field …

K&R C Exercise 3-5: itob — Integer to Any Base String

Exercise 3-5. Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s. In particular, itob(n,s,16) should produce in s a hexadecimal string. itob generalises itoa from base 10 to any base 2–36. The only change to the digit-extraction loop is replacing n % 10 with n …