Lab 1: Trying out C

The goal of this lab is to give you some initial practice with C.

1. Set up

Make a folder for this lab and move into it.

mkdir lab1
cd lab1

As in most labs and projects, I am giving you some code base to work on. Copy the following files from the course directory for this lab.

cp /homes/tvandrun/Public/cs245/lab1/* .

This gives you nine files:

These last two are the only files that you will need to modify.

2. Selection sort

Open selection.c in gedit, emacs, or xemacs. You will see it contains only a basic stub for the selection_sort function. This function takes (a reference to) an array and the size of the array n. Implement the selection sort algorithm:

Compile your code using

gcc -c selection.c

Once you have fixed any compilation errors, you can compile and link the utility library and driver program for selection sort:

gcc -c sort_util.c
gcc -c test_selection.c
gcc test_selection.o sort_util.o selection.o -o test_selection

Seem like a lot of steps? Then just use the make command:

make test_selection

Once it all compiles, run the driver using

./test_selection

Use the results of the driver program to debug your implementation of selection sort.

3. Substring

You should remember the Java method substring() by which you can make a new string from a sequence of characters from another string. You will write a similar function in C. The protocol for the function you will write (you'll find this protocol in substring.h and a stub in substring.c; open the latter) is

int substring(char source[], char destination[], int start, int stop);

Note that this function takes (references to) two arrays---the first is the array we are copying from, the second is the array we are copying the characters to. You don't need to know their sizes; all you care about is where the string ends (you have to assume that the arrays are big enough to hold the respective strings). The function also takes a starting index (inclusive) and stopping index (exclusive). It copies the subsequence source[start, stop] to destination[0, stop-start] and adds an end-of-string marker to position stop-start.

However, to make this function extra robust, we want to make it work even when "bad" values for start and stop are given. Here are the rules:

Don't forget that the "destination" string must end in an end-of-string marker, even if a no characters are copied.

Compile with

make test_substring

Test with

./test_substring

Thomas VanDrunen
Last modified: Mon Jan 12 09:55:00 CST 2015