K&R C Exercise 2-1: Determine Ranges of Integer Types

Exercise 2-1. Write a program to determine the ranges of char, short, int, and long variables, both signed and unsigned, by printing appropriate values from standard headers and by direct computation. Harder if you compute them: determine the ranges of the various floating-point types. Approach The exercise splits neatly into two halves. The straightforward half …

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-22: Fold Long Lines at Word Boundaries

Exercise 1-22. Write a program to “fold” long lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something intelligent with very long lines, and if there are no blanks or tabs before the specified column. Line folding is the …

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-20: detab — Replace Tabs with Spaces

Exercise 1-20. Write a program detab that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns. Should n be a variable or a symbolic parameter? Approach The key insight is that a tab does not …