C程序设计语言(第二版)习题:第一章

第一章虽然感觉不像是个习题。但是我还是认真去做,去想,仅此而已!

练习 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. 

1 #include <stdio.h>

2 int main(int argc, char const *argv[])

3 {

4     printf("Hello, world\n");

5     return 0;

6 }

收获 : 学习一门新程序设计语言的唯一途径就是使用它编写程序!

 

练习 1-2

Experiment to find out what happens when printf 's argument string contains \c, where c is some character not listed above. 

1 #include <stdio.h>

2 int main(int argc, char const *argv[])

3 {

4     printf("\c\n");

5     return 0;

6 }

chap1.1.c:4:9: warning: unknown escape sequence '\c'
printf("\c\n");
^
1 warning generated.

 

练习 1-3

Modify the temperature conversion program to print a heading above the table.

 1 #include <stdio.h>

 2 #include <stdlib.h>

 3 

 4 int main()

 5 {

 6     float fahr, celsius;

 7     int lower, upper, step;

 8 

 9     lower = 0;

10     upper = 300;

11     step = 20;

12 

13     fahr = lower;

14     printf("%3s\t%6s\n", "F", "C");

15     while(fahr <= upper) {

16         celsius = (5.0/9.0) *(fahr-32.0);

17         printf("%3.0f\t%6.1f\n", fahr, celsius);

18         fahr = fahr + step;

19     }

20     return 0;

21 }

 

练习 1-4

Write a program to print the corresponding Celsius to Fahrenheit table.

 1 #include <stdio.h>

 2 #include <stdlib.h>

 3 

 4 int main()

 5 {

 6     float fahr, celsius;

 7     int lower, upper, step;

 8 

 9     lower = -10;

10     upper = 100;

11     step = 10;

12 

13     celsius = lower;

14     printf("%3s\t%6s\n", "C", "F");

15     while(celsius <= upper) {

16         fahr = celsius * (9.0/5.0) + 32;

17         printf("%3.0f\t%6.1f\n", celsius, fahr);

18         celsius = celsius + step;

19     }

20     return 0;

21 }

 

练习 1-5

Modify the temperature conversion program to print the table in reverse order, that is, from 300 degrees to 0. 

 1 #include <stdio.h>

 2 int main()

 3 {

 4      int fahr;

 5  

 6      for (fahr = 300; fahr >= 0; fahr = fahr - 20)

 7              printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));

 8  

 9    return 0;

10 }

 

练习 1-6

Verify that the expression getchar()!=EOF is 0 or 1. 

#include <stdio.h>

 

int main(void)

{

  printf("getchar() != EOF evaluates to %d\n", getchar() != EOF);

  return 0;

}

Ps : 不输入是 0 , 输入是 1.

 

练习 1-7

Write a program to print the value of EOF

1 #include <stdio.h>

2 

3 int main() {

4     printf("EOF = %d\n", EOF);

5     return 0;

6 }

ps : EOF = -1

 

练习 1-8

Write a program to count blanks, tabs, and newlines.

 1 #include <stdio.h>

 2 

 3 int main(int argc, char const *argv[])

 4 {

 5     int c, nl, tab, space;

 6     while((c = getchar()) != -1){

 7         if(c == '\n')

 8             ++nl;

 9         else if(c == '\t')

10             ++tab;

11         else if(c == ' ')

12             ++space;

13     }

14     printf("nl: %d  tab: %d  space: %d\n", nl, tab, space);

15     return 0;

16 }

 

练习 1-9 

Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

 1 #include <stdio.h>

 2 

 3 int main(int argc, char const *argv[])

 4 {

 5     int c, pre;

 6     pre = -1;

 7     while((c = getchar()) != -1){

 8         if(c == ' ' && pre == ' '){

 9             continue;

10         }

11         putchar(c);

12         pre = c;

13     }

14     return 0;

15 }

ps : 可以用flag 实现

 

练习 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.

 1 #include <stdio.h>

 2 

 3 int main(int argc, char const *argv[])

 4 {

 5     int c;

 6     while((c = getchar()) != -1){

 7         if(c == '\t')

 8             printf("\\t");

 9         else if(c == '\b')

10             printf("\\b");

11         else if(c == '\\')

12             printf("\\\\");

13         else putchar(c);

14     }

15     return 0;

16 }

 

练习 1-11

