K&R C Programs Exercise 5-3

Exercise 5-3. Write a pointer version of the function strcat that we showed in Chapter 2: strcat(s,t) copies the string t to the end of s. The Chapter 2 version used array indexing with integer subscripts. The pointer version eliminates the index variables entirely: advance s to its null terminator, then copy t character-by-character (including …

K&R C Programs Exercise 5-2

Exercise 5-2. Write getfloat, the floating-point analog of getint. What type does getfloat return as its function value? getfloat returns int — the same as getint. This might seem surprising since it reads a double. The return value is used as a status indicator: it returns the terminating non-numeric character (so the caller can check …

K&R C Programs Exercise 5-1

Exercise 5-1. As written, getint treats a + or – not followed by a digit as a valid representation of zero. Fix getint so that it pushes such a character back on the input. K&R’s getint from Section 5.2 reads an optional sign then digits. The bug: if + or – appears but the next …

K&R C Programs Exercise 4-14

Exercise 4-14. Define a macro swap(t,x,y) that interchanges two arguments of type t. (Block structure will help.) A three-argument swap macro: t is the type, x and y are the variables to swap. The block { … } creates a local scope for the temporary, preventing name leakage. The conventional temp variable name _swap_tmp (with …

K&R C Programs Exercise 4-13

Exercise 4-13. Write a recursive version of the function reverse(s), which reverses the string s in place. An iterative reverse uses two indices walking inward from both ends, swapping until they meet. The recursive version does the same with the call stack: each call receives left and right indices, swaps those two characters, then recurses …

K&R C Programs Exercise 4-12

Exercise 4-12. Adapt the ideas of printd to write a recursive version of itoa; that is, convert an integer into a string by calling a recursive routine. K&R’s printd (Section 4.10) prints a number recursively: recurse on n/10 to print all leading digits first, then putchar(n%10 + ‘0’) on the way back up. itoa must …