CECS Home | ANU Home | Search ANU
The Australian National University
ANU College of Engineering and Computer Science
School of Computer Science
Printer Friendly Version of this Document

UniSAFE

Introduction to Computer Systems

Tutorial / Laboratory 02 - Basic C Programming

Week 4


Preparation Exercises [1 mark]

Read up c programming language. Either one of the recommended book also the wiki page on the c programming language is a good place to start.

Complete the following questions on a separate sheet of paper, with your name and student number clearly written. Please ensure your writing is legible. Hand in to your tutor at the beginning of your tutorial / laboratory session:

  1. How are booleanings represented in c? What are is an advantage of this approach? What is a disadvantage?
  2. Why is c a good programming language for systems programming?
  3. What is the relationship between pointers and arrays in c?
  4. How are stuructures defined?

Tutorial Exercises [1 mark]

  1. Discuss any unsolved issues from Tutorial 1. Discuss any questions in relation to the first assignment.
  2. Discuss the answers to the preparation exercises.
  3. 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 [3 marks]

  1. Go to the web pages: 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 7: 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.

     

  2. 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 gedit, 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.

     

  3. Use the command emacs program1.c & or gedit 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.

     

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


    We expect that in week 4 most people will get to about here. Please take some time to complete it before your week 5 tute/lab. Get your tutor to mark of what you have done to this point and have the rest of the lab marked off at the beginning of next week.

     

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

     

  6. (optional - required for COMP6300 students) 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.

  7. (optional) 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!)