Answer_to_Chapter_1

此页代码仅供学习C语言参考之用,以GPL协议发布。

   1 /*Exercise 1-1. Run the "hello, world" program on your system. Experiment with leaving out parts of the program, to see what error messages you get.*/
   2 #include <stdio.h>
   3 
   4 main()
   5 {
   6     printf("hello, world\n");
   7 }

   1 /*Exercise 1-2. Experiment to find out what happens when prints's argument string contains \c, where c is some character not listed above.*/
   2 #include <stdio.h>
   3 
   4 main()
   5 {
   6     printf("\a");
   7 }

   1 /*Exercise 1-3. Modify the temperature conversion program to print a heading above the table.*/
   2 #include <stdio.h>
   3 
   4 /* print Fahrenheit-Celsius table
   5 for fahr = 0, 20, ..., 300; floating-point version */
   6 main()
   7 {
   8     float fahr, celsius;
   9     int lower, upper, step;
  10     
  11     lower = 0; /* lower limit of temperatuire scale */
  12     upper = 300; /* upper limit */
  13     step = 20; /* step size */
  14     
  15     printf("fahr celsius\n");
  16     
  17     fahr = lower;
  18     while (fahr <= upper) {
  19         celsius = (5.0/9.0) * (fahr-32.0);
  20         printf("%4.0f %7.1f\n", fahr, celsius);
  21         fahr = fahr + step;
  22     }
  23 }

   1 /*Exercise 1-4. Write a program to print the corresponding Celsius to Fahrenheit table.*/
   2 #include <stdio.h>
   3 
   4 /* print Celsius-Fahrenheit table
   5 for celsius = 0, 20, ..., 300; floating-point version */
   6 main()
   7 {
   8     float fahr, celsius;
   9     int lower, upper, step;
  10     
  11     lower = 0; /* lower limit of temperatuire scale */
  12     upper = 300; /* upper limit */
  13     step = 20; /* step size */
  14     
  15     celsius = lower;
  16     while (celsius <= upper) {
  17         fahr =  celsius * (9.0/5.0) + 32.0;
  18         printf("%3.0f %6.1f\n", celsius, fahr);
  19         celsius = celsius + step;
  20     }
  21 }

   1 /*Exercise 1-5. Modify the temperature conversion program to print the table in reverse order, that is, from 300 degrees to 0.*/
   2 #include <stdio.h>
   3 
   4 /* print Fahrenheit-Celsius table
   5 for fahr = 300, 280, ..., 0; floating-point version */
   6 main()
   7 {
   8     int fahr;
   9    
  10     for(fahr = 300; fahr >= 0; fahr = fahr - 20)
  11         printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
  12 }

   1 /*Exercsise 1-6. Verify that the expression getchar() != EOF is 0 or 1.*/
   2 #include <stdio.h>
   3 
   4 /* Verify that the expression getchar() != EOF is 0 or 1. */
   5 main()
   6 {
   7     int c;
   8     
   9     while(c = (getchar() !=EOF))
  10         printf("%d\n", c);
  11     printf("%d\n", c);
  12 }

   1 /*Exercsise 1-6. Verify that the expression getchar() != EOF is 0 or 1.*/
   2 #include <stdio.h>
   3 
   4 /* Write a program to print the value of EOF. */
   5 main()
   6 {
   7     printf("%d\n", EOF);
   8 }

   1 /*Exercise 1-8. Write a program to count blanks, tabs, and newlines.*/
   2 #include <stdio.h>
   3 
   4 /* Write a program to count blanks, tabs, and newlines. */
   5 main()
   6 {
   7     int c, nl, nb, nt;
   8     nl = 0;
   9     nb = 0;
  10     nt = 0;
  11     while ((c = getchar()) != EOF)
  12         if (c == '\n')
  13             ++nl;
  14         else if(c == '\t')
  15             ++nt;
  16         else if(c == ' ')
  17             ++nb;
  18     printf("%d %d %d\n", nb, nt, nl);
  19 }

   1 /*Exercise 1-9. Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.*/
   2 #include <stdio.h>
   3 
   4 #define TRUE 1
   5 #define FALSE 0
   6 
   7 /* Write a program to copy its input to its output, replacing each string of one or
   8 more blanks by a single blank. */
   9 main()
  10 {
  11     int c, is_blank;
  12     while ((c = getchar()) != EOF)
  13         if (c != ' ') {
  14             putchar(c);
  15             is_blank = FALSE;
  16         }
  17         else if(c == ' ' && !last_blank) {
  18             putchar(c);
  19             is_blank = FALSE;
  20         }
  21 }

   1 /*Exercise 1-10. Write a program to copy its input to its output, replacing each tab by \t, each backspace by \b, and each backslash by \\. This makes tabs and backspaces visible in an unambiguous way.*/
   2 #include <stdio.h>
   3 
   4 #define TRUE 1
   5 #define FALSE 0
   6 
   7 /* Write a program to copy its input to its output, replacing each tab by \t, each
   8 backspace by \b, and each backslash by \\. This makes tabs and backspaces visible in an
   9 unambiguous way. */
  10 main()
  11 {
  12     int c;
  13     while ((c = getchar()) != EOF)
  14         if (c == '\t') {
  15             putchar('\\');
  16             putchar('t');
  17         } else if(c == '\b') {
  18             putchar('\\');
  19             putchar('b');
  20         } else if(c == '\\') {
  21             putchar('\\');
  22             putchar('\\');
  23         } else {
  24             putchar(c);
  25         }
  26 }

   1 /*Exercise 1-11. How would you test the word count program? What kinds of input are most likely to uncover bugs if there are any?*/
   2 #include <stdio.h>
   3 #define IN 1 /* inside a word */
   4 #define OUT 0 /* outside a word */
   5 
   6 /* count lines, words, and characters in input */
   7 main()
   8 {
   9     int c, nl, nw, nc, state;
  10     state = OUT;
  11     nl = nw = nc = 0;
  12     while ((c = getchar()) != EOF) {
  13         ++nc;
  14         if (c == '\n')
  15             ++nl;
  16         if (c == ' ' || c == '\n' || c == '\t')
  17             state = OUT;
  18         else if (state == OUT) {
  19             state = IN;
  20             ++nw;
  21         }
  22     }
  23     printf("%d %d %d\n", nl, nw, nc);
  24 }

   1 /*Exercise 1-12. Write a program that prints its input one word per line.*/
   2 #include <stdio.h>
   3 #define IN 1 /* inside a word */
   4 #define OUT 0 /* outside a word */
   5 
   6 /* Write a program that prints its input one word per line. */
   7 main()
   8 {
   9     int c, state;
  10     state = OUT;
  11     while ((c = getchar()) != EOF) {
  12         if( c != ' ' && c!= '\n' && c != '\t') {
  13             state = IN;
  14             putchar(c);
  15         } else if(state == IN) {
  16             state = OUT;
  17             putchar('\n');
  18         }
  19     }
  20     printf("%d %d %d\n", nl, nw, nc);
  21 }

   1 /*Exercise 1-13. Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.*/
   2 #include <stdio.h>
   3 #define MAXLENGTH 20
   4 
   5 /* Write a program to print a histogram of the lengths of words in its input. It is
   6 easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging. */
   7 main()
   8 {
   9     int c, i, len, nlength[MAXLENGTH+1], state, max;
  10     for(i = 0; i <= MAXLENGTH; i++)
  11         nlength[i] = 0;
  12     while ((c = getchar()) != EOF) {
  13         if( c != ' ' && c!= '\n' && c != '\t') {
  14             ++len;
  15         } else if(len != 0) {
  16             if(len <= MAXLENGTH)
  17                 ++nlength[len];
  18             len = 0;
  19         }
  20     }
  21     for(i = 1; i <= MAXLENGTH; i++) {
  22         int j = 0;
  23         printf("%4d %4d ", i, nlength[i]);
  24         for(j = 0; j < nlength[i]; j++)
  25             putchar('=');
  26         putchar('\n');
  27     }
  28     
  29     max = 0;
  30     for(i = 1; i <= MAXLENGTH; i++)
  31         if(nlength[i] > max)
  32             max = nlength[i];
  33     for(len = max; len >=1; len--) {
  34         for(i = 1; i <= MAXLENGTH; i++)
  35             printf("%3c", nlength[i] >= len ? '|' : ' ');
  36         printf("\n");
  37     }
  38     for(i = 1; i <= MAXLENGTH; i++)
  39         printf("%3d", i);
  40     printf("\n");      
  41 }

   1 /*Exercise 1-14. Write a program to print a histogram of the frequencies of different characters in its input.*/
   2 #include <stdio.h>
   3 #include <limits.h>
   4 #include <ctype.h>
   5 
   6 /* Write a program to print a histogram of the frequencies of different characters in its input.*/
   7 main()
   8 {
   9     int c, i, freq[UCHAR_MAX+1], max, f;
  10     for(i = 0; i <= UCHAR_MAX; i++)
  11         freq[i] = 0;
  12     while ((c = getchar()) != EOF) {
  13         freq[c]++;
  14     }
  15     for(i = 0; i <= UCHAR_MAX; i++) {
  16         if(freq[i] > 0) {
  17             int j = 0;
  18             printf("%4d %c %4d ", i, isprint(i)?i:' ', freq[i]);
  19             for(j = 0; j < freq[i]; j++)
  20                putchar('=');
  21             putchar('\n');
  22         }
  23     }
  24     max = 0;
  25     for(i = 0; i <= UCHAR_MAX; i++)
  26         if(freq[i] > max)
  27             max = freq[i];
  28     for(f = max; f >=1; f--) {
  29         for(i = 0; i <= UCHAR_MAX; i++)
  30             if(freq[i] > 0)
  31                 printf("%4c", freq[i] >= f ? '|' : ' ');
  32         printf("\n");
  33     }
  34     for(i = 0; i <= UCHAR_MAX; i++)
  35         if(freq[i] > 0)
  36             printf("%4d", i);
  37     printf("\n");
  38     for(i = 0; i <= UCHAR_MAX; i++)
  39         if(freq[i] > 0)
  40             printf("%4c", isprint(i)?i:' ');
  41     printf("\n");
  42 }

   1 /*Exercise 1.15. Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.*/
   2 #include <stdio.h>
   3 
   4 float fahr2celsius(float f);
   5 
   6 /* Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.*/
   7 main()
   8 {
   9     float fahr, celsius;
  10     int lower, upper, step;
  11     
  12     lower = 0; /* lower limit of temperatuire scale */
  13     upper = 300; /* upper limit */
  14     step = 20; /* step size */
  15     
  16     printf("fahr celsius\n");
  17     
  18     fahr = lower;
  19     while (fahr <= upper) {
  20         celsius = fahr2celsius(fahr);
  21         printf("%4.0f %7.1f\n", fahr, celsius);
  22         fahr = fahr + step;
  23     }
  24 }
  25 
  26 float fahr2celsius(float f)
  27 {
  28     return (5.0/9.0) * (f - 32.0);
  29 }

   1 /*Exercise 1-16. Revise the main routine of the longest-line program so it will correctly print the length of arbitrary long input lines, and as much as possible of the text.*/
   2 #include <stdio.h>
   3 #define MAXLINE 10 /* maximum input line length */
   4 
   5 int getline(char line[], int maxline);
   6 void copy(char to[], char from[], int lim);
   7 
   8 /* Revise the main routine of the longest-line program so it will correctly print
   9 the length of arbitrary long input lines, and as much as possible of the text. */
  10 main()
  11 {
  12     int len; /* current line length */
  13     int total_len;
  14     int max; /* maximum length seen so far */
  15     char line[MAXLINE]; /* current input line */
  16     char longest[MAXLINE]; /* longest line saved here */
  17 
  18     max = 0;
  19     total_len = 0;
  20     while ((len = getline(line, MAXLINE)) > 0) {
  21         total_len += len;
  22         if(len != MAXLINE-1 || line[MAXLINE-2] == '\n') {
  23             if (total_len > max) {
  24                 max = total_len;
  25                 copy(longest, line, MAXLINE);
  26             }
  27             total_len = 0;
  28         }
  29     }
  30     if (max > 0) /* there was a line */
  31         printf("%d\n%s\n", max, longest);
  32     return 0;
  33 }
  34 
  35 /* getline: read a line into s, return length */
  36 int getline(char s[],int lim)
  37 {
  38     int c, i;
  39     for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
  40         s[i] = c;
  41     if (c == '\n') {
  42         s[i] = c;
  43         ++i;
  44     }
  45     s[i] = '\0';
  46     return i;
  47 }
  48 
  49 /* copy: copy 'from' into 'to'; assume to is big enough */
  50 void copy(char to[], char from[], int lim)
  51 {
  52     int i;
  53     i = 0;
  54     while (i < lim && (to[i] = from[i]) != '\0' )
  55         ++i;
  56     to[lim-1] = '\0';
  57 }

   1 /*Exercise 1-17. Write a program to print all input lines that are longer than 80 characters.*/
   2 #include <stdio.h>
   3 #define MAXLINE 1000 /* maximum input line length */
   4 
   5 int getline(char line[], int maxline);
   6 
   7 /* Write a program to print all input lines that are longer than 80 characters. */
   8 main()
   9 {
  10     int len; /* current line length */
  11     char line[MAXLINE]; /* current input line */
  12     while ((len = getline(line, MAXLINE)) > 0)
  13         if (len > 80) 
  14             printf("%s", line);
  15     return 0;
  16 }
  17 
  18 /* getline: read a line into s, return length */
  19 int getline(char s[],int lim)
  20 {
  21     int c, i;
  22     for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
  23         s[i] = c;
  24     if (c == '\n') {
  25         s[i] = c;
  26         ++i;
  27     }
  28     s[i] = '\0';
  29     return i;
  30 }

   1 /*Exercise 1-18. Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.*/
   2 #include <stdio.h>
   3 #define MAXLINE 1000 /* maximum input line length */
   4 
   5 int getline(char line[], int maxline);
   6 
   7 /* Write a program to remove trailing blanks and tabs from each line of input, 
   8 and to delete entirely blank lines. */
   9 main()
  10 {
  11     int len; /* current line length */
  12     char line[MAXLINE]; /* current input line */
  13     while ((len = getline(line, MAXLINE)) > 0) {
  14         while(len > 0 && (getline[len-1] == ' ' || getline[len-1] == '\t'))
  15             len--;
  16          
  17     }
  18     return 0;
  19 }
  20 
  21 /* getline: read a line into s, return length */
  22 int getline(char s[],int lim)
  23 {
  24     int c, i;
  25     for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
  26         s[i] = c;
  27     if (c == '\n') {
  28         s[i] = c;
  29         ++i;
  30     }
  31     s[i] = '\0';
  32     return i;
  33 }

   1 /*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.*/ 
   2 #include <stdio.h>
   3 #define MAXLINE 1000 /* maximum input line length */
   4 
   5 int getline(char line[], int maxline);
   6 void reverse(char s[]);
   7 /* Write a function reverse(s) that reverses the character string s. 
   8 Use it to write a program that reverses its input a line at a time. */
   9 main()
  10 {
  11     int len; /* current line length */
  12     char line[MAXLINE]; /* current input line */
  13     while ((len = getline(line, MAXLINE)) > 0) {
  14         if(line[len-1] == '\n') {
  15             line[len-1] = '\0';
  16             reverse(line);
  17             printf("%s\n", line);
  18         } else {
  19             reverse(line);
  20             printf("%s", line);
  21         }
  22     }
  23     return 0;
  24 }
  25 
  26 /* getline: read a line into s, return length */
  27 int getline(char s[],int lim)
  28 {
  29     int c, i;
  30     for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
  31         s[i] = c;
  32     if (c == '\n') {
  33         s[i] = c;
  34         ++i;
  35     }
  36     s[i] = '\0';
  37     return i;
  38 }
  39 
  40 void reverse(char s[]) 
  41 {
  42     int head, tail;
  43     for(tail = 0; s[tail] != '\0'; tail++);
  44     tail--;
  45     for(head = 0; head < tail; head++, tail--) {
  46         char temp = s[head];
  47         s[head] = s[tail];
  48         s[tail] = temp;
  49     }
  50 }

   1 /*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?*/
   2 #include<stdio.h>
   3 #include<stdlib.h>
   4 
   5 #define TABSIZE 7
   6 
   7 /*Write a program detab that replaces tabs in the input with the proper number
   8 of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns.
   9 Should n be a variable or a symbolic parameter?*/
  10 main()
  11 {
  12     int c, i;
  13     int count=0;
  14     while((c=getchar())!=EOF) {
  15         if(c=='\t') {
  16             int blank_count = TABSIZE - count % TABSIZE;
  17             for(i = 0; i < blank_count; i++) {
  18                 putchar(' ');
  19                 count ++;
  20             } 
  21         } else if (c == '\n'){
  22             putchar(c);
  23             count = 0;
  24         } else {
  25             putchar(c);
  26             count ++;
  27         }
  28     }
  29 }

   1 /*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?*/
   2 #include<stdio.h>
   3 #include<stdlib.h>
   4 
   5 #define TABSIZE 7
   6 
   7 /*Write a program entab that replaces strings of blanks by the minimum
   8 number of tabs and blanks to achieve the same spacing. Use the same tab stops as for detab.
   9 When either a tab or a single blank would suffice to reach a tab stop, which should be given
  10 preference?*/
  11 main()
  12 {
  13     int c, i;
  14     int count = 0;
  15     int blank_count = 0;
  16     while((c = getchar()) != EOF) {
  17         if(c == ' ') {
  18             count ++;
  19             blank_count++;
  20             if(count % TABSIZE == 0) {
  21                 for(i = 0; i < blank_count; i++)
  22                     putchar('\b');
  23                 putchar('\t');
  24                 blank_count = 0;
  25             }
  26         } else if (c == '\t') {
  27             count = 0;
  28             blank_count = 0; 
  29         } else if (c == '\n'){
  30             putchar(c);
  31             count = 0;
  32             blank_count = 0;
  33         } else {
  34             putchar(c);
  35             count ++;
  36             blank_count = 0;
  37         }
  38     }
  39 }

   1 /*Exercise 1-22. Write a program to ``fold'' long input 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.*/
   2 #include <stdio.h>
   3 
   4 #include <stdio.h>
   5 #define MAXLINE 1000 /* maximum input line length */
   6 #define FOLD_LENGTH 70
   7 
   8 int getline(char line[], int maxline);
   9 
  10 /*Write a program to "fold" long input lines into two or more shorter lines after
  11 the last non-blank character that occurs before the n-th column of input. Make sure your
  12 program does something intelligent with very long lines, and if there are no blanks or tabs
  13 before the specified column.*/
  14 main()
  15 {
  16     int len; /* current line length */
  17     int start, end, i;
  18     char line[MAXLINE]; /* current input line */
  19     while ((len = getline(line, MAXLINE)) > 0) {
  20         start = 0;
  21         while ( start < len) {
  22             if( len - start > FOLD_LENGTH) {
  23                 for( end = start + FOLD_LENGTH; end >= start && (line[end] != ' ' 
  24                     && line[end] != '\t'); end--);
  25                 for(; end >= start && (line[end] == ' ' || line[end] == '\t'); end--);
  26                 if( end < start)
  27                     end = start + FOLD_LENGTH-1;
  28             } else {
  29                 end = len -1;
  30             }
  31             for(i = start; i <= end; i++)
  32                 putchar(line[i]);
  33             if(line[end]!='\n')
  34                 putchar('\n');
  35             start = end + 1;
  36         }
  37     }
  38     return 0;
  39 }
  40 
  41 /* getline: read a line into s, return length */
  42 int getline(char s[],int lim)
  43 {
  44     int c, i;
  45     for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
  46         s[i] = c;
  47     if (c == '\n') {
  48         s[i] = c;
  49         ++i;
  50     }
  51     s[i] = '\0';
  52     return i;
  53 }

   1 /*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.*/

   1 /*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, escape sequences, and comments. (This program is hard if you do it in full generality.) */

Answer_to_Chapter_1 (2008-02-23 15:34:13由localhost编辑)