How would you test the word count program? What kinds of input are most likely to uncover bugs if there are any? 

 1 #include <stdio.h>

 2 

 3 int main(int argc, char const *argv[])

 4 {

 5     int c, nl, nw, nc, flag;

 6 

 7     flag = 0;

 8     nl = nw = nc = 0;

 9     while((c = getchar()) != -1){

10         ++nc;

11         if(c == '\n')

12             ++nl;

13         if(c == ' ' || c == '\n' || c == '\t')

14             flag = 0;

15         else if(flag == 0){

16             flag = 1;

17             ++nw;

18         }

19     }

20     printf("%d %d %d\n", nl, nw, nc);

21     return 0;

22 }

ps:

0. input file contains zero words
1. input file contains 1 enormous word without any newlines
2. input file contains all white space without newlines
3. input file contains 66000 newlines
4. input file contains word/{huge sequence of whitespace of different kinds}/word
5. input file contains 66000 single letter words, 66 to the line
6. input file contains 66000 words without any newlines
7. input file is /usr/dict contents (or equivalent)
8. input file is full collection of moby words
9. input file is binary (e.g. its own executable)
10. input file is /dev/nul (or equivalent) 

 

练习 1-12

Write a program that prints its input one word per line.

 1 #include <stdio.h>

 2 

 3 int main(int argc, char const *argv[])

 4 {

 5     int c;

 6     int pre;

 7     pre = -1;

 8     while((c = getchar()) != -1){

 9         if(pre == -1 && c == ' ')    continue;

10         if(c == ' ' && pre == ' ')    continue;

11         else if(c == ' ')    printf("\n");

12         else putchar(c);

13         pre = c;

14     }

15     return 0;

16 }

 

练习 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.

 1 //水平直方图

 2 

 3 #include <stdio.h>

 4 #define MAX 10

 5 

 6 int main()

 7 {

 8     int len[MAX];

 9     int c;

10     int num;

11     int flag = 0;

12     int i;

13 

14     for(i = 0; i < MAX; i++)    len[i] = 0;

15     

16     while((c = getchar()) != EOF){

17         if(c != ' ' && c != '\t' && c != '\n'){

18             if(flag == 0)    num = 1;

19             else    num++;

20 

21             flag = 1;

22         } 

23         else{

24             len[num]++;

25             num = 0;

26         }

27     }

28     for(num = 0; num < MAX; num++){

29         if(len[num] != 0){

30             printf("%3d ", num);

31             for(i = 1; i <= len[num]; i++)

32                 putchar('*');

33             

34             putchar('\n');

35         }

36     }

37 }

 

//垂直直方图

# include <stdio.h>

# define MAX 20

# define MAXLEN 20



int main(void){

    int length[MAX];

    int c;

    int num;

    int i;

    int r;



    for(i = 0; i < MAX; i++){

        length[i] = 0;

    }

    num = 0; 

    while((c = getchar()) != EOF){

        if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ){

            num++;

        } else{

            length[num]++;

            num = 0;

        }

    }

    printf("1 2 3 4 5 6 7 8 9 10 ....\n");

    for(r = 1; r < MAXLEN; r++){

        for(i = 1; i < MAX; i++){

            if(r <= length[i]){

                printf("* ");

            } else{

                printf("  ");

            }

        }

        putchar('\n');

    }

}

 

练习 1-14

Write a program to print a histogram of the frequencies of different characters in its input. 

 1 //水平

 2 #include <stdio.h>

 3 #include <string.h>

 4 #include <stdlib.h>

 5 #define N 256

 6 

 7 

 8 void print() {

 9     int r[N] = {0};                            

10      int i, j, c;

11      while ((c = getchar()) != -1) {

12          if(c == ' ' || c == '\t' || c == '\n' || c == '\r')    continue;

13         r[c]++;                         

14     }

15     for (i = 0; i < N; i++) {

16           if (r[i]) {                                            

17                   printf("%c| ", i);

18                 for (j = 0; j < r[i]; j++)    printf("*");

19                 printf("\n");

20         }

21     }

22 }

23 int main() 

24 {

25 

26     print();

27     return 0;

28 }

 

练习 1-15

Rewrite the temperature conversion program of Section 1.2 to use a function for conversion. 

 1 /* 重新编写1.2 温度转换程序,使用函数实现温度转换程序 */

 2 

 3 #include <stdio.h>

 4 

 5 void change(int fahr){

 6     printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));

 7 }

 8 

 9 int main(int argc, char const *argv[])

