COS 126 FAQs

COS 126 Frequently Asked Questions



This document contains answers to some commonly asked questions in COS 126. If you know of a question that many people have unnecessarily been struggling with, please send email to cs126@cs with the subject COS 126 FAQ. The list is broken up into the following general categories.
  • Assignments
  • Working At Home
  • Unix
  • Common C Programming Bugs
  • C Programming
  • PostScript
  • Java
  • Lecture

  • Assignments

    My program doesn't work. I try to compile it and it just list and endless stream of errors. Should I just give up? No! Everyone makes such mistakes - they're called syntax errors. This means your code does not conform to the very rigid rules of C syntax. Get used to it. If your program doesn't compile, look at the first error message and try to figure out what you did wrong. A single typo can generate a very long stream of error messages, so don't despair. The compiler will give you a line number along with a description of the error. Identify the first error and try to fix it. Recompile and repeat this process until it compiles.

    My program compiles but doesn't give the right answer. Should I just give up? No! If your program compiles, but doesn't work properly, you will need to determine what went wrong on your own. (These errors are often called bugs, because in the old days an insect could fly into the computer and the code you had labored over painstakenly for days would no longer work.) For small programs, the printf method is often the quickest and most effective approach. There are more powerful methods for experienced programmers (see gdb below), but these require quite a bit of effort to master. The idea of the printf method is to print out the values of variables, including index variables in a loop. This will help you pinpoint where the problem is occurring. Figure out what you intended the computer to do and where it did something different. Sometimes, it is something as simple as using = instead of == in a logical expression.

    My program still doesn't work. Help me please! Before you become excessively frustrated and violent, seek advice from classmates, lab assistants, and preceptors. Sophomores are also quite useful. They have all experienced the same frustration at some point in their programming career and will be very sympathetic.

    How heavily do I need to comment my code? Ask your preceptor. Your code should be easily understandable by you and by the grader. Well written code often speaks for itself and needs little commenting. Always use consistent indenting to make your code more readable.

    What's a readme file? It's a single text file (you can create it with emacs), that you will submit with every assignment. It should contain a brief narrative documenting what the various portions of your code do and how they do it. It should also include all of the output that the assignment asks for. Be sure to write this file carefully; the grader will read this file first. See /u/cs126/examples/readme for a sample readme file.

    How do I check whether my homework has really been submitted? Enter the Unix command /u/cs126/bin/submit 1. It will list all of the files that you have submitted for Assignment 1.

    Where can I find helpful clarification to the assignments and online versions of the sample code provided? Go to the Assignments page.


    Working Outside CS101

    Can I work from home? Yes, if you are familiar with telnet you can login to the arizona machines remotely and do almost everything from home. Unfortunately, the graphical interface will be lost (e.g., no multiple windows, the mouse will not work in emacs, you will not be able to view images using gs).

    I can't save a file in emacs remotely with Ctrl-x Ctrl-s from my MacIntosh. What's wrong? The default CIT telnet setup maps Ctrl-s to "suspend output" and Ctrl-q to "resume output." These are antiquated commands. Go to the menu "session", select "setup keys", and delete the last two entries. (It may also be possible to use Ctrl-x s instead.)

    Can I write my C code using Windows instead of Unix? Yes, a version of the lcc compiler is availalbe for Windows 95 - NT. Adventurous souls can look into lcc-win32. Keep in mind your programs must still compile properly under Unix and some assignments require you to use Unix.

    Are there other clusters capable of running X-Windows? To the best of our knowledge, none of the clusters in the residential colleges are X-Windows capable. The only other public X-Windows capable cluster is in the E-Wing of the equad on the 4th floor. These are not staffed with lab assistants.

    How do I enter the EOF signal from the keyboard? EOF means end of file. By default, it is usually Ctrl-z on PC's and Ctrl-d on Mac's.

    How do I view and print a PostScript file on a PC? You can download a PostScript viewer from the Ghostview home page.


    Unix

    How do I get the backspace key to work? The "erase" function may have been mapped to the delete key instead of the backspace key. Either use the delete key or change your shell as described below. Alternatively, an ugly fix is to enter the Unix command stty erase ^H. Here ^ means Shift-6.

    How do I enter the EOF signal from the keyboard in Unix? EOF means end of file. By default, it is usually Return Ctrl-d.

    The Unix command lpr hello.c doesn't work. Instead it reports _default: unknown printer. There is no default printer setup. The printer in COS 101 is named psr. Use the Unix command lpr -Ppsr hello.c to print your file. Alternatively, use the Unix command setenv PRINTER psr and lpr hello.c will work.

    I accidentally named my program hell.c. What do I do? The Unix command mv hell.c hello.c will rename the file appropriately.

    The lcc compiler gives me a warning message that says "warning: missing return value". If you'd like to eliminate the warning, replace main with void main in your program. By default, all functions are supposed to return integers. The void means that this function should not return anything. It is actually safe to ignore this warning, but we do not reccommend it; in the future, the compiler warning messages may signify a serious error, and paying attention may save you alot of time in subsequent debugging!

    I need help with Unix. Check out the web site Unix Help for Users.

    What does Unix stand for anyway? It is not an acronym, but is a pun on "Multics". Multics is a large operating system that was being developed shortly before UNIX was created. Brian Kernighan (of K+R) is credited with the name.

    Where can I find a tutorial or cheatsheet for emacs? Type Ctrl-h t in emacs to get an on-line tutorial. For a cheatsheet, follow the link

    How can I get the output of a.out into a readme file? You can use the X-Windows cut-and-paste options. A more systematic way is to enter the Unix command a.out > readme. This redirects the output of a.out into the file readme (instead of to the screen). You can still input data from the keyboard (e.g., if your programs call scanf). However, the screen will be blank, as all output (including printf statements) goes to the file, not the screen.

    How can I get the output from several programs into one readme file. The Unix command a.out > readme overwrites the original readme file. Use a.out > readme the first time. This creates the file readme, and puts the output of a.out into it. If the readme files already exists, use the Unix command a.out >> readme to append to it.

    What does !! do? It is shorthand for re-running the previous Unix command. Also, the command !lc will re-run the most recent Unix command that starts with lc, perhaps lcc myprogram.c

    What exactly is piping? We only answer the question with respect to Unix. :) Piping connects the standard output stream of one Unix program into the standard input stream of another. This is best demonstrated by example. To send the output of a.out to the printer, you could enter the following three Unix commands. a.out > temp, lpr temp, rm temp. The first command redirects the output of a.out to temp. (See above.) The second prints the file temp, which now contains the appropriate output. The third command cleans up and removes the file temp. The Unix command a.out | lpr does the same thing, without creating and deleting the intermediate file.

    If I telnet to arizona, how can I exit out of emacs and compile my C code? The emacs command Ctrl-x Ctrl-c exits you out of emacs permanently. The command Ctrl-z temporarily suspends emacs and lets you type in Unix commands like lcc hello.c. To return to emacs type the Unix command fg which puts emacs in the "foreground".

    How can I compile my code from within emacs? See customizing emacs below. After you have done this, just type Ctrl-c Ctrl-c and the Return key and emacs will automatically compile your file, creating a window to display any error message. If there are errors, type Ctrl-c Ctrl-n to jump to the next error.

    How can I customize emacs? You can create a text file called .emacs in your home directory. To copy our sample .emacs file to your home directory, use the Unix command cp ~cs126/.emacs ~. It puts the line number and time at the bottom of the emacs window. It will make emacs to automatically indent after each line. Also you can compile your code from within emacs (see above). Finally, if you use xemacs it will add some nice coloration to your otherwise drab display. Try it and you will love it! Possibilities are endless.

    What is xemacs? It's a X-Windows version of emacs with a nicer graphical interface. If you have access to it, use the Unix command xemacs hello.c & to try it out.

    What is command line editing and file name completion? Command line editing lets you recall previous commands using the arrow keys. Also you can use emacs style commands to edit it. File name completion is when the computer finishes the name of your file after you enter the first few characters. If file name completion is enabled, you can type emacs he followed by the Tab key. It will complete it to hello.c. Of course, it depends on what files are actually in the current directory. You may need to change your shell (see below).

    How do I change my shell to tcsh? The shell is the program that processes your Unix commands. The tcsh is a fancier version of the standard shell. Simply type the Unix command tcsh to change it. To permanently change your shell, enter the Unix command chsh. It will ask you for your password and the new shell. On the arizona machines, it is /usr/princeton/bin/tcsh. Ask a lab assistant for help if you are unsure. As an added bonus, the backspace key should work properly.

    Where can I learn more about grep. See pages 11-25 of Unix Tools for Text Processing. The two sample text files used are virgin and wizard

    Where did the name grep come from? The original UNIX text editor "ed" has a construct g/re/p, where "re" stands for a regular expression, to Globally search for matches to the Regular Expression and Print the lines containing them. This was so often used that it was packaged up into its own command, thus named "grep". According to Dennis Ritchie (of K+R), this is the true origin of the command.

    Are there any automated ways to help me debug my programs? The GNU debugger gdb is such a tool. Not needed for use in COS 126, but useful for creating larger pieces of code. Check out the following link or this one for a tutorial. Here's a gdb cheat sheet.

    How can I view Adobe Acrobat or .pdf files from Netscape? If it's not already setup, on Unix machines you should go into the Netscape 3.04 Options menu and select General Preferences. Then select Helpers. Scroll down to where it says application/pdf. Highlight and click Edit. Check Application and type acroread %s in the box. Now when you click on a .pdf file you can view it automatically.

    How can I run a recent version of Netscape on the arizona machines? On arizona, the Unix command netscape & will run Netscape 3.04. To run Netscape 4.05, use netscape-4.05 & instead.


    Common C Programming Bugs

    Reversing order in assignment statement. In C, = means assignment, not mathematical equality. To replace the value of a with the current value of b use a = b; not b = a;

    Unitialized varaibles. All variables must be initialzed to some value (often to 0 or NULL) before they can be used. Be sure to reinitialize them to their original values when appropriate.

    Assignment vs. logical equals. In C, = means assignment and == means logical equals. To test if two integers represent the same number, use if (a == b) not if (a = b)

    Not giving scanf a pointer as input. The function scanf requires its arguments to be pointers (not integers or floats) so that it can change their values. Use scanf("%d", &a); not scanf("%d", a);

    Extra ; before body of loop. A semicolon at the end of a for or while statement is not part of the syntax. Instead it is treated as an empty statement. So, i = 0; while (i < 17); i++; will cause an infinite loop.

    Off by one errors. C arrays are indexed starting at 0, not 1. So, if a is an N element array. you should use for (i = 0; i < N; i++) a[i] = 0; instead of for (i = 0; i <= N; i++) a[i] = 0;

    Characters vs. Integers. The declaration char c; provides storage for an integer between 0 and 256. Do not use for reading in input with while ((c = getc(file)) != EOF) since EOF has the value -1, which cannot be assigned to a char. Use int c; instead.

    Following a NULL pointer. If link x = NULL when your program accesses x->key or x->next, then your program performs an illegal operation. This causes a segmentation fault error at run-time. Use lcc -n myprog.c to compile your program to eliminate these notorious bugs.


    C Programming

    What's the difference between a local and global variable? Local variables are defined at the beginning of a function. They can only be used within that function. It is fine for different functions to use the same variable names. But, each function only knows about its own local variables. Global variables are defined at the beginning of the file, not inside any function. They can be accessed and modified by any of the functions within the file.

    What's are parameters and arguments of a function? Arguments are used to pass information to a function. The expression f(10,2) calls the function f with two arguments, 10 and 2. Suppose we had a function int f(int m, int n) {return m - n*n ;} The function f has two parameters, m and n. When called, the parameter m is assigned the value 10 and n is assigned the value 2. The parameters m and n can be used just like local variables (see above) within the function f. Thus f(10,2) returns the value 6.

    The compiler complains when I try to use the sqrt and other math functions. First, be sure to #include <math.h> in your program. Also, depending on your setup, you may need to tell the compiler to use the math library, e.g., lcc -lm hello.c

    What's the difference between ++i and i++? Both ++i and i++ increment i by one. They differ in when the increment is performed. For example, suppose i = 17. Then the statement x = i++; sets x=17 and then increments i to 18. In contrast, the statement x = ++i; first increments i to 18, then sets x=18.

    What causes a segmentation fault? Here's the simplest way to generate one. link x = NULL; x->key = 17;. Of course the problem is that you are trying to access the key field of x but it doesn't exist. A similar thing would happen if you write x->next = y; since the next field of x doesn't exist either. This seems like a simple thing to avoid, but often occurs when you change the link x, say in a for loop, so that it sometimes points to a real node and sometimes points to NULL. Here's one way to pinpoint the segmentation fault: replace x->key = 17; with if (x != NULL) x->key = 17; else printf("Here's the seg fault!"); An easier way is to compile your program with lcc -n. Now, when you run your program, code is automatically inserted to check for following null pointers.

    How do I get printf to print a % sign? printf("%%");


    PostScript

    What is PostScript and how do I create it? PostScript is a stack-based language that is used by many printers. Printers have built-in computers that translate the PostScript language into printed output. A PostScript program is a text file (just like a C program). You will write a C program that creates a PostScript program! Use printf statements to print the PostScript program to the screen. Then use redirection to output it to a file, e.g., a.out > picture.ps. Check out
    A First Guide to PostScript for more information.

    How do I view and print a PostScript file? To print a PostScript file named picture.ps, use the Unix command lpr picture.ps. The printer will realize that it is a PostScript program, not just a regular text file. Before printing, make sure that your PostScript program works properly by viewing. The Unix command gs picture.ps will "compile" the program and set up an X-window for you to view it.

    How do I view and print a PostScript file on a PC? You can download a PostScript viewer from the Ghostview home page.

    How do I put comments into my PostScript program? The % in PostScript is analogous to // in C. Upon seeing a %, the rest of the line is ignored. There is one exception - the first line of a PostScript program must begin with %!.

    Could you describe PostScript commands for drawing graphics? Here are some of the most common ones.

  • %! every PostScript program starts with these two symbols - since % is a special symbol with printf, use printf("%%") to print a % sign
  • x y moveto moves turtle to (x,y) without drawing anything - this starts a new path
  • u v rmoveto if current point is (x,y), change current point to (x+u,y+v) without drawing anything - this starts a new path
  • x y lineto moves turtle from current point to (x,y), adding the straight line segment to the current path
  • u v rlineto if current point is (x,y), move turtle to (x+u, y+v) and add the straight line segment to the path
  • closepath adds a straight line segment connecting the current point to the starting point of the current path (typically the point most recently specified by moveto) thereby "closing" the current path
  • stroke draws a line (of some thickness) around the current path
  • fill paints the entire region enclosed by the current path (using the current color)
  • showpage ejects page from printer
  • x setlinewidth change the default line thickness used by stroke to x
  • x setgray changes pen color to shade of gray x, where x is between 0 and 1 (1 = black, 0 = white)
  • r g b setrgbcolor changes pen color of turtle to red-green-blue color (r,g,b), where r, g, b, are values between 0 and 1 - (1,0,0) is red, (0,1,0) is green, (0,0,1) is blue
  • h s b sethsbcolor changes pen color of turtle to hue-saturation-brightness color (h,s,b), where h, s, b, are values between 0 and 1
  • x y translate change origin to (x,y) - 50 50 translate is often used to prevent anything from being drawn in the very lower left margin of the page
  • x1 y1 x2 y2 x3 y3 curveto appends a Bezier curve to the current path from the current point, say (x,y), to (x3,y3) using (x1,y1) and (x2,y2) as "Bezier cubic control points"
  • x y r ang1 ang2 arc appends an arc of a circle to the current path - the arc has radius r, is centered at (x,y), and goes counterclockwise from ang1 degrees to ang2 degrees
  • N { . . . } repeat repeats the statements deliminted by the braces N times
  • /anyname { . . . } defines anyname as a synonym for the statements delimited within the braces
  • /pt { 0 360 arc fill } def this defines a function pt (as on the Mandelbrot assignment) so that x y r pt draws a solid circle (in the current color) centered at (x,y) of radius r

  • Java

    Where can I learn more about Java? Go to
    www.javasoft.com or www.gamelan.com. These widely used sites have on-line tutorials and loads of information and sample applets. Also, if you like the Deitel and Deitel C book, they have a book for Java too. (The Sedgewick book will be available in Java eventually.) Here's a link which describes all Java 1.2 classes.

    Where can I download a free Java compiler for Windows? Go to www.javasoft.com. The latest version is (at least) 1.2.1. A full installation requires about 65MB.

    Is there a good editor like emacs to use with Java? Under Unix, emacs works for Java just like it does for C. Under Windows, you can use Notepad - it doesn't have the same functionality as emacs, but will do the job.

    Where can I find some really great Java demos? Follow the link to www.jars.com. Stand back. Much of the source code is available, so you can use it as a starting point to design your own sophisticated Web applet.

    How can I run Java 1.2 instead of Java 1.1 on arizona? By default the arizona machines are setup to run Java 1.1. You are better off using Java 1.2. Use /usr/java2/bin/javac and /usr/java2/bin/appletviewer instead of javac and appletviewer.

    I can't get appletviewer to work on arizona. What's wrong? First, make sure that you have compiled MovingBall.java with the command javac MovingBall.java. Then the command appletviewer MovingBall.html should work fine on the arizona machines. On some machines, the DISPLAY variable needs to be changed from :0.0 to localhost:0.0. In principle, these are the same, but it appears to cause a problem with appletviewer. To change it, type the Unix command setenv DISPLAY "localhost:0.0".

    I can't get my Java program to work under appletviewer or Netscape on my PC. What's wrong? You may not have the latest version of the Java Runtime Environment. You can download from www.javasoft.com. It's about 10MB.

    How come my Java program doesn't work under Netscape? Older versions of Netscape do not support all of the features in Java. You probably need Version 4 or later (maybe even 4.5). In arizona type netscape-4.05 instead of netscape. To reload an Applet, use Shift-Reload.

    For debugging in C, I use the "printf method." How can I do the same thing in Java? Use the method System.out.print or System.out.println as used in the lecture notes. Output will be written to the arizona prompt, rather than to the Java window, but this should be sufficient. Note that there is no formatted printing in Java (i.e., can't use things like %9.3f).

    If I run appletviewer, the output of System.out.println goes to a Unix window. Where does it go in Netscape? View with the Netscape menu option Communicator-Tools-Java console.

    What's a class? It's the idealization of an ADT - a data structure along with associated functions to manipulate the data.

    What's an object? It's a particular instance of the class. An object of class Rational is a single rational number.

    What's a method? A method is one of the functions associated with the data in the class. For class Rational, a method might be add.

    How do I allocate memory for a new object? There is no automatic memory allocation for data objects in Java (except for intrinsic data types like int). There is no malloc either. Use the new operator, e.g., r = new Rational(3,8).

    What's a constructor? It is the method that gets called when you initialize a new object with the operator new. The constructor shares the same name as the class.

    What is overloading? Whenever a class has two methods with the same name, but different arguments, the method is overloaded. Java knows the data types of each object, so it knows to call the appropriate overloaded method, depending on the arguments.

    What's a static data element or method? It's a data element or method that is not associated with an individual class object, but rather with the class as a whole. This plays the role of a global variable. A good example is the static variable N in Nbody.java which counts the number of Body objects.

    What are public and private data elements and methods? Public data elements and methods can be accessed by any classs. Private members can only be accessed by other members of the same class.

    What are final data elements and methods? A final data element is one whose value can't be changed after initialization. A final method is one that can't be overridden by classes that inherit it.

    What is this? The keyword this within a method is a reference to the object itself.

    What are try, catch, finally, and throws used for? Java supports (and enforces) exception handling. Functions return not only their value, but also any errors that occurred (e.g., division by zero, not enough memory).

    What is garbage collection? In C you must explicitly return memory to the system with free when you're done using it (otherwise you get memory leaks). In Java, the system is clever, and periodically checks to see which memory you are done with, and reclaims it.

    What does extends do? Java supports (single) inheritance. The declaration class Nbody extends Applet means that the new class Nbody will inherit all of the data object and methods of the built-in parent class Applet. Objects of a subclass will have access to all of the non-private data and function members of the parent class. This includes support for graphics and a user-interface.

    What does super do? For a subclass, the super keyword refers to its parent class.

    What is overriding? Whenever a method in a subclass has the same name and arguments of a method in the parent class, the subclass method will replace the previous definition. The methods show, run and start are overridden in Nbody.java.

    What is the control flow of an applet? An applet first calls methods init, start, and then paint. The paint method is called automatically each time the window is moved or resized. The method repaint calls update then paint. In Nbody.java, the start and update methods are overridden.

    What is multithreading? Multithreading enables multiple program to run concurrently, without any one of them hoarding all of the system resources. The Java language directly supports multithreading. This is done in Nbody.java. The run method of Thread is overridden.

    What is multithreading?


    Lecture Material

    Where can I find notes on TOY? These
    TOY notes were specifically written to supplement the COS 126 material. They are very new, and not yet completely finished, but you may still find them quite useful. Comments, corrections, and suggestions to wayne@cs are much appreciated.

    In Lecture 5, what does the "leading bit of the second digit" mean? The instruction 9F24 has 4 hexadecimal digits. The second digit is F and can be expressed in binary as 1111. So, the first (or leading) bit of the second (hexadecimal) digit is 1. Contrast with the instruction 9724. 7 is 0111 in binary. The leading bit of the second digit is 0.

    Where can I learn more about grep. See pages 11-25 of Unix Tools for Text Processing. The two sample text files used are virgin and wizard

    Where can I find notes on formal languages, automata, grammar, and regular expressions? These language notes were specifically written to supplement the COS 126 material. They are new and a few details are missing (e.g., Turing machine examples), but you should find them quite useful. Many practice exercises and solutions are included. Comments, corrections, and suggestions to wayne@cs are much appreciated.

    Where can I find notes on unsolvable problems and NP-completeness? These Unsolvability and Intractability notes were specifically written to supplement the COS 126 material. Last updated 4/18. Comments, corrections, and suggestions to wayne@cs are much appreciated.

    I want to know more about Alan Turing and John von Neumann. Here's the Alan Turing home page. Here's a biography of von Neumann.


    www.CS.Princeton.EDU/~cs126/docs/faq2.html