版本7和10间的区别 (跳过第3版)
于2005-12-20 21:47:02修订的的版本7
大小: 5969
编辑: czk
备注:
于2005-12-20 22:02:48修订的的版本10
大小: 13002
编辑: czk
备注:
删除的内容标记成这样。 加入的内容标记成这样。
行号 240: 行号 240:

{{{#!cplusplus
/*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.*/
#include <stdio.h>
#define MAXLENGTH 20

/* 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. */
main()
{
    int c, i, len, nlength[MAXLENGTH+1], state, max;
    for(i = 0; i <= MAXLENGTH; i++)
        nlength[i] = 0;
    while ((c = getchar()) != EOF) {
        if( c != ' ' && c!= '\n' && c != '\t') {
            ++len;
        } else if(len != 0) {
            if(len <= MAXLENGTH)
                ++nlength[len];
            len = 0;
        }
    }
    for(i = 1; i <= MAXLENGTH; i++) {
        int j = 0;
        printf("%4d %4d ", i, nlength[i]);
        for(j = 0; j < nlength[i]; j++)
            putchar('=');
        putchar('\n');
    }
    
    max = 0;
    for(i = 1; i <= MAXLENGTH; i++)
        if(nlength[i] > max)
            max = nlength[i];
    for(len = max; len >=1; len--) {
        for(i = 1; i <= MAXLENGTH; i++)
            printf("%3c", nlength[i] >= len ? '|' : ' ');
        printf("\n");
    }
    for(i = 1; i <= MAXLENGTH; i++)
        printf("%3d", i);
    printf("\n");
}
}}}

{{{#!cplusplus
/*Exercise 1-14. Write a program to print a histogram of the frequencies of different characters in its input.*/
#include <stdio.h>
#include <limits.h>
#include <ctype.h>

/* Write a program to print a histogram of the frequencies of different characters in its input.*/
main()
{
    int c, i, freq[UCHAR_MAX+1], max, f;
    for(i = 0; i <= UCHAR_MAX; i++)
        freq[i] = 0;
    while ((c = getchar()) != EOF) {
        freq[c]++;
    }
    for(i = 0; i <= UCHAR_MAX; i++) {
        if(freq[i] > 0) {
            int j = 0;
            printf("%4d %c %4d ", i, isprint(i)?i:' ', freq[i]);
            for(j = 0; j < freq[i]; j++)
               putchar('=');
            putchar('\n');
        }
    }
    max = 0;
    for(i = 0; i <= UCHAR_MAX; i++)
        if(freq[i] > max)
            max = freq[i];
    for(f = max; f >=1; f--) {
        for(i = 0; i <= UCHAR_MAX; i++)
            if(freq[i] > 0)
                printf("%4c", freq[i] >= f ? '|' : ' ');
        printf("\n");
    }
    for(i = 0; i <= UCHAR_MAX; i++)
        if(freq[i] > 0)
            printf("%4d", i);
    printf("\n");
    for(i = 0; i <= UCHAR_MAX; i++)
        if(freq[i] > 0)
            printf("%4c", isprint(i)?i:' ');
    printf("\n");
}
}}}

{{{#!cplusplus
/*Exercise 1.15. Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.*/
#include <stdio.h>

float fahr2celsius(float f);

/* Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.*/
main()
{
    float fahr, celsius;
    int lower, upper, step;
    
    lower = 0; /* lower limit of temperatuire scale */
    upper = 300; /* upper limit */
    step = 20; /* step size */
    
    printf("fahr celsius\n");
    
    fahr = lower;
    while (fahr <= upper) {
        celsius = fahr2celsius(fahr);
        printf("%4.0f %7.1f\n", fahr, celsius);
        fahr = fahr + step;
    }
}

float fahr2celsius(float f)
{
    return (5.0/9.0) * (f - 32.0);
}
}}}

{{{#!cplusplus
/*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.*/
#include <stdio.h>
#define MAXLINE 10 /* maximum input line length */

int getline(char line[], int maxline);
void copy(char to[], char from[], int lim);

/* 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. */
main()
{
    int len; /* current line length */
    int total_len;
    int max; /* maximum length seen so far */
    char line[MAXLINE]; /* current input line */
    char longest[MAXLINE]; /* longest line saved here */

    max = 0;
    total_len = 0;
    while ((len = getline(line, MAXLINE)) > 0) {
        total_len += len;
        if(len != MAXLINE-1 || line[MAXLINE-2] == '\n') {
            if (total_len > max) {
                max = total_len;
                copy(longest, line, MAXLINE);
            }
            total_len = 0;
        }
    }
    if (max > 0) /* there was a line */
        printf("%d\n%s\n", max, longest);
    return 0;
}

/* getline: read a line into s, return length */
int getline(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;
}

/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[], int lim)
{
    int i;
    i = 0;
    while (i < lim && (to[i] = from[i]) != '\0' )
        ++i;
    to[lim-1] = '\0';
}
}}}

{{{#!cplusplus
/*Exercise 1-17. Write a program to print all input lines that are longer than 80 characters.*/
}}}

{{{#!cplusplus
/*Exercise 1-18. Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.*/
}}}

{{{#!cplusplus
/*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.*/
}}}

{{{#!cplusplus
/*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?*/
}}}

{{{#!cplusplus
/*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?*/
}}}

{{{#!cplusplus
/*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.*/
}}}

{{{#!cplusplus
/*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.*/
}}}

{{{#!cplusplus
/*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.) */
}}}

此页代码仅供学习C语言参考之用,以[http://www.gnu.org/copyleft/gpl.html 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.*/

   1 /*Exercise 1-18. Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.*/

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

   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?*/

   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?*/

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

   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编辑)

ch3n2k.com | Copyright (c) 2004-2020 czk.