10 {

11     int fahr;

12     while(scanf("%d", &fahr) != -1)

13         change(fahr);

14 

15     return 0;

16 }

 

练习 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.

 1 /* 修改打印最长行的主程序 main 使之可以打印任意长度的输入行的长度, 并尽可能多的打印 */

 2 

 3 #include <stdio.h>

 4 #define MAXLINE 1000

 5 void copy(char to[], char from[]){

 6     int i;

 7     i = 0;

 8     while((to[i] = from[i]) != '\0')

 9         ++i;

10 }

11 

12 int _getline(char s[], int lim){

13     int c, i;

14     for(i=0;i<lim-1 && (c = getchar()) != -1 && c!='\n'; ++i)

15         s[i] = c;

16     s[i] = '\0';

17     return i;

18 }

19 

20 void printlength(int realLen){

21     int len;

22     char line[MAXLINE];

23     char realline[MAXLINE];

24     while((len = _getline(line, realLen)) > 0){

25         printf("%s", line);

26         printf("\n");

27     }

28 }

29 

30 int main(int argc, char const *argv[])

31 {

32     printlength(5);

33     return 0;

34 }

 

练习1-17

Write a program to print all input lines that are longer than 80 characters.

 1 /* 编写一个程序,打印长度大于80个字符的所有输入行 */

 2 

 3 #include <stdio.h>

 4 #define MAXLINE 1000

 5 

 6 int _getline(char s[], int lim){

 7     int c, i;

 8     for(i=0; i<lim-1 && (c = getchar()) != -1 && c != '\n' ; ++i)

 9         s[i] = c;

10     if(c == '\n'){

11         s[i] = c;

12         ++i;

13     }

14     s[i] = '\0';

15     return i;

16 }

17 

18 void printfLen(){

19     char line[MAXLINE];

20     char longest[MAXLINE];

21     int len;

22     int tmp;

23     while((len = _getline(line, MAXLINE)) > 0)

24         if(len > 10)

25             printf("%s", line);

26 }

27 

28 int main(int argc, char const *argv[])

29 {

30     printfLen();        

31     return 0;

32 }

 

练习1-18

Write a program to remove all trailing blanks and tabs from each line of input, and to delete entirely blank lines.

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



#include <stdio.h>

#define MAXLENGTH 1000

int len, newline;

char line[MAXLENGTH];

int gline(char line[]);

int main()

{

    while ((len = gline(line)) > 0) {

        if (line[len - 1] == '\n') {

            newline = 1;

            len--;

        }

        else

            newline = 0;

        while (len > 0 && (line[len - 1] == ' ' || line [len - 1] == '\t'))

            len--;

        if (len != 0)

        {

            if (newline == 1) {

                line[len] = '\n';

                len++;

            }

            line[len] = 0;

            printf("%s", line);

        }

    }

    return 0;

}

int gline(char s[])

{

    int c, i;

    for (i = 0; (c = getchar()) != EOF && c != '\n'; i++)

        s[i] = c;

    if (c == '\n') {

        s[i] = c;

        i++;

    }

    s[i] = '\0';

    return i;

}

 

练习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.

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



#include <stdio.h>

#include <string.h>

char s[100];

void swap(int a, int b){

    int tmp;

    tmp = s[a];

    s[a] = s[b];

    s[b] = tmp;

}



void reverse(char a[]){

    int i, p, len;

    len = strlen(a);

    for(i=0,p=len-1;i<p;++i,--p){

        printf("%d ", p);

        swap(i, p);

    }

}



int main(int argc, char const *argv[])

{

    scanf("%s", s);

    reverse(s);

    printf("%s", s);

    printf("\n");



    return 0;

}

 

练习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-21

Write a program entab that replaces strings of blanks with the minimum number of tabs and blanks to achieve the same spacing. Use the same 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 #include <stdio.h>

 2 

 3 int main() {

 4     int i, c, nwhite, ntab;

 5 

 6     nwhite = 0;

 7     while((c = getchar()) != EOF) {

 8         if(c == ' ') {

 9             ++nwhite;

10         }

11         else {

12             putchar(c);

13             if(nwhite != 0) {

14                 ntab = nwhite / 5;

15                 nwhite = nwhite % 5;

16                 for(i = 0; i < ntab; i++)

17                     putchar('\t');

18                 for(i = 0; i < nwhite; i++)

19                     putchar(' ');

20                 nwhite = 0;

21             }

22         }

23     }

24     return 0;

25 }

 

