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 …

K&R C Exercise 1-19: Reverse a String in C

Exercise 1-19. Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time. Approach The core algorithm is the classic two-pointer swap: place one index at the start of the string (i = 0) and one at the end (j = …

K&R C Exercise 1-17: Print Lines Longer Than 80 Characters

Exercise 1-17. Write a program to print all input lines that are longer than 80 characters. Approach This exercise is a direct application of the getline / main pattern introduced in K&R Section 1.9 — but now with a filter condition added to main. The key insight is that getline already returns the line length, …

K&R C Exercise 1-16: Print True Length of Long Input Lines

Exercise 1-16. Revise the main routine of the longest-line program so it will correctly print the length of arbitrarily long input lines, and as much as possible of the text. The K&R longest-line program (Section 1.9) stores each input line in a fixed buffer of MAXLINE characters. That design silently truncates any line longer than …

K&R C Exercise 1-15: Rewrite Temperature Conversion Using a Function

Exercise 1-15. Rewrite the temperature conversion program of Section 1.2 to use a function. Section 1.2 of K&R embeds the conversion formula directly inside main. It works — but it ties the formula to one spot in the code. This exercise asks you to extract that logic into a separate function called celsius. The payoff …