COS 126
Exercise Set 3
Answers

These programming exercises are intended help review the material on arrays and strings in preparation for the two midterms. Do not turn in solutions.

  1. Modify /u/cs126/examples/stem2.c so that it prints a period (".") and a space for at the positions of the mean and median, respectively. For example:
    % a.out </u/cs126/examples/scores
    10 00
     9 97765510
     8 977655533100
     7 998777666655555444333211100
     6 98877654 4333221000.
     5 44322111111000
     4 888444444311
     3 7655211
     2 865221
     1 65311
     0 8850
    
    shows that the median is 64 and the mean is 60 (it's actually 59.6).
  2. Write a program, wf.c, that lists the number of times the words given as its arguments appear in the input. For example:
    % a.out int while if </u/cs126/examples/stem2.c
    5       int
    3       while
    shows that, in /u/cs126/examples/stem2.c, "int" appears 5 times, "while" appears 3 times, and "if" doesn't appear at all. Your program should be able to handle 100 arguments.
  3. Write a program,fmt.c, that "wraps" the words in the standard input onto 72-character lines, or onto lines whose length is given by the program argument. For example:
    % a.out 60 </u/cs126/examples/scores
    100 100 99 97 97 96 95 95 91 90 89 87 87 86 85 85 85 81 83
    83 80 80 77 76 73 75 77 79 77 76 72 75 73 75 78 74 79 70 75
    76 71 73 71 75 74 76 74 70 71 68 68 66 65 64 64 63 63 63 62
    62 61 60 60 60 67 67 69 54 53 54 51 52 51 51 50 51 52 51 50
    50 51 44 44 44 48 48 44 48 43 44 44 41 41 37 36 35 35 32 31
    31 28 22 22 21 26 25 15 16 13 11 11 8 8 5 0
    Make sure you handle the various "boundary conditions;" for example, your program should do something "reasonable" when it encounters words that are longer than the output line length.

Answers

Try to implement these programs before looking at the suggested solutions.

  1. stem3.c
  2. wf.c
  3. fmt.c

Copyright © 1996 David R. Hanson / drh@cs.princeton.edu
$Revision: 1.3 $ $Date: 1996/10/11 13:36:08 $