练习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 #include <stdio.h>

 2 

 3 #define MAXLINE 1000 

 4 char line[MAXLINE];

 5 int getline(void);

 6 int main()

 7 {

 8   int t,len;

 9   int location,spaceholder;

10   const int FOLDLENGTH=70; /* The max length of a line */

11 

12   while (( len = getline()) > 0 )

13     {

14       if( len < FOLDLENGTH )

15     {

16     }

17       else

18     {

19 

20       t = 0;

21       location = 0;

22       while(t<len)

23         {

24           if(line[t] == ' ')

25         spaceholder = t;

26 

27           if(location==FOLDLENGTH)

28         {

29           line[spaceholder] = '\n';

30           location = 0;

31         }

32           location++;

33           t++;

34         }

35     }

36       printf ( "%s", line);

37     }

38   return 0;

39 }

40 

41 int getline(void)

42 {

43   int c, i;

44   extern char line[];

45   

46   for ( i=0;i<MAXLINE-1 && ( c=getchar()) != EOF && c != '\n'; ++i)

47     line[i] = c;

48   if(c == '\n') 

49     {

50       line[i] = c;

51       ++i;

52     }

53   line[i] = '\0';

54   return i;

55 

56 }

 

练习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 do not nest. 

 1 #include <stdio.h>

 2 #define IN    1

 3 #define OUT    0

 4 

 5 int main() {

 6     int c, state;

 7     int s1, s2, e1, e2;

 8     

 9     state = OUT;

10     

11     while((c = getchar()) != EOF) {

12         if(c == '/')

13             s1 = 1;

14         else if(c != '*' && s1 == 1) 

15             s1 = 0;

16         else if(c == '*' && s1 == 1) 

17             state = IN;

18         else if(c == '*' && state == IN)

19             e1 = 1;

20         else if(c != '/' && e1 == 1)

21             e1 = 0;

22         else if(c == '/' && e1 == 1)

23             state == OUT;    

24         else if(state == OUT)

25             putchar(c);

26     }

27     return 0;

28 }

 

练习1-24

Write a program to check a C program for rudimentary syntax errors like unbalanced 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.) 

 1 #include <stdio.h>

 2 #define MAXLINE 1000 

 3 

 4 char line[MAXLINE]; 

 5 int getline(void);  

 6 

 7 int main()

 8 {

 9   int len=0;

10   int t=0;

11   int brace=0, bracket=0, parenthesis=0;

12   int s_quote=1, d_quote=1;

13 

14 

15   while ((len = getline()) > 0 )

16     {

17       t=0;

18       while(t < len)

19     {

20       if( line[t] == '[')

21         {

22           brace++;

23         }

24       if( line[t] == ']')

25         {

26           brace--;

27         }

28       if( line[t] == '(')

29         {

30           parenthesis++;

31         }

32       if( line[t] == ')')

33         {

34           parenthesis--;

35         }

36       if( line[t] == '\'')

37         {

38           s_quote *= -1;

39         }

40       if( line[t] == '"')

41         {

42           d_quote *= -1;

43         }

44       t++;

45     }

46     }

47   if(d_quote !=1)

48     printf ("Mismatching double quote mark\n");

49   if(s_quote !=1)

50     printf ("Mismatching single quote mark\n");

51   if(parenthesis != 0)

52     printf ("Mismatching parenthesis\n");

53   if(brace != 0)

54     printf ("Mismatching brace mark\n");

55   if(bracket != 0)

56     printf ("Mismatching bracket mark\n");

57   if( bracket==0 && brace==0 && parenthesis==0 && s_quote == 1 && d_quote == 1)

58         printf ("Syntax appears to be correct.\n");

59   return 0;

60 }

61 

62 int getline(void)

63 {

64   int c, i;

65   extern char line[];

66   

67   for ( i=0;i<MAXLINE-1 && ( c=getchar()) != EOF && c != '\n'; ++i)

68     line[i] = c;

69   if(c == '\n') 

70     {

71       line[i] = c;

72       ++i;

73     }

74   line[i] = '\0';

75   return i;

76 

77 }

 

你可能感兴趣的:(程序设计)