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 wayne@cs with the subject "COS 126 FAQ". The list is broken up into the following general categories.

  • Assignments
  • Working From the Arizona Lab
  • Working on the Arizona System Remotely
  • Creating a Web Page
  • Unix
  • Windows
  • Common C Programming Bugs
  • C Programming
  • PostScript
  • Java
  • Miscellaneous

  • Assignments

    Which operating system should I use? That's a difficult question to answer. OS X is a great choice because you get the comfort of a GUI with the power of Unix. The main advantage of using Windows is familiarity and that you may already have it installed on your computer. (Note, I'd caution against using Windows 98 - a buggy C program often causes the whole system to crash.) Unix variants (e.g., arizona, OS X, and Linux) offer a more stable and powerful programming environment, but there is a relatively steep learning curve. If you're planning to be a CS major, now might be a good time to start learning about Unix - you will have to use it in subsequent coursework.

    My program doesn't work. I try to compile it and it just lists an 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 a moth might fly into the computer, and the code that you had labored over painstakenly for days would no longer work. Useless trivia: this was the $1 million question on the Who Wants to be a Millionaire gameshow.)

    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 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 where the computer did something different from what you intended. Sometimes, it is as simple as accidentally 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 preceptors, lab TAs, and classmates. Sophomores are also quite useful. We have all experienced the same frustration at some point in our programming careers and will be very sympathetic.

    However, before you seek advice, isolate your problem as best you can. Try to find a minimal piece of code that still exhibits the problem. Isolating the problem is an important skill, and it will benefit you in the long run. Once you have done this, bring this to your preceptor or lab TA for advice. When they determine what's wrong, ask them how they discovered it. Learn from your mistakes.

    I'm totally lost, and I don't even know how to begin coding. What should I do? Usually, the problem is more with the big picture of what needs to get done than with the actual programming. First, try to write down with pencil and paper a high-level flowchart of how your program will work. Try to fill in some of the details. After you have done this, consult with your preceptor for advice.

    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 files have really been submitted? You'll receive an email confirmation. If you don't receive one, your file hasn't been submitted.

    Do I need to submit all of my files at the same time? No, you can submit the files separately if you prefer.

    How can I resubmit a file? Just submit it again. It will overwrite the previous version, and leave all other submitted files intact.

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

    What are the basic skills needed to be a successful programmer? Steve Summit's list of basic programming skills includes: attention to detail, stupidity, good memory, and the ability to abstract on several levels.

    Working From the Arizona Lab

    When I login to a machine in the Arizona lab, I get the "black screen of death". If this is your first login on these machines, it's possible your configuration files are screwed up. If you know how to login to your account using ssh, then do this, and type the following command:

    Now try to log back in to an Arizona lab machine. If this doesn't work, consult a lab TA or go to CIT at 87 Prospect.

    What should I do if one of the Arizona lab machines is showing the "black screen of death"? Do not use that machine. Ask a lab TA to reboot it. Unlike your home PC's, you can do damage by turning on and off these machines without following the proper procedure.

    How do I print my C program to the printer in the Arizona lab? We recommend using the command "enscript126 hello.c" - it will pretty-print your program, two column per page. The command "lpr126 hello.c" will print your program without any special formatting.

    How can I remove my job from the print queue? Type the command "lpq126" - this lists all pending jobs on the Arizona lab printer. Locate the ID number of the job you wish to kill, and type "lprm126 id-number", where id-number is the ID number of your job.

    What shell should I use? The shell is the program that interprets your Unix commands. The shell tcsh has many nice features that will make using Unix easier. By default, OIT makes your shell csh, although their help desk recommends changing it to tcsh. We highly recommend changing your shell with the following command:

    phoenix.Princeton.EDU% chsh
    You will be instructed to enter your Unix password. Then it will prompt you to enter your new shell. Carefully type
    The chsh program on arizona is a bit flaky, so if it doesn't work, try again later. This will enable the following features:

  • The backspace key will work properly.

  • Use the up-arrow key to recall previous commands.

  • Use the Tab key to complete filenames. For example, instead of typing "gcc alongfilename.c", simply type "gcc126 alo<Tab>" and the shell will automatically complete the filename for you.

  • Working on the Arizona System Remotely

    Can I work on the arizona system from home? Yes, we recommend reading Notes on Working from Home first. The notes are written specifically for Princeton COS 126 students.

    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.)

    When I run emacs from a telnet session, it just hangs. This may happen if arizona thinks your terminal is capable of displaying X-windows. Try typing "emacs -nw hello.c" instead. If your terminal really is capable of displaying X-windows, use ssh instead of telnet.

    Are there other clusters capable of running X-Windows? According to CIT, the X-Windows emulator MI/X on their Windows machines. It is unsupported, but here are their directions. The public cluster in the E-Wing of the equad on the 4th floor does support X-Windows, but is not staffed with lab assistants.

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

    I've been writing my programs on a PC, but when I transfer them over to Unix, my file is littered with weird "^M" characters. Then I have to manually remove each of them in order to get the program to compile. Type "dos2unix < hellodos.c > hellounix.c".

    Under Linux, I compile my program, but when I type "a.out" I receive a message that it can't find the file. The current directory is not in your path. Try typing "./a.out" instead.

    When I open the SSH FTP client, why does the SSH telnet window open instead (or vice versa)? How do I fix that? This situation occurs because of a feature in the File menu of SSH. The File -> Save Settings option causes the current settings, in addition to the window positions, the quantity of windows, etc., to be saved. Thus, if you choose that option while an FTP client window is open, then the next time you open any variant of the SSH Secure Shell client, the FTP client window will open (and vice versa). In order to rectify the situation, open only the SSH telnet window and go to File -> Save Settings.

    When using SSH telnet, why won't my backspace work? In order to rectify this situation, go to Edit -> Settings.... In the Profile Settings -> Keyboard setting, click the Backspace sends Delete.

    Creating a Web Page

    How do I go about creating a web page? If you've followed the Hello World instructions for Arizona, you already have one! Your web address is
    where you replace username with your CIT login name. Otherwise, check CITs instructions on publishing Web pages at Princeton.

    I already have another web page which I'd prefer to use. How can I automatically redirect visitors of my Princeton home page to another site? Create a file named .htaccess with a line like the following

    Redirect /~wayne/
    and put it in your public_html directory. Change the permissions to world readable with the command
    chmod 644 .htaccess
    The above .htaccess file automatically redirects all traffic from to


    I need help with Unix. Where can I find some guidance? The optional course textbook Harley Hahn's Student Guide to UNIX is a good hardcopy reference. There are also many electronic references. Unixtools contains several Unix tutorials, some for beginners, and some for more advanced users. Also, check out the web site Unix Help for Users.

    My program goes into an infinite loop. How to I stop it? Don't worry. Every programmer writes code that does this from time to time. On Unix, type "Ctrl-c" to break out of the loop. Under no circumstances should you turn off a Sun machine. Seek assistance if you cannot stop the program on your own.

    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.

    What's EOF? How do I put it into my file? How do I enter it from the keyboard? EOF means end of file. It is automatically the last character of every file. To enter it from the keyboard, it is usually "<Return> Ctrl-d" by default.

    The Unix command "lpr hello.c" doesn't work. Instead it reports _default: unknown printer. There is no default printer setup. Please follow the Hello World on arizona instructions.

    I accidentally deleted my file hello.c. How can I recover it? There is no "Recycle Bin" in Unix. When you delete a file, it is gone. You can email restores@phoenix to have CIT restore your file from their tape backup. First, you might want to check that hello.c didn't end up in the wrong directory by accident. Second, you may have a file ~hello.c in your directory: this is a backup created by emacs. If it is sufficiently recent, type "mv ~hello.c hello.c" to rename.

    How can I print my code in two column format? Use our customized version of the program enscript. For example,

    enscript126 hello.c
    will print 2-columns per page, in landscape, with a header at the top of each page, but no cover page.

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

    How can I clear the Unix screen? Use the command "clear".

    Where can I find a tutorial or cheatsheet for emacs? Type Ctrl-h t in emacs to get an on-line tutorial. Here's an emacs cheatsheet

    I can't write any files. I get the error message write: Disc quota exceeded. You have used more disc space on arizona than CIT permits. Type

    quota -v yourusername
    to see how much space you've used, and how much you're allowed to use. CIT gives you woefully little. Delete unnecessary files, especially large PostScript files. To determine which files are consuming the most room, use the command
    du | sort -n
    to get a list of all directories, sorted in reverse order of how much space they consume. What does !! do? It is shorthand for re-running the previous Unix command. Also, the command "!gc" will re-run the most recent Unix command that starts with gc, perhaps gcc 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 gcc 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? If you ran the setup126 program in the Hello World assignment, you should already have the compilation features mentioned above. Also you will get auto-indenting of your C code. Finally, if you use xemacs it will add some nice coloration to your otherwise drab display.

    What is xemacs? It's an extended 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).

    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? To tell the gcc compiler to report more possible errors and warnings, compile with

    gcc -ansi -pedantic -W -Wall -O2 myprog.c
    or gcc126 for short.

    The GNU debugger gdb is useful for finding semantic errors. Not needed in COS 126, but useful for creating large pieces of code. Check out the following gdb tutorial. Here's a gdb cheat sheet.

    Sun Workshop (Forte) is a professional integrated development environment (IDE) that is already installed on the arizona system. You can access it via the "Workshop" button in xemacs or by typing the command "workshop". Here is a link to some documentation.

    How can I profile my code with gcc? Compile using the -pg option. When you run a.out, it creates a file named gmon.out that you can process using gprof.

    % gcc -pg hello.c
    % a.out
    % gprof

    Is there any automated way to "beautify" my C code with consistent indentation? Automatic indentation in emacs is described above. The Unix program cb will make your code consistent with the style found in Kernighan and Ritchie. A slightly more sophisticated version is called indent. Here's a sample style format:

     indent -st -di3 -i3 -nce -bad -bap -npsl < oldhello.c > newhello.c
    or indent126 for short. Use the command "man indent" to see what all the options are.

    Is there a spelling program for Unix? Type "ispell filename".

    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.


    Can I use Windows compilers other than lcc-win32? Sure, we recommend trying DJGPP. It's a port of the renowned gcc compiler to DOS. Some popular commercial compilers are Microsoft Visual Studio, Metrowerks Code Warrior, and Borland C++. Be absolutely sure that your programs are ANSI C compliant and do not use any operating system or compiler specific features.

    Is there any way to avoid typing the path c:\lcc\bin\ each time I run lcc126? Yes. It depends on which version of Windows you are using. Basically, you need to add C:\LCC\BIN to your path. You might need to reboot your machine before it starts working.

    Are DOS filenames case-insensitive? Yes, but be sure to submit your files with the required capatilization.

    How do I enter the EOF signal from DOS? EOF means end of file. On Windows / DOS machines, type Ctrl-z. On some DOS systems the first line of output sent to the screen after you enter EOF will be rendered invisible by DOS. This is not a problem with your code, but rather a problem with DOS. To help you debug your program, we recommend including an extra printf("\n"); statement before what you really want to print out. If anyone knows of a better fix, please let us know!

    How can I repeat a previous command from the DOS prompt without retyping it? You can recall the previous command with the up arrow key. On some Windows systems, you might have to add the line DOSKEY to your autoexec.bat file.

    My program produces more than 25 lines of output, and it just whizzes by the DOS command window when I run it. Help! One solution is the redirect the output of your program to another file. Then, you can read this file using any text editor. A simpler solution in Windows 2000/NT is to right click the title bar of the Command Prompt, then choose Properties -> Screen Buffer Size, and select a number larger than 25. Feel free to adjust the font or color while your at it. Unfortunately, this does not work in Windows 98.

    The lcc-win32 accepts variable declarations anywhere, but when I compile my program via the submission system, it rejects such declarations. The lcc-win32 system supports the ANSI C89 standard, but also includes a few (but not all) of the new C99 options. We will be using a C89 compliant compiler to grade your programs (since no C99 compliant compiler currently exists). So, do not use code like the following as it is not C89 compliant:

    for (int i = 0; i < 10; i++)
    Instead declare all local variables at the beginning of a block.

    How can I get the lcc editor to automatically load my C file when I double click it? Click once on a file with a .c extension. Then, hold down the Shift key and right-click on the file. Choose the Open With... option. Click on the Other button, and find the LCC executable file (wedit.exe) installed in the bin folder of the directory where LCC is located. For example, if you installed LCC in C:\lcc, then the command line is: C:\lcc\bin\wedit.exe. Click Open and make sure Always use this program to open this file is checked. Then click OK. You may wish to repeat this process for .h files.

    In the lcc editor, how can I tell what line number I am currently editing? Look in the lower right hand corner.

    When I jointly compile several files, does the order matter? Yes, in lcc the command "lcc e.c rat.c" produces an executable named e.exe, whereas "lcc rat.c e.c" produces an executable named rat.exe.

    The lcc compiler complains vociferously when I write a function named max()? The lcc compiler appears to reserve max() for its internal use. Try renaming your function to work around this compiler bug.

    Common C Programming Bugs

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

    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;

    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)

    Logical AND vs. bitwise AND. In C, "&&" means logical AND, e.g., "if (x >1 && x < 2)". In contrast, "&" means bitwise AND, e.g., if x is an integer, then "x & 15" is the rightmost 4 bits in the binary representation of x. Similarly, "||" means logical OR, and "|" means bitwise OR.

    Logical XOR and exponentiation. In C, "^" means bitwise XOR. Use the math library function pow() to do exponentiation.

    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.

    Extra ; or = after #define. The line "#define N 100;" will replace occurrences of N with "100;" instead of "100". The line "#define N = 100" will replace occurrences of N with " = 100" instead of "100".

    Chaining multiple < operators. The statement if (x < y < z) does not mean what it does in mathematics. Instead, you must break up the compound statement into two separate conditions joined by logical AND: if ((x < y) && (y < z)).

    Forgotten ; after struct definition. The following code will produce a core dump.

    struct Rational { int num; int den; }
    main(void) { }
    as the program will try to return a struct Rational from main() instead of an int.

    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 = 1; i <= N; i++) a[i] = 0;

    Characters vs. Integers. The declaration char c; provides storage for a character (typically an integer between 0 and 255 or between -128 and 127). Do not use for reading in input with while ((c = getchar()) != EOF) since EOF does not have the value of any character. EOF is always negative; on most systems it is -1. If you use char c you may never detect the end-of-file, or you may get a spurious end-of-file signal if EOF casts to the same value as an input character.

    Int vs. Float. The following code won't work.

    int a;
    scanf("%f", &a);
    The "%f" signifies float, but it is read into an integer variable.

    Float vs. Double. The following code won't work.

    double d;
    scanf("%f", &d);
    Use %lf with scanf() instead of %f for doubles. Annoyingly, you should still use %f with printf() for doubles.

    Pointers vs. Arrays. The following code won't work.

    char *p = "hello world!";
    p[0] = 'H';
    String literal are not (necessarily) modifiable. Instead, use
    char a[] = "hello world!";
    a[0] = 'H';

    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.

    Mismatch of format specifiers with printf(). The statement "printf("%f", 17);" will not work as expected, unless you replace 17 with 17.0. The variadic function printf() will try to print to the integer 17 as a real number. The arguments to printf() are not automatically cast to the type specified by the format string.

    C Programming

    Is there a general C programming FAQ? Yes, here's the C programming FAQ. It contains many more questions and answers than the ones presented here.

    Where can I find a good on-line introduction to C? Steve Summit maintains a very nice set of C programming notes. You will also find detailed and inciteful comments about the Kernighan and Ritchie text.

    Where can I find a good tutorial on C pointers? Some students have reported that Ted Jensen's tutorial is a godsend. Pointers are a more advanced C programming topic that aren't covered until the middle of the course, so if you don't know what a pointer is yet, don't worry until they're covered in lecture.

    What's the history of the C programming language? Here's Dennis Ritchie's article on the Development of the C Language.

    I already know C. How can I further develop my programming skills? COS 126 is designed to teach only introductory programming skills. You will learn "industrial strength" systems programming in COS 217, and more advanced data structures and algorithms in COS 226. The Valladolid Programming Contest Problem Set contains hundreds of problems of varying difficulty. You can submit your C programs for electronic judging. Two highly recommended books for motivated students are Programming Pearls by Jon Bentley and The C Programming FAQ by Steve Summit.

    I already know C++. Is C a subset of C++? Not quite.

    What's the difference between a local and global variable? Local variables are defined at the beginning of a function or block. They can only be used within that function or block. 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 (usually) 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.

    How do I properly use the strcmp() function? Carefully. First, note that it can return any integer, not just 1, 0, and -1. Many programmers find it counterintuitive that 0 corresponds to the strings being equal. Second, it is not guaranteed (or likely) to work if you pass it a NULL pointer.

    I get crazy results with the sqrt and other math functions. Be sure to #include <math.h> in your program. Also, make sure that other functions returning doubles are correctly defined. Depending on your setup, you may need to tell the compiler to use the math library, e.g., "gcc hello.c -lm".

    The math library function pow doesn't work with integers. Why not? All math library functions return type double. You will need to "cast" to get things to work.

    I get imprecise results when doing arithmetic with floats and doubles. For example, the statement printf("%f", 3.0 * 1.0 / 3.0); might print out 0.999999 instead of 1.000000. Floating point arithmetic is not done exactly. The computer stores the numbers in binary, so do not be surprised to see roundoff error. This can be especially troublesome when you are trying to compare a very tiny number with 0.0. You should write code that does not depend on such roundoff imprecision. It is possible to write an ADT to work with arbitrary precision; however, doing arbitrary precision arithmetic will be significantly slower than with the built-in float and double types.

    I get the following warning when I compile my program, even though I never use a variable of type double.

    hello.c:28: warning: passing arg 3 of 'f' as 'float' rather than 
    'double' due to prototype
    In C, float and char variables are treated as second-class citizens, and some compilers automatically convert them to type double and int when they are passed to a function. This creates an apparent mismatch with the function prototype. This warning is safe to ignore, but we recommend using types double and int instead, unless space it at a premium.

    Instead of printing out a number, the computer prints out NaN. What's going on? NaN stands for "not a number." It occurs when you apply an illegal operation (divide by 0) to a floating-point number.

    My program crashes before it ever executes the first statement in main. What's going on? You probably have an array that is too large. If you really need an array that large, either make it a global variable or allocate space for it with malloc.

    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 does i = 5; a[i] = i++; do? Undefined. Depending on your compiler, it might set a[5] = 5, or a[6] = 6. This statement is undefined, so the compiler can do anything at all, e.g., set a[5] to 17 or reformat your hard drive.

    What do "segmentation fault" and "bus error" mean? In general, your program tried to access memory that it shouldn't have. The cause is likely: uninitialized pointers, inadvertent use of null pointers, mismatched function arguments (especially scanf).

    Give me an example of 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!\n"); 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("%%");

    What should go in the .h header file? In general, the header file should contain macros, structure definitions, typedef declarations, global variable declarations, and external function declarations.

    I've heard from a serious C programmer to never use scanf(). What should I do? For COS 126, scanf() is perfectly fine. However, it is nearly impossible to do proper error checking and recovery with scanf(). A more refined method is to use fgets() with sscanf().

    I've heard from a serious C programmer to never use gets(). Yes, there is no way to use gets() safely. It is the most dangerous function in the C library, and its usage has been instrumental in spreading several computer viruses. Use fgets() instead.

    Are goto statements really that evil? After doing the TOY programming assignment, you will see that for and while loops are much better at controlling program flow than goto statements. Here's a reprint of Dijkstra's famous 1968 article Go To Statement Considered Harmful.

    How should I generate a random integer between 0 and N-1? Using rand() % N doesn't produce uniformly random integers between 0 and N-1, even if the rand() function produces uniformly random integers between 0 and RAND_MAX. (Consider what happens if RAND_MAX is not a multiple of N.) With many compilers, rand() % N is notoriously bad for other reasons. For simplicity, we ignore these issues in COS 126. If you're curious, some better alternatives include: rand() / (RAND_MAX / N + 1) or (int)((double)rand() / ((double)RAND_MAX + 1) * N). For an industrial strength random number generator, try the Mersenne Twister. Even this is insufficient for cryptography - you will need to use cryptographically strong random number generators.

    The random numbers I generate are the same each time I run my program. Yes - the random number generator uses a deterministic algorithm so the numbers aren't really random. You can achieve a useful effect by setting the seed value for the random number generator according to the system clock time. Include <time.h> and execute the following statement before calling rand():

    srand((unsigned int) time(NULL));

    Where can I find really bad C code? Check out the International Obfuscated C Code Contest for some really horrific examples. It takes quite a bit of C knowledge to write or decipher these nasty programs written by some of the world's best programmers.

    Is there a program that will convert my C code to html? Check out Code2html.

    Can I use // style comments in COS 126? Yes. Although comments beginning with // are not technically legal in the current C standard, they will be incorporated into the next C standard. So, feel free to use them.

    I've heard about a new version of C called C99 or C9X. What is this all about? It's the latest ANSI/ISO standard that specifies exactly what the C language is. There aren't yet any C99 compliant compilers, but here's a list of changes between the two versions if you're interested. Features include: Boolean types, variable-length arrays, and declarations in the middle of a block.


    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 >".

    Are there any good references for PostScript? Yes, check out A First Guide to PostScript. The PostScript Language Reference Manual provides more complete documentation. It is available online, and is on reserve at the Engineering Library.

    How do I view and print a PostScript file? To print a PostScript file named, use the Unix command "lpr". 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" will "compile" the program and set up an X-window for you to view it. You can't do this over a telnet session.

    How do I view and print a PostScript file on a PC or Mac? You can download AFPL Ghostscript and the PostScript viewer GSview via the COS 126 software 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 couples of lines are used to pass information to the program or printer that processes the raw PostScript.

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

  • %!PS-Adobe-3.0 EPSF-3.0 All of your PostScript programs will begin with this line. Since % is a special symbol with printf, use printf("%%") to print a % sign.
  • %%BoundingBox: 0 0 512 512 This specifies the region in which you are permitted to draw. Going outside the 512 x 512 box may result in serious penalties. Since % is a special symbol with printf, use printf("%%%%") to print %%.
  • 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 subpath.
  • 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. The following PostScript fragment builds a path in the shape of a triangle.
    256 0 moveto 512 512 lineto 0 512 lineto closepath
  • stroke draws a line (of some thickness) around the current path. Note that stroke destroys the current path, so to start drawing a new path after stroke you need to use a command like moveto to establish a new current path. The following PostScript fragment draws a triangle.
    256 0 moveto 512 512 lineto 0 512 lineto closepath stroke
  • fill paints the entire region enclosed by the current path (using the current color). Like stroke, fill eats up the current path. The following PostScript fragment draws a filled diamond.
    256   0 moveto
    512 256 lineto
    256 512 lineto
      0 256 lineto
    256   0 lineto fill
  • showpage ejects page from printer.
  • x y w h rectstroke draw a rectangle of width w, height h, and lower left endpoint (x,y).
  • x y w h rectfill draw a solid rectangle of width w, height h, and lower left endpoint (x,y).
  • 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 (0 = black, 1 = 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.
  • 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.
  • d rotate changes the orientation of the turtle d degrees counterclockwise. Warning: whatever drawing commands (including moveto) are now with respect to the new orientation. The following PostScript fragment draws a pentagon.
    128 128 moveto
    256 0 rlineto 72 rotate
    256 0 rlineto 72 rotate
    256 0 rlineto 72 rotate
    256 0 rlineto 72 rotate
    256 0 rlineto 72 rotate
    The last "72 rotate" does not affect the drawing of the pentagon, but it ensures that the turtle orientation after drawing the pentagon is identical to when it started (a net change of 360 degrees).
  • a b scale scales (multiplies) all x-coordinates by a, and all y-coordinates by b. It's OK to have a or b negative.
  • 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. The following PostScript fragment draws a disc of radius 100, centered at (256, 256).
    256 256 100 0 360 arc fill
  • N { . . . } repeat repeats the statements delimited by the braces N times
  • /anyname { . . . } defines anyname as a synonym for the statements delimited within the braces. The following defines a function pt so that x y r pt will subsequently draw a solid circle (in the current color) centered at (x,y) of radius r.
    /pt { 0 360 arc fill } def
  • What is the unit of measure for the PostScript coordinate system? By default, one unit is 1/72 of an inch. On an 8.5 x 11 page, the lower left corner is (0,0) and the upper right is (612,792).

    What are the standard colors in rgb format? Red, green, and blue, are (1,0,0), (0,1,0), and (0,0,1), respectively. Black is (0,0,0), white is (1,1,1). Cyan, magenta, and yellow are (0,1,1), (1,0,1), and (1,1,0), respectively. Here's a color palette in PostScript.

    How do I draw a single path that has several colors? You can't. Each path in PostScript must be drawn the same color. So you need to break up your path into pieces, and color each one individually. This can be done by individual moveto and lineto commands. If you are using relative coordinates (e.g., with rlineto) then you may not know (or want to compute) where to move to to begin the next path. In this case, use the command currentpoint to push the current point onto the stack and use it to start the next path. The following draws an equilateral triangle in red, green, and blue.

    0 440 moveto
    1 0 0 setrgbcolor 512 0 rlineto currentpoint stroke moveto -120 rotate
    0 1 0 setrgbcolor 512 0 rlineto currentpoint stroke moveto -120 rotate 
    0 0 1 setrgbcolor 512 0 rlineto stroke


    Can you recommend a good introductory book on Java? Check out
    Sun's online Java Tutorial. Peter van der Linden's Just Java 2 (ISBN 0-13-010534-1) is a wonderful introduction for Java for students who know a little C. Another recommended online book is Thinking in Java by Bruce Eckel. Do not buy anything written by Cary Jardin no matter how cheap it is, although we encourage you to read through some of the reviews of his writing talents.

    Where can I learn more about Java? Go to or 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 documentation for all Java 1.2 classes and for Java 1.3 classes.

    Where can I download a free Java compiler for Windows? Go to The latest version is (at least) 1.3. A full installation requires about 65MB. You also might consider downloading a JAVA IDE (editor + debugger) such as JBuilder or Forte.

    Where can I find other Java compilers? Here's a long list of java compiler and virtual machines .

    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 any text editor.

    Is there a Java FAQ? It's available at Also you can check out the Java glossary.

    Some of the applets from the Sun Java Tutorial don't work on my browser. Yes, Sun assumes that you have a browser that directly supports Java 1.2, which is rare. Assuming you have a recent version of Java installed, you can type "appletviewer http://www.blah.blah.html" and it should run.

    The class Vector doesn't work in my browser. Java changed some of the methods in class Vector between 1.1 and 1.2. Your browser probably only supports the 1.1 methods.

    Where can I find toolbar button graphics. Sun suggests using the following Java look and feel buttons.

    My gif or jpg image doesn't display. Be sure that the image is in the appropriate directory. Java may not warn if it cannot find the file - it may just display nothing. If you are working in an applet, the getImage() cannot occur in the init() method. If your images are large, you may need to use the class MediaTracker so that the images are downloaded before you attempt to display them.

    How can I run my Java 1.2 or 1.3 applet from my browser. You need to download the Java plug-in and you also need to modify the html code so that it tells your browser to use the plug-in. See this html file for an example.

    Where can I find some really great Java demos? Check out 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.

    I can't get appletviewer to work on arizona. What's wrong? First, make sure that you have compiled with the command javac 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 It's about 10MB.

    How come my Java program doesn't work under Netscape or IE? Older versions of Netscape and IE 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.7 instead of netscape.

    When I update my java file, it does not get updated in my web browser, even after hitting the Reload button. Why not? First, you must javac your program again. Then, in Netscape use Shift-Reload; in Internet Explorer, use Ctrl-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). You can also print a one line message to the applet status window using the applet's showStatus() method.

    If I run appletviewer, the output of System.out.println goes to a Unix window. Where does it go in Netscape? In Internet Explorer? In Netscape 4.7 use the menu option "Communicator-Tools-Java console". In IE 5.0, use the menu option "View-Java Console". You may have to check the "Tools-Internet Options-Advanced-Microsoft VM-Java console enabled" option first.

    How do I create an array in Java? You can't do "int a[256];" as in C. Instead, use "int a[] = new int[256];". The keyword "new" is needed to allocated memory for the new object.

    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 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 class. 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

    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, the start and update methods are overridden.

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

    What is a "deprecated method"? It is a method supported in the current version of Java, but may not be supported in future versions. You should try to avoid using these obsolete methods. Java changes so quickly that sometimes it is hard to keep up!

    How can I read in an integer/double from the keyboard? It's not so easy to do on your own. The easiest way is to download the class EasyIn from


    Where can I find a humorous account of the history of operating systems. Here's In the Beginning was the Command Line by Neal Stephenson.

    Where can I learn more about floating point precision? Here's What every computer scientist should know about floating-point arithmetic by David Goldberg. It's quite detailed and it's only meant as a reference if you're quite interested in the subject.

    Where can I find a sample Turing machine simulator? Here's a TM that tests if one number divides another.

    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. Here's information on Enigma and the Turing Bombe.

    Where can I find Turing's original paper on the Turing test? Here is his 1950 paper Computing Machinery and Intelligence.

    Where can I learn more about the history of computing? Visit the Virtual Museum of Computing.

    Where can I find a formal statement of the P versus NP problem? Here is a link to Stephen Cook's description of the problem via the Clay Mathematics Institute. You can also claim a $1 million prize from this Web site if you solve the problem!

    Where can I learn more about the algorithms and data structures? There are many Web sources including this online course. See also COS 226.

    Where can I learn about Fibonacci numbers in the arts and sciences? Visit Fibonacci Numbers and The Golden Section in Art, Architecture and Music .

    Where can I learn about quantum computing? Visit the Centre for Quantum Computation.

    How about some gratuitous cs quotes? I'm glad you asked. Here is a collection of cs related .

    Copyright © 2000 Kevin Wayne