K&R C Chapter 1 Exercise Solutions — A Tutorial Introduction

Chapter 1: A Tutorial Introduction is where K&R C begins — and it moves faster than most C books. By exercise 1-8 you are counting characters by category; by 1-13 you are drawing histograms; by 1-22 you are folding long lines. The chapter uses only a tiny subset of C deliberately: loops, if/else, basic functions, …

K&R C Exercise 1-24: Rudimentary C Syntax Checker

Exercise 1-24. Write a program to check a C program for rudimentary syntax errors like unmatched parentheses, brackets, and braces. Don’t forget about quotes, both single and double, and comments. (This is hard to do in full generality.) Approach The obvious approach — keep a counter for each bracket type and check it reaches zero …

K&R C Exercise 1-23: Remove Comments from a C Program

Exercise 1-23. Write a program to remove all comments from a C program. Don’t forget to handle quoted strings and character constants properly. C comments don’t nest. Approach The core challenge is that the same character sequence means completely different things depending on context. A /* inside a string literal is not a comment. A …

K&R C Exercise 1-21: entab — Replace Spaces with Tabs

Exercise 1-21. Write a program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use the same tab stops as for detab. When either a tab or a single blank would suffice to reach a tab stop, which should be given preference? Approach entab is …

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 …