CS 1355
Introduction to Programming in C
Thursday 2006.11.23
Lecture notes (at http://r638-2.cs.nthu.edu.tw/C/notes/20.txt)
Today: Morse Code homework example
1. main program
- calls a function based on argv[1]
- program name is in argv[0]
2. usage(): just substitute in the program name to a
constant string
3. help(): print the code and symbol, five per column.
if you do the way it is suggested, then it is a
matter of printing all entries of a table.
4. encode():
- converts each character to a code word.
- lower case and upper case are not distinguished
- accepted symbols: letters, digits, spaces, returns
- any other symbol: interpreted as a space
- return is printed as a return
Tricky part: when do you actually print a blank space?
- you need a blank space between each nonblank symbol
- a blank symbol is encoded as three spaces
- however, you should not always print an extra space to
separate code word and the three-blank code word!
Hint: use a state variable to remember whether to print
5. decode():
- convert back from Morse code to A-Z 0-9
- three spaces get printed as one
- all other chars printed as-is
Tricky part: space handling
- if you scan %s, it skips all blanks!
- need to preserve blanks
use the "character set" pattern,
use repeat * to scan multiple
- if blanks found, decide whether it is a codeword delimiter
(single) or the codeword for the space symbol (three blanks)
If not blank, check if it is one of the codewords.
- ok use linear search or binary search to find codeword
(what is linear search? see Lecture 14)
- when found, use the index to retrieve the symbol
- if not found, get the next char from standard input
and print it to standard output
6. testing:
- write and test one routine thoroughly at a time
- test the help() usage() ones first
test encode() before writing decode()
- run the reference executable to compare output format
Example: put input in the file named "in"
% cat in
Hello World lucky 7
Today is 2006 11 23
The Time is 14 56
Goodbye Mylove
% ./a.out -e < in # try encoding, redirecting "in" to standard-input
.... . .-.. .-.. --- .-- --- .-. .-.. -.. .-.. ..- -.-. -.- -.-- --...
- --- -.. .- -.-- .. ... ..--- ----- ----- -.... .---- .---- ..--- ...--
- .... . - .. -- . .. ... .---- ....- ..... -....
--. --- --- -.. -... -.-- . -- -.-- .-.. --- ...- .
% ./a.out -e < in | ./a.out -d # pipe encoded output to decoder
HELLO WORLD LUCKY 7
TODAY IS 2006 11 23
THE TIME IS 14 56
GOODBYE MYLOVE
%
Extra Credit:
- If your code runs faster than the professor's code,
you qualify for extra credit, though you must explain the techniques
you used to make the code run fast.
- Fastest encoder:
if your program runs the fastest in the class,
you will get more extra credit.
- to measure how long a program takes to run, use the time command:
- time to be measured on the workstation
- input to be provided by TA