CS16, Fall 2009

lab01: ("lab one")
Turning one C program into another


Goals for this lab

By the time you have completed this lab, you should be able to:

More specifically, we'll show:

You'll also get more practice with the things you learned in lab00:

Step by Step Instructions

 

Step 0: If you haven't complete lab00, do so now.

We will not accept your lab01 submission until lab00 is complete. So please go finish lab00 if you haven't submitted it yet via the turnin program.

Also, you'll need some of the skills from lab00 in order to complete this lab, including how to log in to CSIL, create a new directory, and use the turnin command.

Step 1: Log on to CSIL and bring up a terminal window.

As a reminder, that's the Application Menu, then System Tools, then Terminal Window.

Here's what it should look like (click on a thumbnail to bring up a bigger image)

Selecting the menu option Result
Applications, Internet, System Tools Terminal Window

In future weeks, we'll assume you know how to pull up a terminal window, and we won't walk you through those details.

Step 2: Create a ~/cs16/lab01 directory

Last week, we created your ~/cs16 directory, and the ~/cs16/lab00 directory.

This week, we'll create the ~/cs16/lab01 directory.

You can do this with the following unix command:

mkdir ~/cs16/lab01

Then you can use a cd command to go directly into that directory:

cd ~/cs16/lab01

You can then use the pwd command to make sure that you are in the proper spot. The result should look like this (except in place of /cs/faculty/pconrad, you'll see your own home directory listed, e.g. /cs/student/jsmith, or /cs/guest/kchen).

-bash-3.2$ mkdir ~/cs16/lab01
-bash-3.2$ cd ~/cs16/lab01
-bash-3.2$ pwd
/cs/faculty/pconrad/cs16/lab01
-bash-3.2$

In future weeks, we may simply say something like "create a ~/cs16/lab02 directory and make it your current directory", without spelling out the unix commands to do this. You can always refer back to previous labs if you forget the details, but eventually you'll want to memorize some of the most useful commands such as mkdir, cd, pwd and ls.

Step 3: Copying the program you worked on in lab00

During lab00, you copied a file into your directory ~/cs16/lab00 called firstCProgram.c

This week, we are going to copy that program into your ~/cs16/lab01 directory.

Here's a unix command that will do that:

cp ~/cs16/lab00/firstCProgram.c ~/cs16/lab01

This command says to copy the file firstCProgram.c from where it lives, in ~/cs16/lab00 into ~/cs16/lab01. After executing this command, if you are in ~/cs16/lab01 (which you can verify with the pwd command, as shown below, the ls command should show you that you have a copy of the file ~/cs16/lab00/firstCProgram.c in your account:

-bash-3.2$ cp ~/cs16/lab00/firstCProgram.c ~/cs16/lab01
-bash-3.2$ pwd
/cs/faculty/pconrad/cs16/lab01
-bash-3.2$ ls
firstCProgram.c
-bash-3.2$

Next, we are going to copy this file to another file called secondCProgram.c like this:

cp firstCProgram.c secondCProgram.c

We'll then run the ls command to see that it worked:

-bash-3.2$ cp firstCProgram.c secondCProgram.c
-bash-3.2$ ls
firstCProgram.c secondCProgram.c
-bash-3.2$

Now we are ready to start editing secondCProgram.c to make it different from firstCProgram.c

Step 4: Bring up secondCProgram.c in an editor (e.g. emacs)

By now, in lecture you should have seen a demonstration of a text editor that is available on CSIL called emacs.

You'll use that program now to make changes to the file secondCProgram.c

To bring up emacs to make changes to secondCProgram.c, type:

emacs secondCProgram.c

This may bring up a new window where you can edit this program.

Do I have to use emacs?

If there is another program that you prefer, e.g. vim, that is already available on CSIL, and you already know how to use it (or are willing to take responsibility for learning how) that's fine. So, no, you don't have to use emacs, specifically. However you will need to learn some editor that works on CSIL. Working only on your own PC or Mac at home will not be sufficient.

I'll also add that knowing how to use either vi/vim or emacs is really a kind of "basic skill" that every software developer should have in his/her toolkit. So if you don't already know one of those editors, now is as good a time as any to start learning one of them.

Assuming you are using emacs, for the time being...

Here are a few emacs commands that may be helpful to know.

Remember that:

C-x is called "control-X" and means "hold down the control or Ctrl key while typing the letter x"
C-x 1 means "type control-X, then type the number 1".
C-x C-c means "type control-X then type control-C".

Keystroke Command
C-x 1 If there are multiple windows, get rid of the other ones.
I only want the one the cursor is in right now.
Arrow Keys Used to move around
Delete/Backspace Deletes the previous character
C-d Deletes the character immediately under the cursor
C-x C-w Save As
C-x C-s Save
C-x C-c Exit emacs (it will ask if you want to save)
C-g Cancel current command ("get me out of trouble")
C-k Kill (delete) the current line

Here's a link to a PDF File with lots more emacs commands—it is suitable for printing on a single sheet of paper (front and back) and having handy while you work in Emacs.

Once you've brought up the file in some editor, be it emacs or something else, we are ready to start making changes. Continue with the next step.

Step 5: Making changes to secondCProgram.c—and learning about C

So, now that we have secondCProgram.c loaded up in emacs (or an alternative), here are the changes we want to make.

As we make these changes, we'll review some basics of C programming, including

We are assuming that none of those ideas is new to you—only the way of expressing them in C is new to you.

If that's not the case, then you are probably in the wrong class—and there may still be time to switch to CS8, so let your instructor know if that's the case!

Step 5a: Changing the comment at the top of the file

At the top of the file, you'll see a comment like this one:

// firstCProgram.c convert Fahrenheit to Celsius
// P. Conrad for CS16, Fall 2009, UCSB CS Dept., 09/25/2009

Change this comment so that instead, the first line reads:

// secondCProgram.c convert Celsius to Fahrenheit

In general, we always want the first line of our file to have the filename, and a brief description of the program. As you can now see, we are going to modify the first C program we encountered, changing it from a program that converts Fahrenheit to Celsius, into one that does the reverse.

Now change the second line from:

// P. Conrad for CS16, Fall 2009, UCSB CS Dept., 09/25/2009

to something like this (but insert your name where it says Your Name Here, and insert the correct date for the day you are working on the lab.)

// Your Name Here, for CS16 lab01, 10/02/2009

Generally speaking, we want the second line of a program file to have the name of the programmer, and the date the file was created.

Step 5b: Changing the function definition

We'll skip on past this line, which as you probably know by now, tells C that we are going to be using "standard input output functions" such as printf and scanf in our program—we won't be changing this line. In fact, you'll see this line in most of the files that we work on in this course (though not necessarily all).

#include <stdio.h>

Instead, lets turn our attention to the function definition for the fToC() function, which consists of these four lines:

double fToC(double fTemp) // ftemp is temperature in Fahrenheit
{
   return (fTemp - 32.0)*(5.0/9.0); // return Celsius temperature
}

Your job is to do the following five things with this function definition:

  1. Change the name of the function—instead of fToC, we will call our function cToF. Generally speaking, we start function names and variables with lowercase letters in C—this isn't required by the language, but it is a convention that is very often followed.
  2. Change the name of the formal parameter fTemp—call it cTemp instead. For our new cToF function, we are not going to be passing in a fTemp, but rather a cTemp.
  3. Change the comment on the first line of the function definition (it starts with // and continues to the end of the line). Change it to one that describes what cTemp stands for (a temperature in Celsius).
  4. Inside the braces { } we have the "body" of the function. This body consists of only one line: a line that returns a value. After the word return we have an expression that returns the Celsius temperature, by doing a calculation based on the value of fTemp.

    Your job is to replace the expression after the word return with one that will calculate a fahrenheit temperature by doing a calculation based on the value of cTemp.

    The following web page has both formulas, but beware: you may have to adapt them to C: http://www.usatoday.com/weather/wtempcf.htm

    Keep in mind, especially, the rules about order of operations, and how the division operator works on integers.
  5. Change the comment that says "return Celsius temperature" to something more appropriate given the other changes you've made.

Step 5c: Changing the main program

Next we have the main program. Here are the changes you'll need to make here:

  1. There is a comment immediately before the main that will need to change.
  2. The comment immediately inside the main is fine, as is the declaration of the variables fTemp and cTemp, and the declaration of the variable again (and the associated comment.) Look over all this and understand how it works.

    Then notice the while loop. The while loop will always be executed at least once, because the first time we evaluate the condition while (again), the variable again has the value 1, which is C is treated as "true". So we enter the while loop, and the first thing that happens is we have a prompt (a printf statements) that asks the user to enter a fahrenheit temperature. As you probably realize by now, you will need to change this prompt to one that asks the user to enter a Fahrenheit temperature.
  3. The next line looks like this:

    scanf("%lf",&fTemp); // reads a double into "fTemp"

    That line is a little complex, and we'll explore the details in lecture—but for now, all you need to know is that it reads a value from what the user types in, and places it into the variable fTemp.

    Instead, we want to read a value in to the variable cTemp. Carefully replace the variable name fTemp with cTemp in both the scanf function call, and the comment that follows it, being careful to leave all the other punctuation intact. We'll eventually be able to understand all the details of the %lf, the & symbol, and so forth.


  4. The next line is an assignment statement where the left hand side is the variable cTemp, and the right hand side is a function call to the fToC function, where we pass in the value of fTemp that was read from the user.

    Instead, replace this with an assignment statement with fTemp on the left hand side, and a function call to cToF on the right hand side, where we pass in the value of cTemp that was read from the user.

  5. Next, we find a line of code with a comment above it, "provide output to user".This is an example of how we can use printf sort of like a "form letter" or a "mail merge". Look at the places in the string shown below where we see %lf
    "%lf degrees F is %lf degrees C"
    These are the places the the values of fTemp and cTemp will appear, in that order. If we want to reverse this, with a format string like the following:

    "%lf degrees C is %lf degrees F"

    then we will need to reverse the order in which fTemp and cTemp appear in the printf statement. So, go ahead and make those changes.

  6. Look over the rest of the program. I think you'll see that no further changes are needed! Try to understand how it works though. There is a printf that prompts the user to enter either a 1 or a 0, and the value typed in is placed into the variable "again". This controls whether the while loop goes around for another conversion, or whether the program ends with the Goodbye message.

Ok, if you've made all those changes, you are ready to save the file and try running the program.

To save, in emacs you can use C-x C-c (control-X, control-C), and then answer the question "Save file ~/cs16/lab01/secondCProgram.c?" with the letter y (for yes). Then proceed to step 6.

Step 6: Running the file

Assuming you successfully completed Steps 1-5, and are now in the ~/cs16/lab01 directory and it contains the file secondCProgram.c, we are just about ready to try to run the program.

An initial check

But, before you do, type the pwd and ls commands (print working directory, and list files). The result should look like this—except you'll see your home directory listed instead of /cs/faculty/pconrad.

-bash-3.2$ pwd
/cs/faculty/pconrad/cs16/lab01
-bash-3.2$ ls
firstCProgram.c secondCProgram.c secondCProgram.c~
-bash-3.2$

One of the things you may notice (if you are using emacs) is the secondCProgram.c~ file—this is an emacs backup file, which saves an "older" version of your program, in case you decide you don't like your most recent changes, and want to go back a version. It is also handy in case you accidentally delete the main file.

For now, we can ignore this secondCProgram.c~ file.

The possibility of syntax errors...

One thing that will be different this week is that instead of trying to run a program that you copied directly from my account (which presumably is error free), since you made some changes, there is the possibility of typos introducing syntax errors in the program.

Since CS16 is not your first encounter with programming, we assume this is also not your first encounter with syntax errors! So if you type the next few commands and get error messages:

Instead, take a deep breath, and then actually read the message that comes up. It will often give a line number, and some hint as to what might be wrong.

Then, look at your program, around that line, and also immediately before that line. Often, if the error is reported on, say, line 15, it is because of a missing semicolon, on line 13 or 14, for example.

If you've really looked, and are still stumped after two or three tries, then you might ask the TA for help. But try to fix it on your own first.

Ok, with that said, here's what to do:

To prepare your program to be run, we do this step:

make secondCProgram

Try typing that now. It should look like this:

-bash-3.2$ make secondCProgram
cc     secondCProgram.c   -o secondCProgram
-bash-3.2$

If it worked, then try typing the ls command to list your files. You should see that you now have another file in your account, called secondCProgram. This is the machine language version of your program. To run it, you type the following at the Unix prompt:

./secondCProgram

Try running your program on a few sample values. It should work just like the firstCProgram from last week, except this time, the conversion goes in the opposite direction.

If it worked, lucky you—you can skip directly to step 8!

But if it didn't work.... continue with step 7:

Step 7. edit, compile, edit compile, edit compile run, until done...

If you program didn't compile, then as mentioned before, really look carefully at the error message that was printed. Here are some problems you may have, and samples of the resulting error messages you may get:

  1. Function call doesn't match function definition—if you have a function call to fToC, but you don't have a function definition for fToC—say, because you changed it to cToF, but didn't make the change in both places, you'll get an error like this. It's kind of ugly, but the truth is buried in there somewhere:
    -bash-3.2$ make secondCProgram
    cc secondCProgram.c -o secondCProgram
    /tmp/ccmCwEH1.o: In function `main':
    secondCProgram.c:(.text+0x67): undefined reference to `fToC'
    collect2: ld returned 1 exit status
    make: *** [secondCProgram] Error 1
    -bash-3.2$

    The most useful part of this error message is the part that says "In function `main' ... undefined reference to `fToC' — the rest is mostly just "noise". Learning to find the useful parts of an error message is an important skill!

  2. Missing semicolon. Here's a sample error message for that one:

    -bash-3.2$ make secondCProgram
    cc secondCProgram.c -o secondCProgram
    secondCProgram.c: In function ‘fToC’:
    secondCProgram.c:13: error: expected ‘;’ before ‘}’ token
    make: *** [secondCProgram] Error 1
    -bash-3.2$

    The useful part here is "secondCProgram.c:13: error: expected `;' before '}' token

    This is telling us the exact line number where the compiler encountered the error. A trick we can use is this: if we type this at the unix command prompt, emacs will put us in the editor, with the cursor right on line 13!

    emacs +13 secondCProgram.c

    Then, we are likely to find the missing semicolon just before the place where the error was spotted. In this case, the compiler didn't realize a semicolon was missing until it hit a later } character (which it calls a "token" for technical reasons we may discuss later.)

  3. Forgetting the closing " on a string, e.g in a printf or scanf call. Here's an error message for that:

    cc secondCProgram.c -o secondCProgram
    secondCProgram.c:28:14: warning: missing terminating " character
    secondCProgram.c: In function ‘main’:
    secondCProgram.c:28: error: missing terminating " character
    secondCProgram.c:29: error: expected ‘)’ before ‘;’ token
    secondCProgram.c:41: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast
    secondCProgram.c:41: error: expected ‘;’ before ‘}’ token

    This can be a particularly confusing one, because except for the first error message about a missing terminating " character, all the rest of the error messages are bogus. Once the missing terminating character is fixed, all the rest of the errors go away.

    One conclusion that you may draw from this is the following—until you are fairly experienced in looking at syntax error reports from the compiler you are using, it is best to focus on only fixing one error at a time, generally the first one reported from the compiler. Often, fixing that one will make many other error messages go away at the same time.

