|
|
COMP2300 / COMP6300
Tutorial / Laboratory 02 - Basic C Programming
Semester 1, 2009
Week 3 (10 - 13 March)
It is not expected that you complete all of this lab in week 3. There
will be time to continue this lab, but, with the exception of the
advanced exercises, you should complete it by week 4. Note that there is
submitable work which is due by 9 am Tuesday March 17 (week 4), which
will contribute up to 1% of your assessment (in the Tute/Lab mark).
Tutorial Exercises
Note that there is no Preparation Exercise this week! However, you
should prepare by reading up on C and read in advance lecture C2, as the arrays, functions
and input sections are highly relevant to this Lab Exercise.
- Discuss any unsolved issues from Tutorial 1. This can include questions related
to Part 1 of Assignment 1, including
what degree of work is required and setting out. Note sample answers are now available.
- Class discussion: compare C with other languages you are familiar
with (e.g. Java and Haskell). What makes C a better systems language?
Compare C with other languages for general software engineering.
Laboratory Exercises
- On the COMP2300 Web site and under C programming on
the Related Links page you will find some
Interactive Tests (note that JavaScript support is
required). Do the following tests:
- Test 1: defining variables (Qs 1, 2, 3, 6)
- Test 2: simple assignments (Qs 1, 2, 4)
- Test 3: printf() (Qs 1, 2, 4) and scanf() (Qs 6, 8)
- Test 4: for loops (Qs 1, 2)
- Test 5: while and if-else (Qs 1, 2, 3, 4)
- Test 6: arrays (Qs 1, 2, 3)
- Test 8: functions Qs 1, 2, 3)
Try to do these quickly; check with your neighbour or tutor if in doubt
on any answer.
Remember, as mentioned in lectures, ++ is a pre or post
increment operator, so
i++ is the same as i=i+1.
Also, when declaring (or prototyping) a function, including the
names of the parameters is optional - including them is good
practice (and should be done in the assignment), but their
inclusion is not mandatory. The types of the parameters,
however, do need to be included. Example:
double sqrt(double); is a valid function prototype.
- Open a terminal window and create a lab2 directory in
your comp2300 directory, and make lab2 the
current directory. Use the command
cp /dept/dcs/comp2300/public/lab2/*
~/comp2300/lab2/
to copy the files required for the lab into your lab2
directory. Check with ls which files have been copied.
Note: The wildcard * is used in Unix as a placeholder
for any name (similar, A* would stand for all files
beginning with an A).
We will use an editor, e.g. emacs or kate, to edit
the source code (*.c files) and then manually
issue the commands to compile and link the modules. These
commands can be put in scripts or a Makefile but we
won't worry about that in this lab.
- Use the command emacs program1.c & or
kate program1.c &
and edit the file program1.c.
The & is important, as it starts the editor as a
background process, which allows you to keep using the
terminal window whilst the editor is running.
Towards the top of the file is a #define statement
for the macro called MY_NAME. Change the replacement
text for this macro to your name (in quotes), and save the
file. Example: #define MY_NAME "Fred Smith"
Start by compiling program1.c using the following command
gcc -Wall -o program1 program1.c
Check that the executable was produced (there should be a file
called program1 in your current working directory), and
then run it by
typing the command ./program1 (the ./ at the
beginning is needed to tell the terminal shell that the executable
is in the current directory). What's wrong with the output?
Note that the source code for the program contains a prototype
for a function called length(), which takes a string (an
array of char) as a parameter, and returns an
int. Replace the 0 in the second printf()
statement with a call to the function called length(),
with MY_NAME as the parameter. Write an implementation
of the length() function, putting it at the bottom of the
file.
To determine the length of the string passed to it as a
parameter, the function can use a while loop to step
though the elements of the char array, until it finds a
null character ('\0') - the not equals operator
!= will be useful here. The number of loop iterations
is then the length of the string.
Compile and link the program again, using the same commands as
before. Then run it and check that it works. If it won't
compile or doesn't give the correct output, check everything
you've done and try to determine the problem. If you've spent
more than ten minutes trying to fix it without success, ask
your tutor for help.
- Compile and link program2.c in the same way as you did
program1.c. Use the command
./program2 < rainfall_data.txt
to run the program, with its input being taken from the file
rainfall_data.txt. Note that the output says the average
rainfall was -999.99mm; if you use emacs or
less to view the contents of rainfall_data.txt,
you can easily see that this average is wrong.
Open the file called program2.c in a text editor. There
are three function prototypes, one of which has an existing
but empty implementation. Complete the implementation of the
first function, then check that your program still compiles and
runs. Implement the other two functions, and make changes to
the statements in main() so that these functions are
called when appropriate.
Apart from this, do not alter otherwise the printf()
statements, or add any other printf() statements.
Your program will be automatically marked on the (exact) correctness
of its output.
You will now need to customize your command line environment for this
course (including being able to access the previewAutoMark
command below). To do this, execute the command emacs ~/.cshrc &
()or kate ~/.cshrc &,
and add to the file the line:
source /dept/dcs/comp2300/login/Cshrc
Make sure the line is properly terminated (press the `Enter' key at the end of
the line -- otherwise it won't work!), save the file and exit the
editor. Finally, propagate the change to your current shell (command
window) by typing the command source ~/.cshrc .
Once you are satisfied your program is running, test it for
correctness with the command:
previewAutoMark lab2 program2.c
This will test your program against some more sample inputs, and
predicts its score for the automated marking upon submission.
Once you are satisfied (or in any case make an initial submission
before the end of your session, even if on an
unmodified version of the program, to test the submission system),
submit it using the submit command:
submit comp2300 lab2 program2.c
submit comp6300 lab2 program2.c
This is due by 9 am Tuesday March 17 (the deadline is strict)
and will contribute up to 1% of your Tute/Lab mark.
This command does an ssh onto a server, and may
require you to type in your ANU password.
Look carefully for any error messages - just because it accepted
your password it does not mean the submission succeeded!
Note also the pitfall that if you have a space in the name of the directory
you submit from (or any if its parent directories, the command will not work
(believe it or not, this is a very difficult thing to fix).
It is recommended that you always log into
StReAMS to verify any important submission.
If you have problems with submission, TELL YOUR TUTOR. It is
important that we fix this ASAP!.
We expect that in week 3 most people will get to about here.
You will have time to continue it in week 4, so
don't panic.........yet! ;-)
- Load the file called program3.c into a text editor. The
program is supposed to display a menu, ask you to enter one
of the displayed options, run the corresponding function
and then display the menu again, repeating this cycle until you
enter the quit option. Most of the program has been
written, but you need to complete the section inside the
do...while loop and change the while condition. There
are some comments in the code to help you with the structure,
and you will need to use the strcmp() function (string
comparison function, use man strcmp for more details or
look in your C book) in conjunction with an if
statement.
A good place to start programming is to get the quit
option working, i.e. read in the option string and either drop
out of the loop if quit was entered or go back to the
top of the loop if it wasn't (you'll need to use
strcmp() in the while() condition to test this).
Once you have done this much, compile and link your program and
test it. Once you are sure the quit option works, make
the changes needed to call the functions corresponding to the
other options, and then compile and link again to test the
changes.
Is your code case sensitive? Should it be? Do you want to
compare the entire character string or just the first
n bytes? Take a look at strcasecmp() and
strncasecmp()
- Supplementary question: Return to program1.c and
write a function reverse()
which reverses a given input string, and use this function to
print your name in reverse order.
- Supplementary question: The following program is taken from the 2003 COMP2300
examination paper. It uses two library functions
(islower() and isalpha()) to determine
properties of character variables. Type man islower and
man isalpha in your terminal to see the details of what
these functions do. Using just this information predict what
output you will obtain from running this code.
#include <stdio.h>
#include <ctype.h>
int main() {
char name1[] = "My-COMP2300-Notes\\";
char name2[] = "28-July-2003 \\noon\\";
int i, nlower = -2, nalpha = -4;
printf("C Programming Example\n" /* );
printf("Comparison Strings" */ );
printf("%s\n", name1);
printf("%s\n", name2);
for (i=0; i<15; i++){
if (islower((int) name1[i]) || islower((int) name2[i])) nlower++;
if (isalpha((int) name1[i]) && isalpha((int) name2[i])) nalpha++;
}
printf("Total number of lower case =%5d\n", nlower);
printf("Total number of alphabetical =%5d\n", nalpha);
return 0;
}
Now copy the code into a file (e.g. called exam.c)
compile and run it in the same way you did for
program1.c. Does your prediction agree with the
observed output? If not, then your prediction is wrong (not
the program)!! Consider carefully the code until you understand
exactly what it is doing and why it is giving the printout it
does. If necessary talk with your tutor as it is important that
you understand this.
The exam question went on to ask you to write C code for two
functions
int myislower(int c);
int myisalpha(int c);
that perform exactly the same operations as the library
routines islower() and isalpha(). Try and do this
for at least one of these functions. In both cases the code you
write should be less than about 10 lines of code. Check that it
works correctly by replacing the calls to islower() and
isalpha() with calls to myislower() and
myisalpha(), compiling the revised code and ensuring
that it gives the same result.
(If you have managed to complete this question without errors
you would have scored 11 marks out of the 100 on offer in the 2003
years exam; however, not many people managed to get this
completely correct!)
Last modified: 6/03/2009, 15:43
|