Kernighan and Ritchie problems solution
If you have an a.out file and don’t know what to do with it, try:
./a.out
Page 29
#include <stdio.h>
#define LOWER 0
#define UPPER 300
#define STEP 20
/* Named constants */
int main(void)
{
int fahr;
for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
printf("%5d %10.1f\n", fahr, 5.0 / 9.0 * (fahr - 32.0));
return 0;
}
gcc -std=c17 -Wall -Wextra -Wpedantic p29.c -o p29
./p29
0 -17.8 20 -6.7 40 4.4 60 15.6 80 26.7 100 37.8 120 48.9 140 60.0 160 71.1 180 82.2 200 93.3 220 104.4 240 115.6 260 126.7 280 137.8 300 148.9
Page 34, paragraph 1.5.3 Counting lines.
if (c == '\n')
Not some mysterious V.
Page 35, exercise 1.8. You need to write a program to count tabs, spaces and new lines.
I wrote two options. One works right.
#include <stdio.h>
/* calculation of spaces, tabs and new lines of input stream */
int main(void)
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
return 0;
}
Run it on three lines of input:
gcc -std=c17 -Wall -Wextra -Wpedantic count.c -o count
printf 'one\ntwo\nthree\n' | ./count
3
The other one counts everything.
Blue says that the if condition here is always TRUE.
The last character in the condition if (c == '\n', '\t', ' ') is considered logical by the compiler.
In ASCII, the space value is 32. 32 > 0, anything more than zero counts as TRUE, i.e. any symbol contributes to the sum.
I checked, if you put just zero there, then nothing will be displayed. Zero is FALSE.
#include <stdio.h>
/* count spaces, tabs and new lines of the input stream */
int main(void)
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n', '\t', ' ')
++nl;
printf("%d\n", nl);
return 0;
}
With the comma operator the condition is the last value only, so every character counts. For the input one two three the program prints 14, the length of the input, not 3:
gcc -std=c17 -Wall -Wextra -Wpedantic count_all_bad.c -o count_all_bad
printf 'one two\tthree\n' | ./count_all_bad
14
The correct condition compares each character separately:
if (c == '\n' || c == '\t' || c == ' ')
That prints 3 for the same input.
Exercise Solutions from Book B. Kernighan and D. Ritchie.
"The C Programming Language"
These are my solutions, at 99%, so they may be quite hacky.
Found a websitewhere solutions are also posted.
1.15
#include <stdio.h>
float ffahr(int c);
int main(void)
{
int cel, i;
for (i = 0; i < 20; ++i) {
cel = i * 10;
printf("%d %f\n", cel, ffahr(cel));
}
return 0;
}
float ffahr(int c)
{
float fahr;
fahr = (9.0 / 5.0) * c + 32.0;
return fahr;
}
gcc -std=c17 -Wall -Wextra -Wpedantic ffahr.c -o ffahr
./ffahr
0 32.000000 10 50.000000 20 68.000000 30 86.000000 40 104.000000 50 122.000000 60 140.000000 70 158.000000 80 176.000000 90 194.000000 100 212.000000 110 230.000000 120 248.000000 130 266.000000 140 284.000000 150 302.000000 160 320.000000 170 338.000000 180 356.000000 190 374.000000
1.17
#include <stdio.h>
#define MAXLINE 1000 /* maximum line length in stream */
#define LIMIT 80
int fgetline(char line[], int maxline);
/* print every line longer than LIMIT characters */
int main(void)
{
int len; /* the length of the current line */
char line[MAXLINE]; /* current input line */
while ((len = fgetline(line, MAXLINE)) > 0)
if (len > LIMIT)
printf("%s", line);
return 0;
}
/* fgetline: read a line into s, return its length */
int fgetline(char s[], int lim)
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
The first line below is short and stays out; the second is 88 characters long and is printed.
gcc -std=c17 -Wall -Wextra -Wpedantic p117.c -o p117
printf 'short line\nC is a small language, but a long line of text like this one still has to be folded somewhere.\n' | ./p117
C is a small language, but a long line of text like this one still has to be folded somewhere.
1.18
#include <stdio.h>
#define MAXLINE 1000
int fgetline(char line[], int maxline);
/* remove trailing blanks and tabs from every input line */
int main(void)
{
int len;
char line[MAXLINE];
while ((len = fgetline(line, MAXLINE)) > 0) {
while (len > 0 && (line[len - 1] == ' ' || line[len - 1] == '\t' || line[len - 1] == '\n'))
--len;
line[len] = '\0';
printf("%s\n", line);
}
return 0;
}
int fgetline(char s[], int lim)
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
1.19
#include <stdio.h>
#define MAXLINE 1000
int fgetline(char line[], int maxline);
void reverse(char s[]);
/* reverse every line of the input */
int main(void)
{
int len;
char line[MAXLINE];
while ((len = fgetline(line, MAXLINE)) > 0) {
if (len > 0 && line[len - 1] == '\n')
line[--len] = '\0';
reverse(line);
printf("%s\n", line);
}
return 0;
}
/* reverse: reverse the string s in place */
void reverse(char s[])
{
int i, j;
char temp;
i = 0;
while (s[i] != '\0')
++i;
--i;
for (j = 0; j < i; ++j, --i) {
temp = s[j];
s[j] = s[i];
s[i] = temp;
}
}
int fgetline(char s[], int lim)
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
gcc -std=c17 -Wall -Wextra -Wpedantic p119.c -o p119
printf 'hello\nabc\n' | ./p119
olleh cba
1.20
#include <stdio.h>
#define TABSTOP 8
/* replace tabs with the number of spaces up to the next tab stop */
int main(void)
{
int c, col, spaces;
col = 0;
while ((c = getchar()) != EOF) {
if (c == '\t') {
spaces = TABSTOP - col % TABSTOP;
while (spaces-- > 0) {
putchar(' ');
++col;
}
} else {
putchar(c);
if (c == '\n')
col = 0;
else
++col;
}
}
return 0;
}
1.22
#include <stdio.h>
#include <string.h>
#define MAXLINE 1000
#define WIDTH 20
int fgetline(char line[], int maxline);
/* fold long input lines after the last blank before column WIDTH */
int main(void)
{
int len, start, end, cut;
char line[MAXLINE];
while ((len = fgetline(line, MAXLINE)) > 0) {
if (len > 0 && line[len - 1] == '\n')
line[--len] = '\0';
start = 0;
while (start < len) {
end = start + WIDTH;
if (end >= len) {
printf("%s\n", line + start);
break;
}
cut = end;
while (cut > start && line[cut] != ' ' && line[cut] != '\t')
--cut;
if (cut == start)
cut = end;
line[cut] = '\0';
printf("%s\n", line + start);
start = cut + 1;
}
}
return 0;
}
int fgetline(char s[], int lim)
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
1.23
#include <stdio.h>
/* strip both comment styles from a C source file */
int main(void)
{
int c, d, state;
state = 0;
while ((c = getchar()) != EOF) {
if (state == 0) {
if (c == '"' || c == '\'') {
state = c;
putchar(c);
} else if (c == '/') {
d = getchar();
if (d == '/') {
state = 3;
} else if (d == '*') {
state = 4;
} else {
putchar(c);
if (d != EOF)
putchar(d);
}
} else {
putchar(c);
}
} else if (state == '"' || state == '\'') {
putchar(c);
if (c == '\\') {
d = getchar();
if (d != EOF)
putchar(d);
} else if (c == state) {
state = 0;
}
} else if (state == 3) {
if (c == '\n') {
putchar(c);
state = 0;
}
} else if (state == 4) {
if (c == '*') {
d = getchar();
if (d == '/') {
state = 0;
} else if (d != EOF) {
ungetc(d, stdin);
}
} else if (c == '\n') {
putchar(c);
}
}
}
return 0;
}
1.24
A simple checker: it counts round, figure and square brackets and says whether they are balanced.
#include <stdio.h>
/* check that round, figure and square brackets are balanced */
int main(void)
{
int c, round, fig, quad;
round = fig = quad = 0;
while ((c = getchar()) != EOF) {
if (c == '(')
++round;
else if (c == ')')
--round;
else if (c == '{')
++fig;
else if (c == '}')
--fig;
else if (c == '[')
++quad;
else if (c == ']')
--quad;
}
if (round == 0)
printf("round ok");
else if (round > 0)
printf("round mistake: too many (");
else
printf("round mistake: not enough (");
printf("\n");
if (fig == 0)
printf("fig ok");
else if (fig > 0)
printf("fig mistake: too many {");
else
printf("fig mistake: not enough {");
printf("\n");
if (quad == 0)
printf("quad ok");
else if (quad > 0)
printf("quad mistake: too many [");
else
printf("quad mistake: not enough [");
printf("\n");
return 0;
}
gcc -std=c17 -Wall -Wextra -Wpedantic p124.c -o p124
printf 'int main(void) { int a[3]; return 0; }\n' | ./p124
round ok fig ok quad ok
2.1
#include <stdio.h>
#include <limits.h>
#include <float.h>
/* print the ranges of the basic types of this compiler */
int main(void)
{
printf("char: %d .. %d\n", CHAR_MIN, CHAR_MAX);
printf("signed char: %d .. %d\n", SCHAR_MIN, SCHAR_MAX);
printf("unsigned char: 0 .. %u\n", UCHAR_MAX);
printf("short: %d .. %d\n", SHRT_MIN, SHRT_MAX);
printf("int: %d .. %d\n", INT_MIN, INT_MAX);
printf("unsigned int: 0 .. %u\n", UINT_MAX);
printf("long: %ld .. %ld\n", LONG_MIN, LONG_MAX);
printf("float: %.3e .. %.3e\n", FLT_MIN, FLT_MAX);
printf("double: %.3e .. %.3e\n", DBL_MIN, DBL_MAX);
return 0;
}
gcc -std=c17 -Wall -Wextra -Wpedantic p21.c -o p21
./p21
char: -128 .. 127 signed char: -128 .. 127 unsigned char: 0 .. 255 short: -32768 .. 32767 int: -2147483648 .. 2147483647 unsigned int: 0 .. 4294967295 long: -9223372036854775808 .. 9223372036854775807 float: 1.175e-38 .. 3.403e+38 double: 2.225e-308 .. 1.798e+308
I've been struggling with example 1.9 for a long time. You had to write a program that outputs what you type from the keyboard, while ignoring all the spaces, except the very first ones.
#include <stdio.h>
/* replace every run of blanks with one blank */
int main(void)
{
int c, last;
last = 0;
while ((c = getchar()) != EOF) {
if (c == ' ') {
if (!last)
putchar(c);
last = 1;
} else {
putchar(c);
last = 0;
}
}
return 0;
}
gcc -std=c17 -Wall -Wextra -Wpedantic p19.c -o p19
printf 'a b c\n' | ./p19
a b c
Article author: Andrei Olegovich