There are many others, too numerous to mention, but I hope this gives you a "good start".

Your task now is this—if you got syntax errors, go back into the editor with:

emacs secondCProgram.c

or, if you know the problem is on a particular line, say line 28, use:

emacs +28 secondCProgram.c

Fix the problem, and try the make secondCProgram command again.

When it finally works, run the program with

./secondCProgram

and make sure the output is reasonable. If it doesn't work properly, then continue to make changes until it does.

Once it is working properly, you are ready for step 9, the "scripting step".

Step 8: Scripting your assignment

In this step, we create a "transcript" of your work. We only do this after everything else is finished, and you are sure you have a good working product.

Here are the steps to prepare to make a transcript for lab01

  1. Type pwd, and make sure you are in the ~/cs16/lab01 directory.
  2. Type ls, and make sure that you have a file called secondCProgram.c in your directory
  3. Type ./secondCProgram and make sure your program works correctly.
  4. Type rm ./secondCProgram (WITHOUT the .c on the end) to delete ONLY the executable.
    • Be sure you KEEP the secondCProgram.c file! Otherwise you'll be starting from scratch!
    • (I've been there and done that before!)

Now, to create your script:

  1. Type script lab01.txt
    You'll get back a regular looking unix prompt, but something is different now—everything you type, and everything that comes back from the computer is being recorded into a file called lab01.txt. It's like turning on the video camera.
  2. Type pwd to show what directory you are in.
  3. Type ls to show what files you have. (If you did the preparation correctly, we should see secondCProgram.c, but we should NOT see the executable file secondCProgram (the one without the .c on the end.)
  4. Type make secondCProgram to show that your program compiles with no errors.
  5. Type ./secondCProgram and run your program with several inputs to show that it works correctly, converting from Celsius to Fahrenheit. After doing at least three conversions on different numbers, type 0 when asked if you want to do more conversions, to end your program and return to the Unix prompt.
  6. Type exit to stop the recording of commands and responses into lab01.txt

When finished, type ls one more time, and you should see a new file in your lab01 directory called lab01.txt.

Use this command to list out the contents of that file:

cat lab01.txt

You should see your life flashing before your eyes, so to speak—a feeling of déjà vu should come over you—becuase everything in the file will be what you just typed and what came back over the last few minutes.

If so, you are ready to submit!

Step 9. Submit your assignment using the turnin program on CSIL

To submit your assignment, you need to be in the ~/cs16 directory—one level higher than the previous step.

You can use the command cd .. to put yourself there, or cd ~/cs16

Do a pwd command to make sure that you did land in ~/cs16.

When you are in inside your cs16 directory, you are ready for the turnin step.

Type the following at the prompt:

turnin lab01@cs16 lab01

You may see a warning like this one:

************** WARNINGS **************
lab01/secondCProgram.c~: NOT TURNED IN: temporary file

*** Do you want to continue?

If so, don't worry—just type y and hit return to indicate you want to continue.

You'll be asked if you really want to turn in these files—the message will look something like this:

These are the regular files being turned in:
   Last Modified   Size   Filename
-------------- ------ -------------------------
1: 09/30/09 23:35 1232 lab01/firstCProgram.c
2: 10/01/09 01:12 1234 lab01/secondCProgram.c
3: 10/01/09 01:12 167 lab01/lab01.txt
4: 10/01/09 01:12 5360 lab01/secondCProgram **************************************************************************** You are about to turnin 4 files [11KB] for lab01 to cs16 *** Do you want to continue?

The main thing is to be sure that lab01.txt and secondCProgram.c appear in the list. (If the other two appear or don't appear, it doesn't really matter.)

Go ahead and hit y and enter, and you should see a message like this one:

lab01/firstCProgram.c
lab01/secondCProgram.c
lab01/lab01.txt
lab01/secondCProgram

*** TURNIN OF lab01 TO cs16 COMPLETE! ***

Congratulations—you've completed your second lab in cs16!

Note: they do get progressively more challenging!


Evaluation and Grading (200 pts total)

Due Date: You should try to complete this assignment by the end of end of your second discussion section, i.e. before 10:50am, 11:50am, or 12:50pm on Friday 10/02/2009 (depending on which section you are enrolled in.)

If you are unable to complete it by the end of your discussion section you may continue to work on it through the week. Please have it completed and turnin command finished by 10pm on Wednesday October 7.

Late assignments will only be accepted (with 20 point penalty) up until the time the TA doing the grading is finished with grading and posting a particular assignment. There is no specific guarantee as to the length of that period of time.

After that, a zero will be recorded, and the only option is to make up the points via extra credit.


Copyright 2009, Phillip T. Conrad, CS Dept, UC Santa Barbara. Permission to copy for non-commercial, non-profit, educational purposes granted, provided appropriate credit is given; all other rights reserved.