K&R C Exercise 2-3: htoi — Convert Hex String to Integer

Exercise 2-3. Write the function htoi(s), which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F. How htoi Works Hexadecimal is simply base-16 positional notation. Converting from a hex string to an integer …

K&R C Exercise 2-2: Loop Without && or ||

Exercise 2-2. Write a loop equivalent to the for loop below without using && or ||: for (i = 0; i < lim – 1 && (c = getchar()) != ‘\n’ && c != EOF; ++i) s[i] = c; Understanding the Problem The && operator in C is a short-circuit operator: if the left operand …

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 …