K&R C Exercise 1-12: Print Input One Word Per Line

Exercise 1-12. Write a program that prints its input one word per line. Approach A word is any contiguous run of non-whitespace characters; spaces, tabs, and newlines are all separators. The challenge is not reading words — it is knowing when to emit the newline that separates them in the output. The solution borrows the …

K&R C Exercise 1-11: How to Test the Word Count Program

Exercise 1-11. How would you test the word count program? What kinds of input are most likely to uncover bugs if there are any? Exercise 1-11 has no new program to write. It asks you to think like a tester — to look at the word count program K&R presented in Section 1.5.4 and design …

K&R C Exercise 1-8: Count Blanks, Tabs, and Newlines

Exercise 1-8. Write a program to count blanks, tabs, and newlines. Approach The solution maintains three independent counters and reads one character at a time using the canonical getchar() loop. The key design decision is using three separate if statements rather than else if. In this case a character can only ever be one thing …

K&R C Exercise 1-7: Print the Value of EOF

Exercise 1-7. Write a program to print the value of EOF. This is one of those exercises that looks trivial — one printf and you’re done — but it opens the door to one of the most important design decisions in the C standard library. Before you can really understand why Chapter 1’s input loops …

K&R C Exercise 1-4: Celsius to Fahrenheit Table

Exercise 1-4. Write a program to print the corresponding Celsius to Fahrenheit table. Approach K&R Chapter 1 opens with a Fahrenheit-to-Celsius table, converting F values to Celsius using C = 5 × (F − 32) / 9. This exercise asks for the inverse: step through Celsius values (0, 20, 40, …, 300) and compute the …

K&R C Exercise 1-2: Escape Sequences in printf

Exercise 1-2. Experiment to find out what happens when printf‘s argument string contains \c, where c is some character not listed above. The escape sequences K&R lists in section 1.5 are: \n (newline), \t (tab), \b (backspace), \” (double quote), and \\ (backslash). The exercise asks what happens with everything else. Approach The key insight …