Handouts: Course Information; Syllabus; All About Homework; Program Standards; CSIF Accounts; Reading USENET News with tin; Sample Basic C Programs; Pascal and C
Homework: Assignment #1, due Tuesday, October 7, at 6PM
Please post things about the class in the discussion newsgroup ucd.class.ecs40.d. Discussing something in this group is perfectly fair!
Midterm Examination: | Thursday, October 30, in class |
Final Examination: | Sections A01 and A02: Friday, December 12, 4:00PM-6:00PM |
Sections B01 and B02: Saturday, December 13, 10:30AM-12:30PM |
Lab Exam: take-home
This exam will require you to demonstrate that you know how to use gdb, among other things. It will be graded pass/fail.
Programs | 50% | Midterm exam | 20% |
Lab exam | 5% | Final exam | 25% |
A good analogy between appropriate discussion and inappropriate collaboration is the following: you and a fellow student work for competing software companies developing different products to meet a given specification. You and your competitor might choose to discuss product specifications and general techniques employed in your products, but you certainly would not discuss or exchange proprietary information revealing details of your products. Ask the instructor or a teaching assistant for clarification beforehand if the above rules are not clear.
lecture | date | topic |
---|---|---|
1. | Thu, Sep. 25 | Getting Started; Writing and Compiling C |
2. | Tue, Sep. 30 | C Program Basics, Operators |
3. | Thu, Oct. 2 | Operators, Control Flow |
Discussion | The UNIX File System | |
4. | Tue, Oct. 7 | Pointers, Command-Line Interface |
5. | Thu, Oct. 9 | Pointers; Storage, Structures, Casting |
Discussion | UNIX Processes and Shells | |
6. | Tue, Oct. 14 | Functions and Scope; Program Stack |
7. | Thu, Oct. 16 | Recursion, Program Stack |
Discussion | Internet, World Wide Web | |
8. | Tue, Oct. 21 | Preprocessor |
9. | Thu, Oct. 23 | Standard I/O Library |
Discussion | Other Libraries | |
10. | Tue, Oct. 28 | UNIX/process interface, system calls |
11. | Thu, Oct. 30 | midterm |
Discussion | Review for Midterm | |
12. | Tue, Nov. 4 | C compiler details, make |
13. | Thu, Nov. 6 | Debugging, gdb |
Discussion | Introduction to C++ | |
14. | Tue, Nov. 11 | Modularity and Interfaces; Portability |
15. | Thu, Nov. 13 | Robust Programming |
Discussion | Data Abstraction in C++ | |
16. | Tue, Nov. 18 | Top-Down Design |
17. | Thu, Nov. 20 | Bottom-Up Design, Toolkit Approach |
Discussion | Overloading in C++ | |
18. | Tue, Nov. 25 | Rapid Prototyping, Shell Programming |
Thu, Nov. 27 | Thanksgiving Holiday | |
Discussion | no section meetings | |
19. | Tue, Dec. 2 | Profiling |
20. | Thu, Dec. 4 | Conclusions and review |
Discussion | Review for final |
When you are asked to analyze something, or explain something, please be complete, and show your work (including any commands you give, and their output, to show how you did the problem); if you don't, your answer must be exactly the correct one or you get no points. Think your answer through and do a rough draft before you begin to write or type. Write clearly and cogently. If the question asks for an opinion, state your opinion clearly, and don't ramble. Answers which start, "My opinion is yes ..." and conclude with " ... so on the other hand I guess it could be no equally well" won't get much credit.
Do not leave assignments for the last minute. The assignments will require significant design time before you start programming and debugging. When we decide on the due dates, we assume you will spend significant amounts of time on design as well as coding and debugging. If you choose not to do this, you will have difficulty finishing the assignments on time.
We do not mind being asked for help; indeed, we welcome it because it helps us know what the students are finding difficult or confusing, and sometimes a few words about the problem in class will clarify the assignment immensely. We do mind being asked for help before you have tried to think the problem through; the classic objectionable question (this really happened) occurred on a homework assignment in which the class was given a buggy program. The assignment said the program did not work, and the homework was to debug it and make it work. Within 10 minutes of the end of the class during which the assignment was given out, we got a request for help: "The program doesn't run. What do I do now?"
So, before asking for help, please be sure that you have:
handin cs40r hw3 getnum.c printnum.cThis program will submit your files to the ECS 40 grader. Once you submit your homework, you cannot alter it in any way; should you wish to change your answer, make the change and resubmit the homework. We'll take the date and time of the last file you submit as the date and time of submission of your homework, and base lateness on that.
A manual page for the handin program is at the end of this section.
Some assignments will ask you to show the output on your screen; programming assignments require that you submit a sample run (using either your data or, if we give you some, our data). To do this, use the script(1) program to save the output into a file. For example, suppose the program you had to write is called randx and generates random numbers between 30 and 60. The number of numbers it produces is given by a command line argument. Here's how you would generate the file for the output (you type what is in boldface):
dec32 % script hw1-4-run typescript started, file is hw1-4-run dec32 % randx 5 34 49 58 43 38 dec32 % exit dec32 % dec32 %Then the file hw1-4-run contains the command, and output, given above. Submit it as above.
If you want to be sure your submission made it, execute
handin ecs40r hw3and you'll get a list of what you have submitted so far:
The following input files have been received: Thu Mar 17 14:50:49 1994 1599 bytes getnum.c Thu Mar 17 14:50:49 1994 3412 bytes printnum.cWe expect any file you submit to be readable as is on the instructional DECStations. This means that you are free to type in your answers on your personal computer (or anywhere else), but we'll use more, cat, lpr, or one of the UNIX text editors to read the file. So be sure to look at what you're going to turn in on the instructional DECs before you turn it in!
We also expect any program you submit to compile (using the gcc(1) compiler with the -ansi and -Wall flags, unless stated otherwise) and execute on the instructional DECStations without change. (Don't forget to include those header files, programs, and other parts when we give them to you!) This means that you are free to develop your program on your personal computer (or anywhere else), but we'll use your Makefile to compile whatever you submit. So be sure to test what you're going to turn in on the instructional DECs before you turn it in!
To see if a homework is late, we check the submission times on the electronically submitted homework. The latest date is the one that we use.
Correctness 70%
Documentation, commenting, ease of reading 20%
Clean, readable output 10%
If your program does not compile, the most you can get is 30%.
There is one catch to the grade. If your program does not work correctly, you will be given at least one example of input that produces an error. You must fix the program, so it does work correctly, within one week of being notified. If you do not, your score on the assignment will become 0%. When you resubmit the fixed assignment, submit the entire fixed assignment to hwn-fix; for example, if the above had a bug in getnum.c, you would fix the bug and then do:
handin cs40r hw3-fix getnum.c printnum.c
All grade appeals must be made within two class periods of when the returned assignments were made available. After that, we won't look at it.
handin touser [ subdirectory [ files ... ] ]
example1% handin cs101 Existing subdirectories (comments in parentheses): Asn1 (Due Mar 18) Asn2 (Due Mar 25) example2% handin cs101 Asn1 part1 part2 Submitting part1... ok Submitting part2... ok example3% handin cs101 Asn1 The following input files have been received: Thu Mar 17 14:50:49 1994 1599 bytes part1 Thu Mar 17 14:50:49 1994 3412 bytes part2
Skipping file: file non-existant or irregular
The named file didn't exist or was probably a directory. The user should check to make sure that the file they specified was indeed the file they intended to submit.
Skipping file: file not readable
The named file was not readable by the user.
Submitting file... failed [: reason ]
The named file was not successfully submitted. If at all possible a reason is
provided by rcvhandin(8).
Submitting file... ok
The named file was successfully submitted.
Code Indentation and Formatting must follow the standard C style, which is illustrated in the text. It's not the prettiest style but it is quite standard. Please indent eight spaces (a tab) for each level of indentation.
Capitalization rules in C are also fairly standardized, although a bit unpleasant. Every part of your code must be in lowercase, except for names of macros, defined types, and enumerated constants which are entirely UPPERCASE.
Comments should be used to make programs absolutely clear. Use them liberally but not so much that the meaning gets submerged.
You should comment your program as you write it. It is actually much faster than going back later, and comments are very useful when debugging. (If what the comment says the code does is different than what it really does, you found a bug.) Graders, teaching assistants, and instructors reserve the right to refuse to look at uncommented programs.
ECS 40 "house standards" call for four kinds of comments; we'll describe each in turn.
/* * * hashtest.c Sam Bent date unknown * * Test hash table routines. Loop endlessly, requesting keys from * stdin. If key doesn't exist, insert it in the table with value * n (where it's the n-th key added to table). If key does exist, * print its stored value of n. * * Modification History: * * 1 Jan 94 Matt Bishop; changed to conform to ECS 40 style * 29 Nov 90 Chip Elliott; changed to conform to CS 23 style * and use ANSI C. * */The comments at the beginning of a file, collectively called its "header," must contain your name in addition to other general information about the program and what it does. The date when the program was written and a history of major modifications are required.
Complex data structures used by a file should be illustrated with a figure, as shown below.
* HASHTABLE hashstruct * +-------------------+ Allocated Block * ht -> | ht_ID | of HASHSLOTs * +-------------------+ +-----------------+ * | ht_size | +->| .... | * +-------------------+ | +-----------------+ * | ht_cnt | | | .... | * +-------------------+ | +-----------------+ * | ht_curslot | | | .... | * +-------------------+ | +-----------------+ * | ht_slots |-+ | HASHSLOT |----+ * +-------------------+ +-----------------+ | * .... | * .... | * +-----------------------------------------------+ * | * | hashentry * | +----------------+ +-----------------+ * +-> | h_key |--> | key's text | * +----------------+ +-----------------+ * | h_val | * +----------------+
/* * ht_enter * * Enter a key into a hashtable and return its HASHSLOT. * If necessary, expand the table to hold the new key. * If the key is already there, just return its HASHSLOT. * * Entered by: ht -- hash table * *key -- key to enter * * Exits with: key in hashtable * if newly created, its val.p field is * set to NULL * ht possibly expanded * returns key's HASHSLOT * * Exceptions: "parameter is not a hash table" (fatal) * "not enough memory to enter item into * hash table" (fatal) * */ HASHSLOT ht_enter(HASHTABLE ht, char *key) {Each function must have its own header. The reader should be able to determine what a function does and how to use it by reading only this header information. Things like global variables referenced or modified, assumptions about the input, or anything else that the reader should know before "lifting" a function and using it in another program should go here. So should the algorithm used, if it's not absolutely clear.
One thing that you may not be familiar with is input and output assertions. "Input assertions" is a fancy way of saying "I assume this about the input." For example, for a square root routine sqrt(x), the usual input assertion is "x > 0." Output assertions are similar -- they describe what is true after the function has been called. It is a good habit to get into writing these assertions. It helps you specify exactly what the routine does, and this is precisely the information that someone needs to know in order to lift your routine and use it elsewhere.
You should also include a list of Exceptions, i.e., unusual/error cases and what the function does with them.
If you borrow code from another source (a fine idea, by the way) you should cite the author, book, and -- if possible -- page numbers. Be specific enough so another reader can find the reference.
/* * update ht's HASHSTRUCT contents */ /* first, copy size and count */ ht->ht_size = newht->ht_size; ht->ht_cnt = newht->ht_cnt; /* release old hash slots, start using new ones */ free(ht->ht_slots); ht->ht_slots = newht->ht_slots; /* free newht's HASHTABLE */ free(newht);When you write pseudo-code or describe how a subroutine accomplishes its task ,you usually break it down into a series of steps. (To insert an item into an array you find where it belongs, move everything after it down one place, and finally copy the item into the correct position.) These steps sometimes become subroutines with descriptive names, but often they become half a dozen lines of code. In this case, it helps to write a comment that explains the purpose of the next section of code. The first comment is an example of this kind of comment.
Sometimes a paragraph comment is completely boxed, like this:
/*********************************** * update ht's HASHSTRUCT contents * ***********************************/These are also called boxed comments. You can use this style if you prefer.
main() { HASHTABLE ht; /* ht = hashtable */ HASHSLOT *hp; /* hp = ptr to hash table entry */ int n=O; /* n = key number (put into ht) */ char key[100]; /* key = entry's key */ /* * create a new hash table */ ht = ht_create(0); /* * loop, reading input and acting accordingly */ for(;;){ /* prompt and get input */ printf("Key: "); scanf("%s", key); /* * if "dump", show what's in the hash table */ if (strcmp(key, "dump") == 0){ /* bingo -- dump the hash table */ ht_dump(ht); continue; } /* * enter the key into the hash table * announcing if it is already there */ hp = ht_enter(ht, key); if (hp->h_data == NULL){ /* key is new -- say so, and store it in entry */ printf("%s is a new key, number %d. ", key, ++n); hp->h_data = (caddr_t) n; } else{ /* key is new -- say so, and store it in entry */ printf("%s is key %d. ", key, (int) hp->h_data); } } }In declarations. Explain the use of constants, types, and variables. Part of this is choosing descriptive names. Avoid single-letter names (except for i, j, k, and their ilk as loop variables when nothing more descriptive is useful). Most of the time you should supplement this with a more descriptive comment when the constant, type, or variable is declared. Sum is a fine variable name for a partial sum, but its declaration should state whether it is summing the grades for an exam, the cost of books for a given term, or whatever. Put these comments at the end of each declaration line, and align the beginning of the ordinary comments in a set of declarations, as shown. If the comment takes more than one line, align the second line too.
In code. Comments should also be placed above a line of code if it will clarify what the code does. These comments should explain how that particular line of code fits into the general scheme of things. The comment:
/* Assign item to ith position of list */ list[i] = item;is worthless. It simply repeats what the code says. Assume that the reader can read the code, and explain the purpose of the statement. The comment:
/* Put item to be inserted into empty spot */ list[i] = item;is much better. These comments are especially useful if the code is somewhat tricky or non-intuitive, and if an innocent-looking statement has consequences not obvious from the statement itself.
Align all these ordinary comments with the beginning of the line they explain. Otherwise they are messy and distracting.
We would like to also comment on the infamous goto statement. The uncontrolled use of goto can make programs totally unintelligible, and many of you have probably been convinced that a goto statement is programming's worst sin.
We consider goto statements justifiable in one case: "error bailout." In some cases, functions call other functions (often recursively) and it is possible to get 20 or 30 nested calls. If at this point an error is discovered, that error must be passed back up through the 20 or 30 calls. Each function must deal with the question "what should I do if this function I am about to call finds an error?" This is certainly doable and can sometimes lead to better error recovery, but functions must pass and test error flags everywhere. A goto back to the top level, if carefully used and properly commented, can greatly simplify life. We will discuss both approaches later in class.
If your name does not appear on this list, either you already have an account on the Computer Science instructional machines, or your name was not included on the class lists that we got from the registrar. The latter may occur if you have added a Computer Science class, as opposed to pre-registering for one. In this case, your account will be added the day after we receive notification from the registrar that you have added the class. Your account name and login name will then be posted as described above.
An initial password has been assigned to your account: the last 8 numeric digits of your student id number. (The student id number has 9 numeric digits in it, so omit the first one, and omit the hyphens to form your initial password.) Because your student id number is something that other people can probably find out about you, a password based on your student id number is not very secure. That is, someone other than you could login to your account, including hackers. Since you are the only one who is authorized to use your account, it is imperative that you change your password as soon as possible. Use the yppasswd(1) command when logged in to the Computer Science instructional machines to do so. If you have not changed your password by 5pm on the Monday of the second week of classes, logins on your account will be disabled. To get logins on your account re-enabled, stop by room 047, whee the student assistants are located. You will need to bring your student id card.
Disk quotas have been installed. You may store no more than 10 Mbytes of data in your home directory.
If you have any questions, send mail to "support".
dec1, ..., dec62 | Digital Equipment Corp. workstations running Ultrix |
sgi1, ..., sgi23 | Silicon Graphics, Inc. workstations running IRIX |
hp2, ..., hp25 | Hewlett-Packard workstations running HP/UX |
To open more DECterm windows, select DECterm from the (SM) system manager's Applications menu.
To end your session, select Quit from the (SM) system manager's Session menu.
Similar commands and actions work on the SGI's and the HP's.
ULTRIX V4.4 (Rev. 44) (dec32) login: bishop Password: note my password is not echoed! Last login: Mon Sep 20 16:11:56 from nob.cs.ucdavis.e ULTRIX V4.3 (Rev. 69) System #1: Mon Aug 19 10:02:26 PDT 1996 UWS V4.4 (Rev. 11) Welcome to the CSIF! You have mail. dec32 1> setenv TERM vt100 be sure to do this first... dec32 2> vi sort.c ...then precede with normal lifeFrom workstations which do not run X Windows, you cannot use X-window tools. But you can access any of the UNIX machines from your dorm room. And all the really important tools (vi, gcc, etc.) work just the same on a plain terminal interface as they do through X Windows.
To open more terminal windows, use rlogin or telnet to create more connections to the UNIX machine. You'll have to log in for each new window.
To end your session, just log out.
The little caret, as in ^C, means "press the control key while typing C."
What | At Workstation | Over the Network |
---|---|---|
delete previous character | DEL | ^H |
delete line | ^U | ^U |
kill a running program | ^C | ^C |
end of file on standard input | ^D | ^D |
escape key (useful for vi) | F11 | ESC |
dec32 29> vi hi.c use vi to create/edit a new file hi.c "hi.c" [New file] 10 lines, 135 characters dec32 30> gcc -ansi hi.c run the c compiler ccom: Error: hi.c, line 9: syntax error printf("hi there!"\n); ----------------------^ volta 31> vi hi.c use vi to fix syntax errors "hi.c" 10 lines, 135 characters dec32 32> gcc hi.c run the c compiler again dec32 33> a.out it compiled, so run the executable hi there! dec32 34> lpr hi.c print the source file dec32 35> lpq check the printer queue hexus is ready and printing via dev Rank Owner Job Files Total Size 1st bishop 49 hi.c 135 bytes dec32 36> mail myfriend mail a note to your friend Subject: hi.c written this is part of the letter Here's my first C program! It just says hello, but it does compile and execute cleanly. ~r hi.c read message text from file hi.c "hi.c" 10/135 . this ends the letter Cc: just hit return dec32 37>
The original program to read news was called readnews(1). Since its inception, a plethora of other programs have been created which improve upon the original readnews, for example, rn(1), xrn(1), trn(1), nn(1), or frn(1). Most of these readers enhance the original by providing better interfaces and threading among followup messages. This handout will describe the basics of a threaded newsreader called tin(1).
To start tin, type
tinIf this is the first time you have used tin, you will get some introductory text as follows:
dec32> tin tin 1.2 PL1 [UNIX] (c) Copyright 1991-93 Iain Lea. Connecting to news.ucdavis.edu... ***************************************** * Welcome to news.ucdavis.edu * ***************************************** On the Information Resources computers: Tin now uses pico as the default editor. If you wish to use vi as your editor in tin, run 'tin-vi' at the Unix prompt. If you are a faculty member and would like to set up newsgroups for class use, mail usenet@ucdavis.edu. (or other campus groups, clubs, etc.) If you have questions about the use of tin 1.2, you can mail ithelp@ucdavis.edu, or call the IT-CAP at 2-2548. Any problems regarding the functionality of tin should be reported to usenet@ucdavis.edu Press any key to continue... Reading news active file... Reading attributes file... Reading newsgroups file... tin 1.2 PL1 [UNIX] (c) Copyright 1991-93 Iain Lea. Welcome to tin, a full screen threaded Netnews reader. It can read news locally (ie. <spool>/news) or remotely (-r option) from a NNTP (Network News Transport Protocol) server. tin -h lists the available command line options. Tin has five newsreading levels, the newsgroup selection page, the spooldir selection page, the group index page, the thread listing page and the article viewer. Help is available at each level by pressing the 'h' command. Move up/down by using the terminal arrow keys or 'j' and 'k'. Use PgUp/PgDn or Ctrl-U and Ctrl-D to page up/down. Enter a newsgroup by pressing RETURN/TAB. Articles, threads, tagged articles or articles matching a pattern can be mailed ('m' command), printed ('o' command), saved ('s' command), piped ('|' command). Use the 'w' command to post a news article, the 'f'/'F' commands to post a follow-up to an existing news article and the 'r'/'R' commands to reply via mail to an existing news articles author. The 'M' command allows the operation of tin to be configured via a menu. For more information read the manual page, README, INSTALL, TODO and FTP files. Please send bug reports/comments to the programs author with the 'R' command.Next, you will be presented with a menu similar to that shown below. The first column indicates the number of each newsgroup, the second column shows the number of new messages in that group. The third column holds the actual name of the newsgroup while the last column gives a brief description of what the newsgroup is about. Use the arrow keys to move the cursor back and forth to select which group to read. At the bottom of the screen is a help menu which lists commonly used commands. Type H for a more complete help screen. Use PgUp or PgDn to move by a whole screen at a time. You may also use vi(1) commands to move; K up, J down, ^F to scroll forward one screen, and ^B to scroll backwards one screen.
1 188 ucd.forsale Things for sale (offers and requests) 2 180 ucd.general Items of general interest to UCD and D 3 18 ucd.jobs Jobs offered and wanted 4 402 ucd.life Davis Chatter 5 23 ucd.housing Rentals available in Davis 6 113 ucd.itcap IT-CAP announcements 7 287 ucd.test Post test messages here 8 5783 ba.general Announcements of general interest to a 9 6504 ba.jobs.offered Job Postings in the Bay Area. 10 1828 ca.general Of general interest to readers in Calf 11 28937 misc.forsale Short, tasteful postings about items f 12 7684 rec.bicycles.misc General discussion of bicycling. 13 23817 rec.humor Jokes and the like. May be somewhat o 14 3565 rec.pets Pets, pet care, and household animals <n>=set current to n, TAB=next unread, /=search pattern, c)atchup, g)oto, j=line down, k=line up, h)elp, m)ove, q)uit, r=toggle all/unread, s)ubscribe, S)ub pattern, u)nsubscribe, U)nsub pattern, y)ank in/outTo add a new newsgroup, use the goto command. After you type g, tin will prompt you for the newsgroup to go to. To subscribe to the newsgroup used in this class, enter ucd.class.ecs40. After determining the newsgroup, tin will ask you where to put the new group in the list. Type 1 to put it first in the list of newsgroups.
Goto newsgroup []> ucd.class.ecs40 Position ucd.class.ecs40 in group list (1,2,..$) [18]> 1The newsgroup will be placed into position 1 of your list. Your main menu will now look something like:
1 7 ucd.class.ecs40.sec01 Intro Software Development 2 188 ucd.forsale Things for sale (offers and requests) 3 180 ucd.general Items of general interest to UCD and D 4 18 ucd.jobs Jobs offered and wanted 5 402 ucd.life Davis Chatter 6 23 ucd.housing Rentals available in Davis 7 113 ucd.itcap IT-CAP announcements 8 287 ucd.test Post test messages here 9 5783 ba.general Announcements of general interest to a 10 6504 ba.jobs.offered Job Postings in the Bay Area. 11 1828 ca.general Of general interest to readers in Calf 12 28937 misc.forsale Short, tasteful postings about items f 13 7684 rec.bicycles.misc General discussion of bicycling. 14 23817 rec.humor Jokes and the like. May be somewhat o <n>=set current to n, TAB=next unread, /=search pattern, c)atchup, g)oto, j=line down, k=line up, h)elp, m)ove, q)uit, r=toggle all/unread, s)ubscribe, S)ub pattern, u)nsubscribe, U)nsub pattern, y)ank in/outYou should also subscribe to the newsgroup ucd.class.ecs40.d, the discussion newsgroup for the course.
To read the messages in a newsgroup, move the cursor onto the newsgroup and press enter. You will be presented with a new menu similar to the one shown below. As always, a help menu is available at the bottom of the screen, and you may use the arrows to move and select which article to read. New articles are denoted by a + sign. If a number is next to an article, it indicates how many other articles are in that "thread." In this example, one article has been posted in reply to the article from Michelle Hoyle entitled "Comments on Assignment 1".
ucd.class.ecs40.d (3T 1A 0K 0H) h=help 1 + This Newsgroup Matt Bishop 2 +1 Comments on Assignment 1 Michelle Hoyle <n>=set current to n, TAB=next unread, /=search pattern, ^K)ill/select, a)uthor search, c)atchup, j=line down, k=line up, K=mark read, l)ist thread, |=pipe, m)ail, o=print, q)uit, r=toggle all/unread, s)ave, t)ag, w=postIf you select the first article and press the enter key, it will be displayed as follows:
Thu, 06 Jan 1994 10:26:40 ucd.class.ecs40.sec01.d Thread 1 of 1 Lines 10 This Newsgroup No responses bishop@nob.cs.ucdavis.edu Matt Bishop at Department of Computer Science, U Just a reminder and a post to get things rolling on this newsgroups. This group is where you, the students, may post and discuss the class assignments or any problems/comments you may have. Hope this helps, Matt Bishop <n>=set current to n, TAB=next unread, /=search pattern, ^K)ill/select, a)uthor search, B)ody search, c)atchup, f)ollowup, K=mark read, |=pipe, m)ail, o=print, q)uit, r)eply mail, s)ave, t)ag, w=postOnce again, useful commands are shown at the bottom of the screen. Press the tab or enter key to read the next message in the thread (if any). Some of the more useful commands are summarized below:
Subject: Re: This Newsgroup Newsgroups: ucd.class.ecs40.sec01.d References: <CJ80KH.5Gz@ucdavis.edu> Matt Bishop (bishop@nob.cs.ucdavis.edu) wrote: : Just a reminder and a post to get things rolling on this newsgroups. : This group is where you, the students, may post and discuss the class : assignments or any problems/comments you may have. Hello, I'd like you to clarify part XXX in assignment ZZZ. Thank you, Diligent but confused ecs40 student.
Check Prepared Article Your article will be posted to the following newsgroup: ucd.class.ecs40.d Intro Software Development (dis)This should be enough to get you started using netnews. Some frequently asked questions follow:
#include <stdio.h> /* * print a table for Fahrenheit to Celsius * from 0 F to 300 F */ void main(void) { int fahr; /* fahrenheit temperature */ int celsius ; /* celsius temperature */ register int lower = 0; /* begin table here */ register int upper = 300; /* end table here */ register int step = 20; /* increment */ /* * print out the lines for the table */ fahr = lower; while(fahr <= upper){ /* get corresponding temp in degrees C */ celsius = 5 * (fahr - 32) / 9; /* print it */ printf("%d\t%d\n", fahr, celsius); fahr += step; } /* * say goodbye */ exit(0); }
#include <stdio.h> #define LOWER 0 /* begin table here */ #define UPPER 300 /* end table here */ #define STEP 20 /* increment */ /* * print a table for Fahrenheit to Celsius * from 0 F to 300 F * floating point version */ void main(void) { float fahr; /* fahrenheit temperature */ /* * print out the lines for the table */ for(fahr = LOWER; fahr <= UPPER; fahr += STEP) printf("%3.0f\t%6.1f\n", fahr, (5.0/9.0) * (fahr - 32)); /* * say goodbye */ exit(0); }
#include <stdio.h> /* * copy input to output: short version */ void main(void) { int c; /* input character */ /* * copy the input to the output * one char at a time */ while ((c = getchar()) != EOF) putchar(c); /* * say goodbye */ exit(0); }
#include <stdio.h> /* * copy input to output: long version */ void main(void) { int c; /* input character */ /* * copy the input to the output * one char at a time */ do { /* read a char */ c = getchar(); /* write a char (unless it's */ /* the end of file marker) */ if (c != EOF) putchar(c); } while (c != EOF); /* * say goodbye */ exit(0); }
#include <stdio.h> #define IN_WORD 1 /* currently inside a word */ #define NOTIN_WORD 0 /* currently not in a word */ /* * count the number of lines, words, and chars in the input * a word is a maximal sequence of nonspace characters, so * the quote "+++ --- hi bye 879+3" has 5 words ("+++", "---", * "hi", "bye", and "879+3") */ void main(void) { register int c; /* input char */ register int nl; /* line count */ register int nw; /* word count */ register int nc; /* char count */ register int state; /* in or not in a word? */ /* * initialize */ nl = nw = nc = 0; state = NOTIN_WORD; /* * handle input a char at a time */ while((c = getchar()) != EOF){ /* got another character */ nc++; /* is it a newline? */ if (c == '\n') nl++; /* is it a word separator? */ if (c == ' ' || c == '\t' || c == '\n') /* YES -- change state */ state = NOTIN_WORD; else if (state == NOTIN_WORD){ /* NO -- we're now in a word; update */ /* the counter and state if need be */ state = IN_WORD; nw++; } } /* * announce the results and quit */ printf("%6d\t%6d\t%6d\n", nl, nw, nc); exit(0); }
#include <stdio.h> /* * count the number of each digit, whitespace, * and all other chars */ void main(void) { register int c; /* input char */ register int nwhite = 0; /* whitespace count */ register int nother = 0; /* other count */ register int i; /* counter in a for loop */ int ndigit[10]; /* digit counts */ /* * initialize the ndigit array */ for(i = 0; i < 10; i++) ndigit[i] = 0; /* * handle input a char at a time */ while((c = getchar()) != EOF){ /* see what it is */ if (c >= '0' && c <= '9'){ /* it's a digit -- bump the right count */ ndigit[c - '0']++; } else if (c == ' ' || c == '\t' || c == '\n'){ /* it's whitespace */ nwhite++; } else{ /* it's neither a digit nor whitespace */ nother++; } } /* * announce the results and quit */ printf("digits: "); for(i = 0; i < 10; i++){ printf("'%c' %3d\t", i + '0', ndigit[i]); /* put 5 digits per line, for neat output */ if (i == 4) printf("\n "); } putchar('\n'); printf("whitespace: %d\nother: %d\n", nwhite, nother); exit(0); }
#include <stdio.h> /* * count the number of each digit, whitespace, * and all other chars */ void main(void) { register int c; /* input char */ register int nwhite = 0; /* whitespace count */ register int nother = 0; /* other count */ register int i; /* counter in a for loop */ int ndigit[10]; /* digit counts */ /* * initialize the ndigit array */ for(i = 0; i < 10; i++) ndigit[i] = 0; /* * handle input a char at a time */ while((c = getchar()) != EOF){ /* see what it is */ switch(c){ case '0': case '1': case '2': case '3': /* digit */ case '4': case '5': case '6': case '7': case '8': case '9': ndigit[c - '0']++; break; case ' ': case '\t': case '\n': /* whitespace */ nwhite++; break; default: /* neither a digit nor whitespace */ nother++; break; } } /* * announce the results and quit */ printf("digits: "); for(i = 0; i < 10; i++){ printf("'%c' %3d\t", i + '0', ndigit[i]); /* put 5 digits per line, for neat output */ if (i == 4) printf("\n "); } putchar('\n'); printf("whitespace: %d\nother: %d\n", nwhite, nother); exit(0); }
#include <stdio.h> /* * prototype (forward declaration) */ int power(int m, int n); /* * generate a table of powers of 2 */ void main(void) { register int i; /* counter in a for loop */ /* * generate the table */ for(i = 0; i < 10; ++i) printf("%3d %6d %6d\n", i, power(2, i), power(-3, i)); /* * bye! */ exit(0); }
/* * compute a power * * arguments: int base what you want to raise * int n non-negative integral power * to raise base to * * returns: base ^ n (base ** n to you FORTRANers!) * * exceptions: none handled; overflow may occur, but there * will be no indication of it */ int power(int base, int n) { register int i; /* counter in a for loop */ register int p; /* resulting power */ /* * do it the obvious, multiplicative, way */ for(i = 1, p = 1; i <= n; i++) p *= base; return(p); }
C construct | Pascal construct |
---|---|
Simple declaration:
type ID, ID;where type is int, float, or char (use int for boolean) |
Simple declaration:
var ID, ID: type;where type is integer, real, char, boolean |
Array declaration:
type ID[];example int scores[5]; access scores[3] |
Array declaration:type ID = array[] of type;example type sc = array[0..4] of integer; var scores : sc; access scores[3] |
Complex declaration:
struct tag { type field_name; } ID;example struct X { int a; float b; } Z;access Z.a, Z.b |
Complex declaration:
type ID = record type ID; end;example type ZT = record a : integer; b : real; end; var Z : ZT;access Z.a, Z.b |
Pointers
type *ID;example int *p; allocate space p = (int *)malloc(sizeof(int)); dereference *p = 6; | |
Pointers to struct
struct tag *ID;example struct X *pZ; reference field pZ->a or (*pZ).a |
Pointers to record
type ID = ^R; type R = record type field_name; end;example type pZ = ^Z; type Z = record a : integer; b : real; end;reference field ^pZ.a |
Unusual Operators
|
Equivalent Operators
|
C construct PASCAL construct Assignment lvalue = right hand side Assignment left hand side := right lvalue evaluates to memory location hand side left hand side is memory an expression, returning as value the location not an expression, no value stored in the lvalue example i value returned example i := 0; = j = 0; shorthand LHS op= RHS means no equivalent to the C shorthand LHS = LHS op RHS example i *= 7; i = i * 7 are the same note that the LHS is evaluated once, not twice, if the short form is used Compound Statements { statement; Compound Statements begin statement; } statement; statement; end Branching: if (expr) statement; else Branching: if bool then statement statement; the else binds to the most else statement; the else binds to previous unmatched if; only one the most previous unmatched if; statement is executed unless you use only one statement is executed a compound statement unless you use a compound statement
C construct PASCAL construct Switch switch (expression){ case Case case expression of val1: val1: statement1; break; case val2: statement1; val2: statement2; no statement2; default: statement3; default end expression evaluates break; } expression evaluates to an to an integer value which is integer value which is compared to compared to the values; the the values in the cases; execution corresponding statement is begins at the matching case; a break executed; failure to match any takes you out of the switch; if value is an error nothing is matched, the default case is executed if present; else nothing is done For Loops: for(expr1; expr2; expr3) For Loops: for ID := expr1 to statement; evaluate expr1; evaluate expr2 do statement; To count expr2; if expr2 is true, do down, say downto rather than to statement, then expr3; reevaluate example for i := 0 to 10 do expr2; repeat until it is false Note write(i ` `); expr1, expr2, expr3 can be any expressions example for(i = 0; i <= 10; i+=1) printf("%d ", i); While Loops: while(expr) statement; While Loops: while boolean do evaluate expr; if true, do statement; statement; while boolean stop loop when expr is false example expression is true, do statement; while(i <= 10){ printf("%d ", i); i stop loop when it is false example += 2; } while i <= 10 do begin write( i:2); i := i + 2; end Do ... While Loop: do statement; Repeat ... until Loop: repeat while (expr); do statement; evaluate statement; until boolean expr; loop until expr is false expression; do statement; evaluate example do { printf("%d ", i); i += boolean expression; loop until it 2; } while (i <= 10); is true example repeat write(i:2); i = i + 2; until i > 10;
C construct PASCAL construct Subroutines return_type ID(parameter Subroutines function ID(parameter list) { body return(value); } No list) : return_type; begin body procedures; everything is a function ID := value; end procedure return_type is void if no value to be ID(parameter list); begin body returned return_type is int by end value returned by assigning to default value returned using return function name statement return value Parameter Passing: always call by Parameter Passing: default is call value pass a pointer to alter the by value declare ID as var in value of a variable parameter list for call by reference C construct PASCAL construct Simple declaration: type ID, ID; Simple declaration: var ID, ID: where type is int, float, or char type; where type is integer, (use int for boolean) real, char, boolean Array declaration: type ID[]; example Array declaration: type ID = int scores[5]; access scores[3] array[] of type; example type sc = array[0..4] of integer; var scores : sc; access scores[3] Complex declaration: struct tag { Complex declaration: type ID = type field_name; } ID; example struct record type ID; end; example X { int a; float b; } Z; access type ZT = record a : integer; Z.a, Z.b b : real; end; var Z : ZT; access Z.a, Z.b Pointers type *ID; example int *p; allocate space p = (int *)malloc(sizeof(int)); dereference *p = 6; Pointers to struct struct tag *ID; Pointers to record type ID = ^R; example struct X *pZ; reference field type R = record type pZ->a or (*pZ)->a field_name; end; example type pZ = ^Z; type Z = record a : integer; b : real ; end; reference field ^pZ.a
C construct PASCAL construct Unusual Operators / division (if both Equivalent Operators / real args are ints, it's integer division; division div integer division mod else float) % remainder && || remainder and or logical and, or logical and, or use lazy evaluation don't use lazy evaluation so all (when value can be determined, don't parts of the expression are evaluate the rest) ++ increment -- evaluated no equivalent to the decrement ?: a?b:c evaluates a; if other operators in C listed at left it's 0, it takes on the value of c; if a is nonzero, it takes on the value of b; only one of b and c is evaluated Assignment lvalue = right hand side Assignment left hand side := right lvalue evaluates to memory location hand side left hand side is memory an expression, returning as value the location not an expression, no value stored in the lvalue example i value returned example i := 0; = j = 0; shorthand LHS op= RHS means no equivalent to the C shorthand LHS = LHS op RHS example i *= 7; i = i * 7 are the same note that the LHS is evaluated once, not twice, if the short form is used Compound Statements { statement; Compound Statements begin statement; } statement; statement; end Branching: if (expr) statement; else Branching: if bool then statement statement; the else binds to the most else statement; the else binds to previous unmatched if; only one the most previous unmatched if; statement is executed unless you use only one statement is executed a compound statement unless you use a compound statement
C construct PASCAL construct Switch switch (expression){ case Case case expression of val1: val1: statement1; break; case val2: statement1; val2: statement2; no statement2; default: statement3; default end expression evaluates break; } expression evaluates to an to an integer value which is integer value which is compared to compared to the values; the the values in the cases; execution corresponding statement is begins at the matching case; a break executed; failure to match any takes you out of the switch; if value is an error nothing is matched, the default case is executed if present; else nothing is done For Loops: for(expr1; expr2; expr3) For Loops: for ID := expr1 to statement; evaluate expr1; evaluate expr2 do statement; To count expr2; if expr2 is true, do down, say downto rather than to statement, then expr3; reevaluate example for i := 0 to 10 do expr2; repeat until it is false Note write(i ` `); expr1, expr2, expr3 can be any expressions example for(i = 0; i <= 10; i+=1) printf("%d ", i); hile Loops: while(expr) statement; While Loops: while boolean do evaluate expr; if true, do statement; statement; while boolean stop loop when expr is false example expression is true, do statement; while(i <= 10){ printf("%d ", i); i stop loop when it is false example += 2; } while i <= 10 do begin write( i:2); i := i + 2; end Do ... While Loop: do statement; Repeat ... until Loop: repeat while (expr); do statement; evaluate statement; until boolean expr; loop until expr is false expression; do statement; evaluate example do { printf("%d ", i); i += boolean expression; loop until it 2; } while (i <= 10); is true example repeat write(i:2); i = i + 2; until i > 10;
C construct PASCAL construct Subroutines return_type ID(parameter Subroutines function ID(parameter list) { body return(value); } No list) : return_type; begin body procedures; everything is a function ID := value; end procedure return_type is void if no value to be ID(parameter list); begin body returned return_type is int by end value returned by assigning to default value returned using return function name statement return value Parameter Passing: always call by Parameter Passing: default is call value pass a pointer to alter the by value declare ID as var in value of a variable parameter list for call by reference
Department of Computer Science
University of California at Davis
Davis, CA 95616-8562