University of Delaware

CISC105 - General Computer Science

C Programming

Lab #2

  1. Goals

    This lab is an exercise to familiarize you with the following:

    • The pico text editor.
    • Coding, compiling and executing a C program using the C compiler cc.
    • Creating a script file which records your computer session for grading.
    • UNIX commands dealing with files and directories.
    • Interactive input and output with C and UNIX.

  2. Reference Materials

    • "Introduction to Unix" , University of Delaware, Sections 2.1-2.7, Chapters 3 and 4.
    • "Introduction to Pine: A Menu-driven Electronic Mail Program", University of Delaware.

  3. Step 1: Creating and Editing a File on UNIX

    Information is stored in the computer in files. You can think of a computer file as a manila file folder, which contains information such as a computer program, a letter, data for a computer program, a term paper, a resume, or any kind of information that can be stored as a sequence of visible characters such as a-z, A-Z, 0-9, and punctuation and symbols. An editor is a program that helps you create and store a text file in a computer and then to later modify it. Computers usually have several editors and you must learn one of them. One of the easiest to learn at the University of Delaware is pico. One of the most powerful (and complex!) is vi. Both are part of the standard UNIX operating system which controls the operation of each of the composers. You are free to use any editor. However, pico is strongly recommended for those not already familiar with an existing editor. Only pico is discussed here.

    To start executing the pico editor, type pico lab2.c at the command prompt. The first part of the command you typed, pico, tells UNIX that you want to execute the program named pico. The second part of the command, lab2.c, tells pico that you want to edit (create or modify) the file named lab2.c. The final .c in the file name is called the filename extension. It helps identify the file as a C source code file. Since there is no existing file in your current directory named lab2.c, pico will create a new file with that name in your current directory and save everything that you type in that file.

    Now that you are in pico, type the following C program exactly as shown with one exception: modify the comment at the beginning to reflect your name, class and section, and today’s date.

    /* 
    	Programmer:
    	Course:
    	Section:
    	File name:
    	Date:
    */
                          
    main ( )
    {
     printf ("Programming is fun.\n");
    }
    
    You can move around in pico by using the arrow keys. You can access any of the menu items by pressing the control key (which is what the ^ symbol stands for) and the letter at the same time. For example, to get to the help screen, press the control key and G simultaneously. If you make an error in typing the program text, use the help screen or your UNIX handbook to determine how to go back and fix your mistakes. Once you have typed in the C program (paying close attention to punctuation), you must save the file. This means that a copy of the file is written to a hard disk attached to the computer. The saved file is given a name so that you can retrieve it any time later. Save the file by pressing ^O (control-O, the write out option of the menu). Hold down the control key and press the O key simultaneously. Pico will give you a prompt such as:
    	File name to write:  lab2.c
    
    Hit RETURN. By doing so, you tell pico that you want lab2.c as the name of the saved file. Exit pico by pressing ^X (described as control-X). You can verify that your file has been saved by typing ls at the command prompt. The command ls lists all files in your current working directory. The next time you type pico lab2.c, you will be editing the most recent copy that you saved.

  4. Step 2: Compiling a C Program

    You have just finished creating a computer file that contains a real live C program. Before you can see if your C program works by executing it, your C program must be translated into a format that the computer can understand directly. We call the computer understandable file an executable file. This translation process is known as compiling and is performed by another program called a C compiler. There are several C compilers available. The one we use is the Sun 3.0 C compiler. Type the command cc lab2.c to invoke (execute) this compiler.

    If you made any mistakes typing in the given program, the compiler will now give you error messages. Use pico to go back and edit your program. The error messages will not mean much at this point since you do not know the C language. Do your best. Go to the indicated line in error and look at the lines before and after this line, as well as this line, for something that is typed wrong. An error message may say the error is in line 20, but the real error may have been omitting a ; in line 19. This process is called debugging.

    After you have corrected some errors, go back and recompile the program by exiting pico and typing cc lab2.c again at the UNIX prompt. Continue this cycle until compilation results in no error messages. When compilation completes with no error messages, type ls to list the names of the files in your directory. The list should include both lab2.c and a.out. The a.out file is the executable file created by the C compiler.

  5. Step 3: Executing a C Program

    Once there are no compilation errors, it is time to execute your program. Compilation identified syntax errors such as spelling mistakes and missing punctuation. Execution requires valid semantics. If you try to divide by zero (which is not allowed), you will not get a compilation error message. Instead you will get an execution error message. Even worse, if you type a + when you want the computer to do subtraction, you will get NO error message; just the wrong results.

    To execute your compiled program, enter the command a.out at the prompt. The file a.out is the default file name the compiler gives to the executable version of your program. You cannot look at the insides of the file a.out. Executables are not visible. Hopefully you will see a valid execution of the Programming is fun program. That is, you should see the words "Programming is fun" displayed on your screen just after you typed a.out. If not, then continuing debugging.

  6. Step 4: Scripting your session for grading

    UNIX provides a way for you to "capture" the information that appears on your terminal screen and to save it in a file. In particular, by typing script file.scr, the computer will save whatever is typed or displayed on the screen into the file called file.scr until you type exit. After typing exit, no more information from the screen is saved in the file. This capability allows you to show others what you actually did while you were working on the computer, without them having to look over your shoulder. In particular, it allows us to see what you actually did and grade you for your work. The process is two steps: (1) create a script file that contains what has been displayed on the screen; (2) print out the script file and hand it in for grading. For this lab you should do the following:

    % script lab2.scr
    % cat lab2.c
    % rm a.out
    % cc lab2.c
    % a.out
    % exit
    
    The first line results in the following actions:

    1. UNIX creates a file named lab2.scr. WARNING! If lab2.scr already exists, UNIX ERASES IT. BE CAREFUL! The filename that you use should NOT end in .c. If you type script lab2.c, you will ERASE whatever was in the file lab2.c, which was your C program!
    2. In addition to showing you the info on the screen, UNIX saves everything that appears on the screen in the file lab2.scr.
    3. UNIX watches your input, looking for you to type exit after the prompt. When you do so, UNIX stops storing information in lab2.scr. DO NOT FORGET TO TYPE exit; otherwise your script file will be lost.

    The second line will display the contents of file lab2.c to the screen. This will also get saved in the script file because you are still in script mode. The third line removes any a.out file you may have in your directory before compiling and creating a new one. The fourth line compiles your program, the fifth line executes it and displays any output to the screen, and the sixth line exits the script mode. At this point, you can view your script file by typing more lab2.scr. If the whole file is not displayed, hit RETURN or ENTER to see the remainder of the script file.

    IMPORTANT WARNING! You are NEVER permitted to edit a script file in any way before submitting it for grading; not even to spell your name correctly. Editing a script file and then submitting it for grading is considered academic dishonesty.

  7. Step 5: Printing out your work

    After exiting script mode, you can then print a copy of your script file using the command qpr. To print your script file to the Willard Hall laser printer, type the following command:

    qpr -q whlps lab2.scr

    To print your file in other buildings, you would substitute the name of the printer in that building (usually written somewhere on the printer itself) for “whlps” in the above command. For example, to print to the printer in 115 Pearson Hall use the following command:

    qpr -q nrkps lab2.scr

    You can tell if your output is waiting to be printed or has finished printing at the Willard Hall printer by entering the following command soon after executing the qpr command above:

    qstat -q whlps

    Go ahead and print out your lab2.scr file.

  8. Step 6: Organizing Files into Directories

    The operating system that coordinates all of the activities and files of the strauss computer is called UNIX. It is a popular operating system used on many different computer systems. The UNIX operating system organizes all of the files of all of the users of the computer system using directories. Each user of the computer has a home directory which is where you start each time you login. Type ls to see all of the files that you currently have stored in your home directory. All of the directories of files on strauss are organized in the form of a tree. See page 54 of the Introduction to UNIX booklet from the University of Delaware for a picture of this tree file structure. Here are some of the most useful commands for moving around and manipulating files in directories:

    cat filename		- display the contents of the file called filename on the screen.
    cd			- change (or move) back to your directory from wherever you are
                              currently located.
    cd ..			- change (or move) back up one directory level in the tree.
    cd directoryname        - change (or move) to the directory called directoryname.
    cp filename newfilename	- copy the file called filename to a new file called newfilename,
                              keeping a replica in the file filename; wipes out the old contents
                              of newfilename.
    ls directoryname        - display the filenames of all files stored in the directory called
                              directoryname.
    mkdir directoryname	- creates a new directory called directoryname, which is located
                              in the current directory.
    more filename		- display the contents of the file called filename on the screen,
                              pausing when the screen is full, waiting for the user to hit RETURN
                              or ENTER to continue displaying.
    mv filename newfilename	- move the file called filename to a new file called newfilename;
                              wipes out the old contents of newfilename and deletes the file
                              called filename. 
    pwd			- displays the complete name of your current directory; includes the
                              whole path name, that is, every directory on the path starting at
                              the root directory of the UNIX system down the tree branches to your
                              current directory.
    rm filename		- remove (delete) the file called filename from the computer system.
    rmdir directoryname	- remove an entire directory called directoryname from the computer
                              system; the directory must contain no files (be empty) for this
                              command to actually do any deletion of the directory.
    

    For this lab, perform the following steps to practice manipulating files and directories:

    1. Type script lab2unix.scr to begin recording your actions in the file called lab2unix.scr for grading.
    2. Using the appropriate command from above, be sure that you are currently in your home directory by first changing to your home directory and then displaying the name of the current working directory. Then, also display the names of the files in your home directory.
    3. Using the appropriate command from above, create a new directory in your home directory called lab2.
    4. Using the appropriate command from above, move all the files that you used for Lab#2 to the new directory, leaving no copies of them in your home directory. This should include the lab2.c and lab2.scr files.
    5. List the current filenames in your home directory to see whether these files are now gone from this directory.
    6. Change to the new directory called lab2 and display the names of the files located there now. From this directory, display the contents of the file lab2.c just to convince yourself that the file is really there and not empty.
    7. Now, copy the lab2.scr file to your home directory, leaving a copy of the file in the current lab2 directory also. This can be done while you are in the lab2 directory by typing cp lab2.scr ../lab2.scr. Be sure to type two dots before the slash. This command places a duplicate copy of the file lab2.scr which exists in the current directory (i.e. the lab2 directory) into the directory that is one level above the current directory in the tree hierarchy. List the files in the lab2 directory to insure that the file still exists there. Change back to your home directory and list the files there to see if the lab2.scr file also exists there now.
    8. Type exit to exit the script mode and print out your script file to hand in for grading.

  9. Step 7: Interactive Input / Output in a C Program

    In C, the printf statement causes the contents of the printf string argument to be displayed or output to the screen for the user to view. The scanf statement causes the C program to pause execution at that point in the program, and wait for the user to enter some input. When the user hits the RETURN or ENTER key, execution continues and the program uses the input from the user in a way depending on the contents of the scanf statement. For this lab, perform the following to learn about interactive input/output in C:

    1. Type in the following program:
      /*
      	Programmer:
      	Course:
      	Section:
      	File name:
      	Date:
      */
      main ( )
      {
       /* Declare variables */
       int value1, value2;
       int sum;
      
       /* Assign values and compute the result */
       printf ("Please enter the first integer:  ");
       scanf ("%d", &value1);
       printf ("Please enter the second integer:  ");
       scanf ("%d", &value2);
       sum = value1 + value2;
      
       /* Display the results
       printf ("The sum of %d and %d is %d\n", value1, value2, sum);
      */
      }
      
    2. Examine the program and make sure that you understand what it is doing. Compile the program. Execute the program. Surprise!
    3. Modify the program so that the total is displayed on the screen when you execute it, recompile the program, and execute it again. You should get output that resembles the following:
      		The sum of value1 and value2 is sum
      
    4. Add statements to the program so that the output looks like :
      		integer1 is ##
      		integer2 is ##
      		the sum is ##
      
    5. To demonstrate that you have mastered interactive input/output, enter script mode and cat your final version of the program created in step one above, compile it, and execute it three times with the values: 50 and 75, then 30 and 90, and finally 133 and 266. Exit the script mode, print out your script file, and include it in what you hand in for grading.

  10. What to hand in:

    1. Script file from compile and execute C program section (Sections 4 & 5).
    2. Script file from file and directory manipulation section (Section 8).
    3. Script file from interactive input/output section (Section 9).