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-18: Remove Trailing Blanks and Delete Blank Lines

Exercise 1-18. Write a program to remove trailing blanks and tabs from each line of input, and delete entirely blank lines. The challenge here is that you cannot know whether a blank or tab is “trailing” until you have seen everything that follows it on the same line. The solution splits the work into two …

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 …

K&R C Exercise 1-14: Histogram of Character Frequencies

Exercise 1-14. Write a program to print a histogram of the frequencies of different characters in its input. Approach The key insight here is one of the most elegant idioms in C: a character read from getchar() is already an integer — its ASCII value. That value falls in the range 0–127, so it can …