comp labnotes

Upload: kebl3630

Post on 06-Apr-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 Comp Labnotes

    1/53

    1st Year Computing LabDr. S.J. Payne1

    Michaelmas Term, 2004

    Introduction

    Many/most of you will already be familiar with using a computer, probably either Windows

    on a PC or MacOS on a Mac. Fewer will have any experience of actually writing computer

    programs.

    The purpose of the five two-hour sessions in the laboratory is to give you an opportunity todiscover and familiarise yourself with the computing facilities within the department, and to

    introduce you to the ideas behind writing your own computer programs (via a language called

    C).

    Procedure in the Laboratory

    The exercises in this document are to be performed over your five two-hour periods; i.e.,

    one per session. You must have each assessed and signed off by a demonstrator before

    starting on the next one. You may also work on your exercises outside of your scheduled

    laboratory hours, and are encouraged to do so.

    You should attend all scheduled laboratory sessions. Tutors will be informed of non-

    attendance where there appears to be no legitimate reason. Bring your attendance sheet

    provided with these notes to all labs. I recommend pasting it into your log-book so you

    dont lose it.

    Work in pairs, using the Sun workstations at the right-hand (northern) end of the 6th

    Floor Solarium.

    Prepare for each session by reading through the notes beforehand so that you are not

    wasting lab time reading when you could be doing the exercises. Make good use of demonstrators, consulting them regularly, and not necessarily just when

    you get stuck. They may be able to give you all kinds of useful tips and insights.

    You should keep notes on your work in your log book. When an exercise is assessed, your

    log-book will be inspected. Plots and programs on the computer may also be inspected.

    In some places these notes prescribe what you should write down in your log. In others

    use your common sense and bear in mind what should become standard good practice:

    write down things which will help you remember what you did and why!

    1PDF versions of these lab notes are available on the web at http://www.robots.ox.ac.uk/ sjp

    1

  • 8/2/2019 Comp Labnotes

    2/53

    You can ask a demonstrator to mark each exercise as soon as it is completed (not only at

    the start or end of sessions). Please note that you must be ready, logged onto a computer

    and prepared to demonstrate your work, when you ask for a demonstrator to come andmark.

    If you do finish an exercise early, you are advised to begin immediately with the next one

    since the exercises become progressively harder and doing so will allow you extra time

    to complete these.

    If you do not complete all the exercises by the end of your fifth session, there will be

    final marking-only sessions scheduled later in the term check the 1st yr noticeboard for

    details of these.

    Conversely, if you andyour partner have completely satisfied the demonstrators that you

    have completed all the exercises, by all means get signed off early.

    Lab Summary

    The aim of each sessions is as follows:

    1. Familiarisation with the machines and their operating system, Unix

    2. The basics of C language programming and the edit/compile/test development cycle

    3. Using C to analyse an engineering system

    4. C arrays, and a more advanced application

    Each lab and its accompanying exercises is designed to occupy about 2 hours, other than the

    last one, which may take you more (4 hours has been allowed).

    Learning Outcomes

    At the end of the lab you should be very familar with using the Unix workstations and have a

    working knowedlege of the C programming language. You should be able to dissect code that

    someone else has written to perceive its meaning/purpose, and be able to write small programs

    yourself.

    2

  • 8/2/2019 Comp Labnotes

    3/53

    1 The Machines, Unix and CDE

    This session provides introductory material which you and your laboratory partner should readand work through step by step to familiarise yourselves with the machine and its operation.

    Please KEEP TO THE INSTRUCTIONS IN THEIR GIVEN ORDER.

    They have been designed, amongst other things, to allow both you and your lab partner to log

    in and out and change passwords during the session.

    Summary of what you have to do this session

    Preparation Spend 10 minutes on this before arriving at the lab

    Register Bring the signed agreement and collect your username

    Unix/CDE/ Spend about 30 minutes working through

    File management There is no need to record this in your logbook

    EXERCISE 1 Record in Log and get it signed off

    Spend about 40-50 minutes on this

    WWW Use of Netscape and the World-wide Web

    Email Setup your electronic mail facilities

    Logging out Is essential!

    Document conventions

    this typeface indicates something you should type.

    1.1 Preparation before the session

    1.1.1 Hardware

    Take note of the safety information posted up in the lab on correct posture, etc, when using

    computing equipment, and assure yourselves that you can distinguish between the keyboard,

    mouse and screen!

    A much simplified picture of the components of each workstation is shown in Figure 1. The

    heart of the machine is the Central Processing Unit (CPU) which executes system and user

    programs. The workstations you will be using are built by SUN, and the cpu has a risc ar-

    chitecture called Sparc (scaleable processor architecture) or in later machines ultraSparc. The

    CPU communicates with main memory and various input/output devices along internal busses.

    The machines have several tens of MB of main memory (random access memory or RAM), an

    several MB of Video RAM to run the screen, and various i/o (input/output) interfaces to the

    keyboard, mouse, local disk, and ethernet.

    Please observe the following:

    3

  • 8/2/2019 Comp Labnotes

    4/53

    Dont switch off the computers system box. You are likely to corrupt the file system and

    destroy the work of others may be remotely logged in to your machine.

    Dont jolt the system box.

    If you experience hardware problems, ask a demonstrator.

    1.1.2 Running Programs

    Just in case you needed to know, a program is a sequence of instructions (a recipe, if you like)

    to the computer to perform a set of actions to get some useful stuff done.

    Such a banal description belies the fact that today, computer programs are the most compli-

    cated engineering systems ever to exist, and how best to manage the design, build and test of

    software is still the subject much research and conjecture.

    The ability to start a program doing its stuff i.e. to execute is supplied by the operating

    system, a program which runs all the time and monitors requests and manages the system re-

    sources. The Suns use Solaris, their version of the UNIX operating system which is available

    of a wide variety of processors. The kernel (core part) of the operating system is initimately in-

    volved with the hardware, but built around the kernel there are layers of software which protect

    the user from the details below.

    In operating systems you may well be familiar with (e.g. Windows, MacOS), the request to the

    operating system from a user to run or execute a program typically takes the form of a mouse

    click on an icon, or an appropriate selection from menu. This is also available in Solaris (the taskbar has icons representing various programs including file-managers, editors, browsers, etc), but

    more common in UNIX is a command line form, where you type the name of a program to a

    prompt.

    Some programs that you will need to run come with the operating system itself. The most

    important and commonly used are the commands which allow you to copy, move, delete, view,

    print and list files and directories of files. Less fundamental are utility programs which allow

    you to have an on-screen calculator, print a calendar, and so on.

    Other programs available to you dont come with the operating system, but are of especial use

    to you as engineers. There are programming languages (like Matlab, C, Basic), scientific word

    processing packages (eg Latex), text-editors, drawing packages and so on.

    Finally, there are programs that you write yourself, typically using a high-level language.

    MAIN

    MEMORY BUS

    CPU

    MEM

    SCREEN

    VRAM

    KEYBDLOCAL MOUSE

    DISKS

    ETHERNET

    IO BUSIO

    IFACE

    Figure 1: The main components of the workstation

    4

  • 8/2/2019 Comp Labnotes

    5/53

    booth42.ecs booth43.ecs

    lucrece.robots claribel.robots

    router.stannes pc1.stannes

    Rest of UK

    and world

    Backbone

    optical fibre

    network

    Figure 2: The Ethernet connects the workstations to a fileserver and beyond

    1.1.3 Filestore

    You have a private store for your own programs and data files, and you might be wondering

    whether you have always to use the same machine. Actually your files are not held on local

    disks i.e. they are not on the disk in the box in front of you but on much fatter and faster

    disks attached to a machine, a fileserver, in another part of the building. All the machines are

    linked via an Ethernet cable (probably a thin black coaxial cable at the back of the machine) to

    each other and to the file server. In this way, a single copy of a program can be used by many

    users: and your filestore appears exactly the same on any machine.

    1.1.4 File managers: to drag and drop or not to drag and drop?

    Many (almost all) of you will be familiar with using drag and drop file managers as seen in

    MacOS and Windows 9x/2K, where by dragging a file icon around you can move files from

    directory to directory, or drag them into the wastebin, and so on.

    The Common Desktop Environment (CDE) has a drag and drop manager which you may use

    later (see the filing cabinet icon on the task-bar at the bottom of the desktop) , but in these exer-

    cises we will use typed commands. There are two reasons. First, to maintain portability, many

    Unix programs retain the command line approach. Secondly, it should help you understand

    more clearly the way your filestore is structured.

    1.1.5 Communications

    The local network in turn attaches to a University wide optical fibre backbone, which in turn

    connects to the national and international network (see Figure 2). The simplest use of the

    network is to send electronic mail to others, but soon no doubt you will wish to log in remotely

    to the Departments computers from your college and of course most of you will be seasoned

    surfers of the web.

    5

  • 8/2/2019 Comp Labnotes

    6/53

    1.2 Getting started

    1.2.1 Logging in

    Decide who is going to log in first. Half way through the practical you will swap logins so that

    both get to change your passwords.

    If the screen is dark, hit any key and it should light up to reveal a login prompt.

    To begin, you need to click with the mouses MIDDLE button on the options box. Observe the

    menu which appears and move the pointer down to the Session option and click on it. Finally,

    select (by clicking with the mouse again) the option Common Desktop Environment (CDE).

    Your selection should be remembered for your subsequent sessions.

    Now, in the box provided, type in your username and when prompted, your password. If you

    type an incorrect letter, use the BackSpace key to erase it.

    login: u03xxx [return]

    password: yoursecretpassword [return]

    Provided you have typed everything correctly, you should now see a screen with some icons at

    the bottom. This graphical user interface (GUI) is the Common Desktop Environment, or CDE.

    If you click on the main background on the screen with the RIGHT mouse button, a menu will

    appear (see Figure 3). You can experiment with this later if you have time, but for now, select

    the Programs option (by clicking on it) which in turn brings up a sub-menu. Select Termi-

    nal from this menu and you should see a window appear, waiting for you to type commands.

    Depending on the machine you have logged into, the menus may not appear identical to the

    one shown here. Dont panic just have a look through the various submenus until you find

    Terminal, and failing that, check with a demonstrator.

    An alternative way to achieve the same effect is to click the small arrow just above the pa-

    per/pencil icon on the toolbar at the bottom of the screen and then click on the Terminal icon on

    the menu which appears.

    1.2.2 Giving commands to UNIX

    Focus on the terminal window you have just invoked.

    When you start a terminal window, you are placed in your home directory, so you should see

    something like the following:

    booth42.ecs:/blah/u03xxx%

    You are on the machine booth42.ecs and your home directory is /blah/u03xxx. The blah

    part is of course replaced by something which may vary from user to user, and machine to

    6

  • 8/2/2019 Comp Labnotes

    7/53

    Figure 3: Sketch of desktop layout after starting CDE, and the menu which appears when you click the

    RIGHT mouse button

    machine. (This variation is often hard to understand. It arises because disks are distributed over

    the network and may be mounted at several points. It really is not worth thinking about!)

    The prompt % is a prompt for you to type a command to the operating system. Now click

    with the mouse in the Terminal window, and you should see the window frame change to a

    reddish colour (if it wasnt already). This indicates that the window has focus (ie it is active)

    and that Unix is ready and waiting.

    Type a Unix command. For example,

    booth42.ecs:/blah/u03xxx% cal 10 2002

    causes a calendar for this month to be written to the screen, whereas typing

    booth42.ecs:/blah/u03xxx% date

    will give you todays date and time.

    1.2.3 Change your password!

    Before getting too involved, now is the time to change your password using the passwd com-

    mand. Decide on a new password. It must be at least six characters long. It must not be your

    username. It must not be a word in the English dictionary. It must not contain triple letters (eg

    aaahchoo). Dont choose anything obvious like your initials and year of birth but dont choose

    something you cant remember or cant type. You can use a mixture of upper and lower case,

    and mix in punctuation and numbers.

    Type

    7

  • 8/2/2019 Comp Labnotes

    8/53

    booth42.ecs:/blah/u03xxx% passwd

    and follow the instructions.Two important things about passwords:

    There is a delay of a few minutes while the change in password is passed around system.

    So during this time do not logout. We will return to logout at the end of the session.

    NEVER divulge your password to another person inside or outside the Department. If

    you are tempted to swap passwords with your prac partner or a friend from another De-

    partment or University just for a wheeze dont. At worst it may lead to loss of your

    files; at best, as routine checks are made on remote logins to the system, your abuse of

    the rules will be detected, and unpleasantness will ensue.

    1.3 Getting a feel for the CDE

    Many of you will be familiar with using a GUI to communicate with a computer - all provide

    multiple windows where different tasks can be executing and a mouse to provide a means to

    select between windows, to move and close windows, to select from menu items, and so on.

    Although all have the same goal, each differs slightly in feel. Spend a few minutes now getting

    the feel of CDE, using the guide below.

    1.3.1 The mouse

    We have already seen that clicking the mouse in a window makes it active. Your mouse has

    three buttons, although in CDE only the LEFT and RIGHT have special functions.

    1.3.2 Operations on an existing window

    You should practice each of the following.

    Moving. Hold the LEFT button down over the top bar and drag.

    Resizing. Hold the LEFT button down over any of the four corner tags and drag.

    Minimising. Clicking the LEFT button on the small dot near the top right of the frame

    will close the frame down into an icon on the left hand side of the desktop. To re-open the

    window, double click the LEFT button on the icon. Note that the contents of the window

    are restored exactly.

    Scrolling up/down. The scroll slider is described as an elevator. Click on the up/down

    arrow on the scroll elevator to move up/down a line. Click on the cable above/below the

    8

  • 8/2/2019 Comp Labnotes

    9/53

    elevator to move up/down a page, and click and drag the elevator itself to slide the text up

    or down.

    Quitting or Closing. Press the LEFT button over the small bar in the top left hand cornerof the frame. A menu appears in which the final option is Close. The same menu

    appears if you click with the RIGHT button anywhere on the window frame. Quitting

    destroys the process that runs the window. There is no way of recovering it.

    1.3.3 Starting up new windows

    Other than running out of memory there is no limit on the number of windows you can open.

    Note that you can open multiple independent terminal windows.

    Holding down the RIGHT button anywhere on thedesktop background makes a Workspace

    Menu appear (see Figure 3 above). Clicking the Programs item makes the Program se-

    lection menu appear, from which you can choose a variety of useful programs. Open a

    couple of terminal windows, try the clock and the calculator and the performance meter.

    Try closing the windows down to icons and then restoring them by double clicking on

    them.

    As hinted at earlier, these programs, and many more, are also available by typing the

    appropriate commands in a terminal window. To convince yourselves of this, type in the

    terminal window

    % /usr/dt/bin/dtterm &

    and another terminal windows appears. (The & symbol tells Unix to run this program

    independently in the background allowing the calling terminal to continue to work inde-

    pendently of the newly created one and, no, dont type the %, that is the prompt.)

    1.4 Organizing your filestore

    1.4.1 Listing the files in a directory

    As mentioned earlier, when you login to the machine, it sets you into your home directory.

    The ls command will list the files in the current directory. Type

    booth42.ecs:/blah/u03xxx% ls (this is ell ess, NOT one ess)

    to see what is there. There is probably nothing.

    One can get more information using

    9

  • 8/2/2019 Comp Labnotes

    10/53

    booth42.ecs:/blah/u03xxx% ls -l (ell ess space minus ell)

    Note that the minus letter is the usual way of providing an option to a Unix command. They

    are called flags.

    Information about hidden files can be obtained by adding another flag, an a. Notice how the

    flags run together in this example.

    booth42.ecs:/blah/u03xxx% ls -al

    Information is stored on the computers disks in logical chunks called files. There are two sorts

    of files: text files (often called ascii files), and binary files. Text files are legible to you and the

    machine, binary files only to the machine. Text files are often created and modified by the user

    using a text editor but they can of course also be created as the output from a program.

    1.4.2 Text editing

    A simple text editor dtpad is provided as part of the CDE, which can be launched either from

    the toolbar, the dekstop menu, or from the command line by typing:

    booth42.ecs:/blah/u01xxx% dtpad &

    The window appears similar to that of a terminal window, but notice that there is no prompt

    typing into a Text Editor does not talk to Unix.

    Feel free to try out dtpad, but it is a very simple editor. A fully-featured editor you may want toinvoke for your subsequent use is xemacs. To launch it simply type:

    % xemacs &

    (dont forget the & at the end to tell Unix that this should be an independent background pro-

    cess). Assumping that most of you will be familiar with editors on PCs, the main editing

    features should be self-explanatory. If not, please ask a demonstrator to show you around.

    You will get quite a bit of practice using xemacs throughout the labs. For now, just type in some

    text, and save it into a file called test.txt (dont put anything of value in here since you will be

    deleting it shortly...).

    1.4.3 Viewing a text file

    You can view the contents of a text file either in an editor (such as xemacs) or you can conve-

    niently list the contents in a terminal window using the command cat:

    booth42.ecs:/blah/u03xxx% cat test.txt

    An alternative to cat is the very similar program more which does the same thing, but it pages

    the output if the file is longer than the terminal can show at once.

    10

  • 8/2/2019 Comp Labnotes

    11/53

    date

    filesession1 session2 session3 etc

    Current Working DirectoryHome

    Directory u03xxx

    Figure 4: The filestore structure after Step 1. The etc files probably wont be there!

    1.4.4 Making an orderly directory structure

    We could carry on making files here in the home directory, but it would end up being very

    confusing mass of filenames. Much better is to arrange files in related groups in directories.

    The usual and good analogy for a directory is a folder. Regard your filestore as a filing cabinet.

    Inside are various large folders: perhaps you want to separate the work you do in various labsessions. Inside the folders may be more smaller folders, and so on, until eventually some

    folders actually contain individual documents or files.

    Obviously we need a method of creating these directories or folders. The Unix command to do

    this is mkdir. Type

    booth42.ecs:/blah/u03xxx% mkdir session1

    booth42.ecs:/blah/u03xxx% mkdir session2

    booth42.ecs:/blah/u03xxx% mkdir session3

    Your filestore now looks like Figure 4 where etc stands for any other files that may be there,but which are nothing to do with your lab session! Later in the lab you will be asked to sketch

    filestores as tree structures.

    If you type ls -l you now see in addition to what was there before

    total 4

    drwx--x--x 2 u03xxx 512 Oct 1 17:32 session1

    drwx--x--x 4 u03xxx 512 Oct 1 17:33 session2

    drwx--x--x 2 u03xxx 512 Oct 1 17:34 session3

    Notice that in the block of 10 columns on the left, the leftmost indicates whether the file is a

    directory or not. The remaining 3 groups of 3 indicate the rwx (read, write, execute) permissions

    for the files and directories. The next number indicates the number of inodes, the next column

    the owner of the files, then the size in Bytes, then the date and time of creation, then the filename.

    We will return to consider permissions later.

    Note, another easy way to distinguish files from directories is with ls -F which places a /

    after a directory name, hinting that you can go further into the tree.

    11

  • 8/2/2019 Comp Labnotes

    12/53

    Home

    Directory

    date

    file

    progs docs

    sessi on 1 sessi on 2 sessi on 3 etcCurrent working

    Directory

    u03xxx

    Figure 5: File structure after Step 2

    1.4.5 Changing the current working directory

    At present we are in the home directory. To move between directories we need to change the

    current working directory. The command is cd. Change directory into session1 and make two

    new directories, progs and docs.

    booth42.ecs:/blah/u03xxx% cd session1

    booth42.ecs:/blah/u03xxx/session1% mkdir progs

    booth42.ecs:/blah/u03xxx/session1% mkdir docs

    Notice that when you change directory, the prompt reminds you of your new working directory.

    The file structure is now shown in Figure 5.

    To move back to your home directory type either:

    cd .. this moves you up one level in the directory tree

    cd on its own always moves you to your home directory

    cd the tilde character is shorthand for your home directory

    1.4.6 Copying, moving and deleting

    Three of the most commonly used commands are those to copy (cp), delete (rm) and move or

    rename (mv) files.

    Work out what each of the following commands does by trying them out, one at a time. After

    each one type ls -F to view the directory contents. Make notes in your log book to remind

    yourself, and discuss any problems you have with a demonstrator:

    % cp test.txt test2.txt

    % cp test.txt session1

    % mv test2.txt test3.txt

    % mv test.txt session1/docs

    % rm test3.txt

    % rm session1/test.txt

    12

  • 8/2/2019 Comp Labnotes

    13/53

    1.4.7 Names may appear relative, but are really absolute

    Commands like mkdir session1 and cp test.txt test2.txt create directo-

    ries or files in the current working directory. So it appears that filenames are described relative

    to the current working directory.

    Appearances deceive! File names are really absolute with respect to the filesystems root /.

    The file test.txt we created in your home directory has a full name of

    /blah/u03xxx/test.txt

    When you supply Unix a straightforward filename like test.txt, it automatically prefixes

    it with the path from the root to the current working directory front of it to make the

    filename absolute with respect to the filesystems root. But when you supply Unix with a filename starting with / it is used as an absolute

    filename.

    What is your current working directory? In the Solarium, simply to look at the prompt, but the

    formal way of finding out is to use the command pwd . Type

    % pwd

    The relative/absolute name mechanism makes referencing files in the current working directory

    and below (ie further from the root) very easy. However, now you need a shorthand to deal withdirectories above yours (ie those nearer the root than yours).

    Shorthand (1) uses the tilde to refer to your home directory. For example

    booth42.ecs:/blah/u03xxx/session/docs% cat /test.txt

    types out the file test.txt in your home directory.

    Shorthand (2): The directory immediately above your current directory is the parent di-

    rectory. In Unix, the ../ prefix refers to the parent of the current working directory. As

    examples try the following:

    booth42.ecs:/blah/u03xxx: cd session/docs

    booth42.ecs:/blah/u03xxx/session1/docs% mv test.txt ../..

    booth42.ecs:/blah/u03xxx/session1/docs% cat ../../test.txt

    booth42.ecs:/blah/u03xxx/session1/docs% cd ..

    booth42.ecs:/blah/u03xxx/session1% cat ../test.txt

    booth42.ecs:/blah/u03xxx/session1% cd ..

    booth42.ecs:/blah/u03xxx% (Back in your home directory)

    Shorthand (3): The current working directory can be referenced using . if necessary

    13

  • 8/2/2019 Comp Labnotes

    14/53

    1.4.8 Directories are tree structures

    Visualize your file store as a tree structure. You sit in the current working directory, and can

    move files up or down referring to them EITHER by a name relative to where you are sitting

    OR by an absolute name. You can move your current working directory using cd target-

    directory.

    1.5 EXERCISE 1

    Preamble

    Make sure that your are in your home directory using an appropriate cd command.

    Now type exactly this:

    booth42.ecs:/blah/u03xxx% /ecslab/demo/yr1/script1

    This shell program silently makes a new directory called exercise1 and a few more subdirecto-

    ries and files beneath, providing an instant file tree for you to explore.

    1.5.1 The tasks

    1. Your first task is to use the cd command and ls -F command to explore the file system,

    making a sketch of the tree in your log book. The tree is probably going to get cluttered,

    so spread each level out.

    Useful hints:

    ls -F prints a / after a name that is a directory. All the directories in the tree must be explored.

    Check with a demonstrator that you have drawn the tree correctly before continuing.

    2. Work out using your sketch how to type out the file socks without changing to its

    directory. Test it, and if you fail, think again. Write down the successful command in

    your log book.

    3. Change into the directory autumn, list the contents of the directory, and write down the

    time of creation and size of the files you find. Are any of these files actually directories?

    4. The directory structure as it is, is a mess. Use the commands cd, mv, cp and rm as

    appropriate to rationalise the directory structure.

    5. Change back (using cd) to your home directory, now move up up one more level in the

    tree. Write down the name of the current directory (from the prompt). List the files in the

    directory using ls . What are these? (NO! It is not just a list of usernames be more

    precise!)

    14

  • 8/2/2019 Comp Labnotes

    15/53

    6. Now get a demonstrator to check what you have done.

    1.6 Switch over now

    1.6.1 Partner 1 washes up (do this even when on your own!)

    Sit in your home directory.

    Delete all the working files you have made so far by typing the following commands

    booth42.ecs:/blah/u03xxx% rm -r session1

    booth42.ecs:/blah/u03xxx% rm -r exercise1

    and answering y when asked for confirmation. It is worth observing how Unix buries into the

    subdirectories during this recursive deletion!

    1.6.2 Partner 1 now Logs out (ignore if working alone!)

    You can either select log out using the Workspace Menu (recall you obtain this by right-clicking

    on the desktop, or by clicking on the Exit button on the toolbar at the bottom of the screen.

    1.6.3 Partner 2 now Logs in (ignore if working alone!)

    Follow the earlier procedure for selecting the CDE (via the Options button at the login prompt),

    logging in, starting a terminal window and changing your password.

    1.7 Redirection and piping

    1.7.1 Redirecting input and output

    Many/most programs write output to the screen (the standard output). Sometimes it is useful

    to store this information in a file (perhaps for future reference). Unix provides a convenientflexible way of doing this from the command line using what is known as output redirection.

    Likewise, many Unix programs (and programs you write) accept input from the standard input

    usually the keyboard. If, instead, you want the program to accept input from a file you can use

    the input redirection facility in the Unix shell.

    So that you can experiment with inout/output redirection, a simple script has been created to

    copy two programs square and cube into the current directory. To execute the script, do the

    following:

    Change to your home directory (cd ).

    15

  • 8/2/2019 Comp Labnotes

    16/53

    Create a directory session1 and change into it:

    % mkdir session1

    % cd session1

    Run the script by typing:

    % /ecslab/demo/yr1/script1.6

    Confirm that they have been copied correctly by typing

    % ls

    Now type

    % square

    This program waits for the input of a number from the standard input the keyboard and

    squares it, sending the output to the standard output the screen. Type:

    1 [return]

    1.000000

    2 [return]

    4.000000

    3 [return]

    9.000000ctrl-d (Press ctrl key and d key at the same time)

    To redirect the output from the screen to a file instead, use the output redirection arrow >

    followed by a filename:

    % square > out2

    1

    2

    3

    ctrl-d (Press ctrl key and d key at the same time)

    Note that the program reads the number, but the output goes into a file called out2. Look at the

    file by typing

    % cat out2

    If you ran the square program again and redirected the output to the file out2, the original version

    of out2 would get overwritten.

    To obtain redirected input from a file rather than the keyboard, you can use the opposite redirect

    arrow

  • 8/2/2019 Comp Labnotes

    17/53

    % square < out2 > out4

    and use cat to examine the file out4.

    1.7.2 Piping

    If one program writes to the standard output, and another reads from the standard input, you

    can pipe the output of one into the other.

    We could pipe the output of square into cube (the symbol is a Unix pipe):

    % square | cube

    1

    2

    3

    ctrl-d (Press ctrl key and d key at the same time)

    1.000000

    64.000000

    729.000000

    Check this makes sense to you! One peculiarity is that the numbers come out only after closing

    the input.

    You can even pipe into the same program! Type

    % square | square | square >out8

    1

    2

    3

    ctrl-d

    Look at out8. Is the output what you expected?

    1.8 Protecting your files

    Change directory to your home directory and type ls -l. You will see lines similar to some-

    thing like:

    drwx--x--x 2 u03xxx 512 Oct 19 17:32 session1

    -rw------- 1 u03xxx 29 Oct 19 17:32 test.txt

    The zeroth column in

    17

  • 8/2/2019 Comp Labnotes

    18/53

    0123456789

    rwxrwxrwx

  • 8/2/2019 Comp Labnotes

    19/53

    ew-5 bert 720 Oct 12 17:34 on booth31.ecs

    ew-10 u01xxx 1261 Oct 12 17:36 on booth41.ecs

    If you want to withdraw your job from a queue either because you have sent the wrong file

    or there are 37 huge jobs ahead of you and you dont have time to wait try

    % cancel ew-10

    You should print sparingly. The window environment and text previewers and interactive de-

    buggers make it an easy job to check for typographical or programming errors on the screen.

    To deter you, there are limits on the amount of paper and disk store you are allow to fill up. To

    obtain information about your quota and usage, type

    % quota -v

    1.10 Netscape and the World-wide Web

    The dtterm terminal window is quite a simple window - a plain pane. Netscape, a program to

    navigate the World-wide Web, exhibits more of the functionalty possible in a window; things

    like buttons to press, lines to fill with text and so on.

    You can launch Netscape by typing

    % netscape &

    in your terminal window.

    Most of you will already be seasoned web-surfers. At some point (NOT until you have com-

    pleted the rest of the exercise) it will be worthwhile to explore some of the resources available

    on the web, particularly those relevant to your course in Oxford. A few good local starting

    points are

    http://www.eng.ox.ac.uk

    http://www.bodley.ox.ac.uk

    http://www.oucs.ox.ac.uk

    1.11 Email

    You can send and receive email from/to your account here at Engineering. If your username is

    u03xyz, the email address associated with your account is

    [email protected]

    which is you @ (pronounced AT) ECSlab in OXford University, an ACademic site in the UK.

    For historical reasons, all engineering students are ecs.

    19

  • 8/2/2019 Comp Labnotes

    20/53

    1.11.1 Creating a .forward file

    As well as your computing account here at Engineering, you will also have been given an email

    account so that you can send and receive electronic mail at your college. The account name will

    be something like coll0123; ie 4 letter identifying the college and four numbers. The email ad-

    dress associated with this account will be something like [email protected]

    (eg [email protected]). This service is administered by the University Com-

    puting Services. If you do not have a Herald account already, you can register for one on-line

    by going to the web-page

    http://www.oucs.ox.ac.uk/registration/

    clicking on OUCS self registration, followed by High-Security self-registration page, and

    finally University (herald) account (and following instructions on the pages thereafter).

    Alternatively, get there in one step by going directly to

    http://register.oucs.ox.ac.uk:8123/cgi-bin/tegu/herald

    Since it can prove awkward to manage two separate accounts for email, we will now configure

    your account at Engineering so that email sent to you at your u03xxx address is automatically

    forwarded to your college address. If you have not yet received the details of your college email

    facility then you can follow the instructions below at a later date.

    Whenever email is delivered to a UNIX account, the mailer checks your home directory for the

    presence of a file called .forward (ie dot-forward). If it is present, it reads the file and expectsto find another valid email address in the text of the file. To create this file to ensure all mail

    arrives at your college address, type the command:

    % echo [email protected] > /.forward

    where of course you should substitute your own name and college as appropriate (also note the

    use of as shorthand for home directory and output redirection to a file).

    Check you have created the file with the correct contents by cating the file

    % cat

    /.forward

    If for any reason you want to prevent email being forwarded, you simply delete (rm) the .forward

    file.

    1.11.2 Accessing email via the web

    The University Computing Services (OUCS) which administers email within the University,

    has set up a service to enable users to read and write email via a web-browser. The service,

    known as Herald can be accessed from the web-page

    20

  • 8/2/2019 Comp Labnotes

    21/53

    https://herald.ox.ac.uk/

    Go to this page and follow the instructions...If all that has gone swimmingly you should now be able to test that (i) you can read email from

    the web and (ii) your .forward file is working.

    One way to test this will be to send email to yourself at your Engineering address u03xxx, and

    see if you receive it at your college address. Go to the Herald service and select the option

    to Compose/Send, entering your own ECS account address, [email protected] in the To:

    field. Soon after you have sent the mail, you should be able to read it via the Herald web-page.

    1.12 Cleaning up and Logging Out

    1.12.1 Partner 2 Cleans up

    Dont do this until you have completed the session and had everything signed off.

    Sit in your home directory.

    Delete any working files you have made in session1 by typing the following, and answering y

    [return] when asked for confirmation.

    booth42.ecs:/blah/u03xxx% rm -R session1

    Once deleted, files cannot be recovered.

    1.12.2 Partner 2 logs out Essential

    It is important not to forget to logout not doing so leaves your session open to others

    and your password and filestore become open to abuse by knaves.

    Click the Exit button in the centre of the toolbar at the bottom of the screen and confirm your

    logout. The screen should clear and display a clean login prompt.

    21

  • 8/2/2019 Comp Labnotes

    22/53

    2 C Programming Basics

    In this lab you learn how to build a simple C language program up from scratch.

    Summary of what you have to do this session

    Preparation Spend 10 minutes before the lab reading through

    to make sure you know what you should be doing

    Building C Programs Spend about 45 minutes working through

    EXERCISE 2A Spend about 20 minutes

    EXERCISE 2B Spend about 55 minutes on this

    2.1 Preparation

    A computer program is a sequence of instructions for the computer to carry out. Often we

    can write down in fairly general terms what it is we want the computer to achieve for us. The

    design process then involves refining this in greater and greater detail and eventually translating

    a formal specification into a particular computer language. Of course, we may (and usually

    will) get something wrong in the translation from specification to program, in which case we

    must debug our program.

    All computer languages offer, in some form or other, the ability to:

    perform input and output, so that a program can read data and write results out

    perform arithmetic functions, both simple and usually more advanced scientific calcu-

    lations as well

    perform repetitions of a group of instructions, known as loops

    test conditions and perform instructions selectively depending on the outcome

    store and recall results in memory, usually by assigning a label to a particular datum,

    known as a variable

    In addition, most have facility to:

    create reuseable routines of code known as functions or procedures

    To begin with in this session, you are going to create a program to compute the square of a set

    of numbers. Here is a rough specification in pseudo-code (i.e. a cross between english and

    some fictitious computer language) for the program we are going to create:

    22

  • 8/2/2019 Comp Labnotes

    23/53

    1. BEGIN

    2. PRINT START ME SSAGE

    3.REPEAT FROM START NUMBER UP TO E ND NUMBER

    :4. SQUARE THE NUMBER

    5. PRINT OUT THE RESULT

    6. PRINT END MESSAGE

    7. EN D

    C is a compiled language. This means that you write C source code into a file using an editor,

    then invoke a special program called a compiler which converts your source code into low-

    level machine readable instructions which are stored in a binary file known as an executable.

    In UNIX you can then execute or run the program by typing its name on the command line.

    Make sure you understand the distinction between source and binary files; ask a demonstrator

    to explain if you are not totally clear on this.

    2.2 Getting Started

    Login, and if necessary launch a terminal window.

    Focus on the terminal window and from your home directory, type

    % /ecslab/demo/yr1/script2 [return]

    which generates directories session2 and exercise2, and places several files in them. Change

    directory into session2.

    % cd session2 [return]

    You will also need a text editor and at this point it is recommended you use xemacs since it has

    some nice features for editing C programs. Recall that to run xemacs you should type

    % xemacs &

    2.3 Building a C program in Steps A-E

    Good programming practice in C involves top-down design. This means that you start with

    overall objectives, and gradually break these down into sub-tasks (which may in turn be ex-

    pressed as a series of actions) then map the actions directly to C program constructs.

    You are going to build a C program in elementary steps to highlight aspects of the structure of

    the language. At each step, you will compile and execute the program to see what happens.

    23

  • 8/2/2019 Comp Labnotes

    24/53

    2.3.1 Step A: A program that does nothing

    1. Edit the program source code:

    In xemacs open a file called squares.c in the directory session2. The file doesnt exist yet,

    so this tells xemacs to be prepared to create it, and to present you with an empty buffer

    in which to type. Type the following into it, and then save it. Dont shut down the editor,

    youll need it again:

    int main() {

    }

    2. Compile and link:

    At the moment, the program squares.c is just a text file, and cannot be executed by themachine. To turn this so-called source code into an executable file, we first compile

    the program, then link it to the other routines we require. Use the following incantation

    in the terminal window:

    % gcc squares.c -o squares

    The gcc program (The Gnu C Compiler) will compile squares.c, link it automatically to

    the standard C library, and the -o squares puts the executable output into a file called

    squares.

    3. Execute the programTo run the program, type in the terminal window:

    % squares

    Step A: Observations

    1. There were no complaints from Unix, so the program executed. However, as expected, it

    did not do anything.

    2. Every C program has at least a main routine, which is where the program starts ex-

    ecuting. All routines surround their bodies with curly brackets

    . If there were anystatements between the brackets we would expect/hope they would be executed in turn.

    Here though, there are no statements, so it does nothing.

    3. As we proceed you will see the development cycle emerging, of edit, compile, then exe-

    cute.

    Step B: Adding a statement

    Let us now add one statement to the main routine. This statement will do some output, satisfying

    line 2 of our spec.

    24

  • 8/2/2019 Comp Labnotes

    25/53

    1. Edit. Go back to the editor, and add in two extra lines

    #include

    int main()

    {

    printf("Squares from 1 to 10\n");

    }

    and then save again as squares.c.

    2. Compile and Execute

    % gcc squares.c -o squares

    % squares

    Step B: Observations

    1. Each statement inside the body of the code surrounded by the outer curly

    must end

    with a semicolon. The statement actually calls another routine printf(), which writes

    output to the standard output. The n puts a newline at the end of the text.

    2. The #include is a compiler directive which makes sure that C knows

    how printf() is defined. (stdio.h is a file defining a number of routines for input and

    output.)

    Step C: Adding comments

    It is good practice to add comments to help explain your code.

    1. Edit. Go back to the editor and add

    /* Name : squares.c */

    /* Version: 1.0 */

    /* Author : E Jarvis Thribbs */

    /* Date : 12 Oct 03 */

    #include

    int main()

    {

    /* This program will eventually

    print out squares from 1 to 10 */

    printf("Squares from 1 to 10\n");

    }

    Save again.

    25

  • 8/2/2019 Comp Labnotes

    26/53

    2. Compile and Execute. Save some fingerwork by using the exclamation mark shorthand

    % !gcc

    which will repeat the last command starting gcc. (This works for any command by the

    way: !p repeats the last command line beginning with p, !pa the last beginning with pa,

    and so on.)

    Step C: Observations

    1. Nothing changes in the executable program. All text between /* and */ is ignored by

    the compiler, and has no effect on the code.

    2. Comments can appear anywhere in the source code. One restriction is that you cannot

    nest comments as in /* A comment /* Nested = Bad */ */

    Step D: Declarations of variables and constants

    The program specification calls on us to repeat the square calculation for a set of numbers. To

    set up the loop we need to create some variables to control the repetition (or loop). We shall

    need one for the starting number, one for the end number and one for the number of the current

    number. We shall also need a variable to store the result in.

    In C all variables must be declared at the top of the function in which they are used, before they

    are used. Each variable has an associated type indicating what sort of data it stores (integer, real

    number, character, etc), and a name. A declaration consists of a type followed by the variablename; eg below i and isq are declared as integers. A const int is an integer whose value

    cannot change during program execution.

    [To save space below, some of the comments in the printed code may disappear. Obviously

    there is no need for you to delete them.]

    1. Edit. Go back to the editor and add/alter:

    #include

    int main(){ /* This program will eventually

    print out squares from 1 to 10 */

    int i,isq;

    const int lolimit=1, hilimit=10;

    printf("Squares from %d to %d\n",lolimit,hilimit);

    }

    Remember to save.

    26

  • 8/2/2019 Comp Labnotes

    27/53

    2. Recompile using !gcc

    3. Execute.

    Step D: Observations

    1. The first set of statements in a routine are the declarations, as mentioned earlier. They

    always come at the top of the routine, and the declared identifiers are valid only within

    the routine itself.

    2. The output is achieved using printf(). On execution, the format code %d is replaced

    with the corresponding integer value.

    Step E: Finishing off with a loop

    We now need statements to achieve the repetition from lolimit to hilimit. We achieve that here

    using a while loop (see observations below).

    1. Edit. Go back to the editor and add

    #include

    int main()

    {

    int i,isq;

    const int lolimit=1, hilimit=10;

    printf("Squares from %d to %d\n",lolimit,hilimit);

    i=lolimit;

    while (i

  • 8/2/2019 Comp Labnotes

    28/53

    2. The while (condition)

    statements ...

    tests that the condition is TRUE

    before entering the body of the loop to execute the statements. When the condition be-

    comes false, execution jumps to the first statement after the loops body.

    3. C does not define an operator to the power of. To obtain write in C

    4. Notice the statement i=i+1; What would happen if this had been omitted? Discuss with

    a demonstrator.

    2.4 Review

    Now go back and look at the specification in section 2.1. Match up each part of the specifi-

    cation with the C-code in your program.

    2.5 Laying out your code

    There are few restrictions on layout in C. Each compiler directive has to be on a separate line,

    and care must be taken splitting strings, but apart from that anything goes. As the mess be-

    low illustrates ugly programs are hard to understand and debug, and are thus bad engineering

    practice.

    #include

    int main(){ int i,isq; const int lolimit=1, hilimit

    =10;printf("Squares from %d to %d\n",lolimit, hilimit)

    ;i=lolimit; while

    (i

  • 8/2/2019 Comp Labnotes

    29/53

    Once the program is working properly, print it on the default printer (see Section 1.9) and attach

    to your log-book.

    Some observations

    1. If there were language errors in your program, the compiler prints error messages to help

    you find the mistakes. Use the editor to correct them, save the editted file, and recompile.

    2. It is important to realize that if the compiler fails, no new executable file is written.

    So if you had a working version of cubes, then altered sqcubes.c but introduced an error,

    and tried to compile, the old version of sqcubes would not be overwritten. So, sqcubes

    might appear to run, but it would be the old not new version.

    2.7 Writing and Calling Subroutines

    Your solution to the exercise probably involved writing something like

    int icubed;

    ...

    icubed = isq*i;

    Now suppose you had been asked to evaluate many more powers within the program. It would

    be tedious and error-prone to write the expressions out explicitly. Instead you might wish to

    write a routine which can compute the result of raising a number to the power of another number.

    If we restrict our attention to integers and positive powers, then a pseudo-code spec for such a

    routine might look like:

    1. BEGIN ROUTINE X TO THE POWER N

    2. INITIALISE RESULT TO 1

    3. REPEAT N TI MES:

    4. RESULT = RESULT*X

    5. RETURN RES ULT

    A C function is described by (i) a return type; (ii) a name; (iii) a list of parameters and their

    types. The specification above is implemented in C as set out below. Make sure you understand

    how the C maps onto the spec, discuss any questions you have with a demonstrator, and follow

    the steps below:.

    1. Edit your program by adding a function. Save the program as powers.c

    #include

    int power(int number, int pow)

    29

  • 8/2/2019 Comp Labnotes

    30/53

    {

    /* This routine returns an integer value

    * equal to number raised to the pow.

    * Pow can be zero or positive.

    */

    int pwr,i;

    pwr=1;

    i=pow;

    while(i>0) {

    pwr = pwr * number;

    i = i-1;

    }

    return(pwr);

    }

    int main()

    {

    int i,i2,i4,i6,i8;

    const int lolimit=1, hilimit=10;

    printf("No Pow2 Pow4 Pow6 Pow8\n");

    i=lolimit;

    while (i

  • 8/2/2019 Comp Labnotes

    31/53

    3. We slightly altered the printf() format string: %4d supplies an output field with a

    fixed width of 4 places.

    2.8 Variables Types in C: int, float and so on

    There are several basic types

    int, which can represent integers from ! to # ! & .

    float for floating point numbers (i.e. real numbers). The largest float values are

    about () 1 3 5 6 & 3 9

    and the smallest non-zero float is (& 1 3 & E 6 & 3 H P Q

    .

    double provide a floating point nummber with higher precision and range.

    char is used for single characters.

    These types can be modified in several ways, but for now these will suffice. Mathematical

    functions tend to use double precision floating point numbers rather than floats.

    ...

    int main()

    {

    int count;

    float volume;double fred;

    char label;

    ...

    count = -356;

    volume = 2345.456;

    fred = 2.123477834599725;

    label = a;

    /* Notice these are closing-apostrophes

    and not speech marks */

    }

    2.9 Operators

    2.9.1 Standard operators

    + Add (eg c=a+b;)

    - Subtract (eg c=a-b;)

    * Multiply (eg c=a*b;)

    / Divide (eg c=a/b;)

    31

  • 8/2/2019 Comp Labnotes

    32/53

    A common error is to forget the multiply sign

    c=2(a+b); /* WRONG */c=2*(a+b); /* RIGHT */

    2.9.2 Operator precedence

    There are strict rules for operator precendence. Expressions in brackets are worked on first.

    Multiplies and divides are done before adds and subtracts. A succession of multiplies and

    divides or adds and subtracts is worked on left to right. So, for example, suppose a=12 and

    b=4 and c=2, then

    d=a/b+2; /* this is (a/b) + 2, => d = 5 */d=a/(b+2); /* and not this! => d = 2 */

    d=a/b*c; /* is (a/b) * c => d = 8 */

    d=a/(b*c); /* and not this => d = 1.5 */

    d=a/b/c; /* is (a/b)/c => d = 1.5 */

    It is always sensible to use brackets to make your meaning clear to you, others, and the compiler.

    2.9.3 Some shorthand operators

    j+=2; add 2 to j Same as j=j+2;

    j-=2; take 2 from j Same as j=j-2;

    j*=2; double j same as j=j*2;

    j/=2; halve j same as j=j/2;

    2.10 Conditionals

    2.10.1 Numerical Conditionals

    The while loop you included in your code was controlled by testing a condition. Conditionals

    are either numerically based or logically based. A list of numerical conditionals is:

    Operator Example Result

    < (a < b) True if a less than b

    b) True if a greater than b

    >= (a >=b) True if a greater than or equal to b

    == (a ==b) True if a equal to b

    != (a !=b) True if a not equal to b

    32

  • 8/2/2019 Comp Labnotes

    33/53

    Note that the equality is tested with ==, NOT, = which is the assigment operator. This is a

    common programming error.

    2.10.2 Conditional if statements

    Conditionals are also used in the very frequently used if statement, which executes the state-

    ments in the block where the respective condition is TRUE.

    There are three flavours of if:

    Using plain if

    if ( Condition ) {

    ... statements A ...}

    ie, statements A executed if Condition is True.

    Using if ... else

    if ( Condition ) {

    ... statements A ...

    }

    else {

    ... statements B ...}

    ie, statements A executed if Condition is True and statements B executed if Condition is False.

    Using if ... elseif ... else

    if ( Condition1) {

    ... statements A ...

    }

    else if ( Condition2) {

    ... statements B ...}

    else {

    ... statements Z ...

    }

    Here is an example of an if ... else if ... else statement

    if( i

  • 8/2/2019 Comp Labnotes

    34/53

    }

    else if ( i>0) {

    printf("i is positive!\n");

    }

    else if (j>0) {

    printf("i is zero and j is positive\n");

    }

    else {

    printf("i is zero and j is zero or negative\n");

    }

    2.11 EXERCISE 2B

    Recall the program powers.c which used a routine to compute the value of integer raised to

    an integer power. The integer power had to be greater or equal to zero. Your task now is to

    modify the routine to allow in addition raising to negative integer power.

    There are many ways of achieving this. It is worth thinking first about some common aspects

    to any solution.

    1. The routine power() will have to check for a negative argument. This requires the use

    of an if statement.

    2. Because an integer raised to a negative number is a floating point number, the result willnow have to be a double rather than an int. This will have repercussions in the main

    routine too (see below).

    3. Usually, the less clever you make the code, the easier it is to write and debug, and the

    easier it is to understand at a later date.

    A partial solution has been supplied to you, and is listed later. Note the following about the new

    code:

    the return type of power has changed to double

    the local variable used to accumulate the result is now type double

    the values into which the result is stored in the main routine are now also doubles.

    the printf statement now has the code %lf meaning long float or double.

    Now:

    1. % cd /exercise2

    and then check that file npowers.c exists.

    34

  • 8/2/2019 Comp Labnotes

    35/53

    2. Load npowers.c into the text editor. You will see that the main routine is complete, but

    the subroutine is not.

    3. Sort out the four FIXMEs in the code. Save the program, compile and link. If unsuc-cessful, reedit until it executes properly. If you feel you are making no progress, consult

    a demonstrator sooner rather than later.

    4. Finally, print out the program npowers, attach to your log-book and show to a demonstra-

    tor.

    /* LISTING of npowers.c */

    #include

    double power(int number, int pow){

    int i;

    double result;

    result=1.0;

    i=pow;

    if (FIXME) { /* This should deal with negative pow */

    while (i < 0) {

    result = FIXME ;

    i= FIXME ;}

    } else {

    while (i > 0) { /* This should deal with positive or 0 pow */

    result = result * (double)number;

    i = FIXME ;

    }

    return(result);

    }

    int main()

    {

    /* we will work out i(-2,-1,0,1,2) */

    int i;

    const int limit=11;

    double im2,im1,iz,ip1,ip2;

    i=1;

    while(i < limit) {

    im2 = power(i,-2);

    im1 = power(i,-1);

    iz = power(i,0);

    35

  • 8/2/2019 Comp Labnotes

    36/53

    ip1 = power(i,1);

    ip2 = power(i,2);

    printf("%lf %lf %lf %lf %lf\n",im2,im1,iz,ip1,ip2);

    i = i+1;

    }

    }

    Logging out

    As ever, remember log yourself out.

    2.12 Summary

    In this session we have seen the following basic programming constructions in C:

    Assigments, eg result=1.0 + a;

    Loops, eg while (i

  • 8/2/2019 Comp Labnotes

    37/53

    3 An Engineering Application of C

    The first aim of this session is to give you further experience of the C programming language.You will start by trying out a number of short programs which illustrate various constructs.

    Later in the lab we develop a program to analyse a simple mechanical system; this should help

    remind you that programming for engineers is usually not an end in itself, but is a means to

    understanding systems.

    Summary of what you have to do this session

    Preparation Spend 10-15 minutes before the lab making sure

    you have read through the lab notes and understand

    what you will be doing

    Various C programs Spend about 50 minutes on this

    including EXERCISES 3A,B

    EXERCISE 3C Spend about 60 minutes

    3.1 Preparation

    In the second half of the lab you are going to complete a program that models one aspect of

    resonance in a second-order system. The example we will use is a spring-damper mechanism,

    but your ODE lectures later this term will show you that many engineered systems can be

    modelled in this way.

    3.1.1 Understanding the model

    Figure 6 below shows a cars suspension system and comprises a wheel of mass R with a spring

    of stiffness S and a damper with viscous constant T . An oscillatory force U V W Y is applied with

    a certain fixed amplitude ` but at different frequencies a . You want to work out the amplitude

    of the resulting oscillations and to plot b , the ratio of amplitudes, as a function of frequency.

    An expression for the ratio b is worked out below. It is not too complicated, but if you are very

    pushed for time, merely skim over the detailed explanation for now, and look at the result given

    in the red box later.

    A force force U V W Y is applied, so Newtons 2nd Law tells us that the equation of motion is

    Re

    gh

    UV W Y S

    g

    T q

    g or Re

    g

    #T q

    g

    #S

    gh

    UV W Y

    By dividing by R we have

    e

    g

    #

    T

    R

    q

    g

    #

    S

    R

    gh

    &

    R

    UV W Y

    37

  • 8/2/2019 Comp Labnotes

    38/53

    y(t)

    f(t)

    m

    vyky

    Figure 6: Spring-damper model. The equilbrium position is att

    u w

    , so the force of gravity is cancelled

    out. An external force y

    is applied to the mass .

    Let us suppose for a moment that we remove the damper, and removed the applied force. The

    system then would undergo simple harmonic motion with its natural frequency of

    a

    h

    S

    R

    It is also convenient to represent the strength of damping by a damping factor (zeta), so that

    T

    R

    h

    a

    Putting these quantities back into the equation, and applying a sinusoidal forcing function at

    frequency a (yes, a , NOT the natural frequency) we describe the system by

    e

    g

    # a q

    g

    #a

    gh

    ` a W

    What we are interested in here is the amplitude of the resulting oscillations in g . These oscil-

    lations must have frequency a (yes, again, a ) so we could try a solution

    gh

    a W # a W

    If you use this in the equation, and then equate coefficients of and , you will find and

    in terms of ` . The ratio we want to examine is the relative amplitude

    b

    h

    #

    `

    However, the fastest track to the solution is to note that the RHS is Im V` j k l n Y

    , so that the

    solution must be of the form

    gh Im V j k l n Y

    38

  • 8/2/2019 Comp Labnotes

    39/53

    where is complex.

    But this means that j kl n

    is a solution. Putting g h Im V j kl n

    Y into the equation and cancelling

    the j k l n we have

    a

    # a V a Y # a

    h

    `

    But we are looking for the ratio

    b

    h

    `

    h

    &

    Va

    a

    Y

    a a

    h

    &

    Va

    a

    Y

    #V a a Y

    So to summarize...

    b is a function of three variables: the damping factor, the frequency of the forcing function, and

    the natural frequency

    b

    h

    &

    Va

    a

    Y

    #V a a Y

    Of course, for a system with fixed mass and stiffness, a is fixed.

    3.2 Getting Started

    After logging in and starting a terminal window, type

    % /ecslab/demo/yr1/script3

    % cd /session3

    In Session 2, we saw four key programming constructs assignments, loops, conditionals, and

    subroutines as they appear in C. To revise these we will look at a small program which uses

    all of those elements.

    In your session3 directory there should be a file called c2f.c. Open it in the editor of your

    choice (xemacs is recommended) and study the code.

    What does it do?

    1. Study the code and determine (i) how it works (ie what the major components are) and

    (ii) what its purpose is

    39

  • 8/2/2019 Comp Labnotes

    40/53

    2. Then compile (and re-edit if necessary) and run

    % gcc c2f.c -o c2f

    % c2f

    3.3 Writing to/reading from the standard output/input

    We have now seen a few examples of the use of printf(). It has a format string followed

    by a list of the variables you wish to print. The codes used in the format statement are most

    commonly:

    %d for an integer

    %Nd for an integer in a fixed-width field N digits wide.

    %f for a float%N.Mf for a float in a field N places wide (including the point)

    with M digits behind the decimal point.

    %lf for a double (NB this is ell eff)

    %N.Mlf for a double in a field N places wide (including the point)

    with M digits behind the decimal point.

    %c for a char (character, see below)

    %s for a string of chars

    %Ns for a string of chars with fixed-width N

    In addition there are special codes: most commonly used are

    n insert a newline (look at c2f.c)

    t insert a tab

    Look at the code ofc2f.c and the output from the program. Make sure you understand why

    the output is formatted the way it is.

    3.4 Reading from the standard input

    The system function printf puts output onto the default output device or file, usually the

    current terminal window (though recall from Session 1 that you can redirect this output to a

    disk file, for example). Its counterpart for getting input (usually from the keyboard, but again,

    this can come from a file using redirection) is the system function scanf. Like printf,

    scanf takes a format string as its first argument, and the arguments which follow are the

    variables whose values are to be read from the keyboard, in this case, just the one, i.

    The same format codes are used, but without numerical modifiers. An example would be

    int i;

    float f;

    double a;

    40

  • 8/2/2019 Comp Labnotes

    41/53

    value of x is 10

    value of y is 1755

    address of x is 1000

    address of y is 1001

    x equals 10

    &x equals 1000

    &y equals 1001

    y equals 1755

    10

    1755

    MEMORY

    x

    y

    0

    21

    1000

    1001

    Figure 7: A memory map of a computer showing the locations and values of variables x and y. A

    typical modern computer has 256Mb, or approx 260 million memory locations

    char q;

    scanf("%d %f %lf %c",&i,&f,&a,&q);

    printf("i=%d, f=%f, a=%lf, q=%c\n", i, f, a, q);

    There is one significant difference which you will almost certainly be puzzling about: why does

    the i have a & in front of it for scanf? The explanation has to do with how variables arestored in the computers memory, and how their values are passed to functions (i.e. the function

    arguments).

    Figure 7 shows a schematic of a computers memory. Each variable of a running program has

    two properties of interest: (i) its value, which probably changes over the course of the program

    (ii) its location, which is fixed for the lifetime of the variable. The location of a variable (or

    address of a variable can be determined using the & operator, as in &x (read this as the address

    ofx).

    As far as most functions are concerned, it is only the value that is of any consequence (consider

    sin(x): the function sin does not need to know where x is stored, just its value. However ifthe function needs to change the parameter, then its location is needed. The scanf function,

    of course does need to change the variable. In C the only method for doing so is explicitly to

    pass the address of the variable, not the value; scanf then knows where to store the value that

    you type in. Other languages support more elegant ways of doing this, but for the time being

    we are stuck with C .

    This is a slightly tricky point, and a demonstrator will be glad to explain it to you!

    41

  • 8/2/2019 Comp Labnotes

    42/53

    3.5 EXERCISE 3A

    1. Modify thec2f.c

    program toscanf()

    the variablemaxtemp

    :

    #include

    ... as earlier ...

    int main()

    {

    float c,f;

    float maxtemp;

    printf("Supply maxtemp :");

    scanf( FIXME -- Get help if you are stuck! );

    printf("Cent Fahr\n");

    c=0.0;

    while(c < maxtemp) {

    ... as earlier ...

    }

    }

    Compile and execute.

    2. Now further modify the c2f program to scanf not only maxtemp but also steptemp,

    and increment c by steptemp rather than by 1.0.

    3.6 Loops

    The c2f program uses a while loop.

    A commonly used alternative is the for loop. It can be used to incorporate the initial conditions

    and the update rule, and so lends clarity to code. For example:

    #include

    int main()

    {

    float c,f;

    const float maxtemp=31.0;

    printf("Cent Fahr\n");

    for(c=0.0; c < maxtemp; c=c+1.0) {

    42

  • 8/2/2019 Comp Labnotes

    43/53

    f = fahr(c);

    printf("%4.1f %4.1f\n",c,f);

    }

    }

    This means, at the start of the loop, initialise c=0; keep looping while c=b True if a greater than or equal to b

    == a==b True if a equal to b

    != a!=b True if a not equal to b

    && c1 && c2 True if c1 and c2 are True

    || c1 || c2 True if c1 or c2 is True

    ! !c True if c is False.

    For example, if you worked NEITHER on wet Tuesdays when it was warmer than 20 degrees

    NOR on non-wet Fridays we might generate and test the condition:

    Cond = ( day==Tuesday && weather==wet && temp>20) ||

    ( day==Friday && weather!=wet);

    if (Cond) {

    work=0;

    }

    Notice particularly the use of double equals == to test for equality. A common error, which is

    hard to find, is to use only =.

    43

  • 8/2/2019 Comp Labnotes

    44/53

    3.9 EXERCISE 3C: modelling resonance

    The overall aimThe aim of this exercise is to reinforce the message that programming is not an end in itself, but

    is a means to understanding engineering systems.

    You are going to complete a program that models one aspect of resonance in a second-order

    system. The example we will use is a spring-damper mechanism, but your ODE lectures later

    this term will show you that many engineered systems can be modelled in this way.

    To get started

    % cd /exercise3

    Briefly re-read section 3.1 and note that even if you dont understand the maths, what you

    ultimately need to do is to program the function to compute b as a function ofa , a and .

    3.9.1 Programming the R function

    1. You should find resonance.c in your exercise3 directory. Load resonance.c into an editor.

    The program is complete except for the lines missing in the ratio R() function.

    #include

    #include #include

    double R(double zeta,double w,double wn)

    {

    /* Function R() will work out amplitude ratio */

    double result;

    result = 999; /*

  • 8/2/2019 Comp Labnotes

    45/53

    * times round loop

    */

    wmax = 2.0*wn;

    wstep = wmax/100.0;

    for(w=0; w out

    10 0.5

    % more out

    4. Now type in some lines to express the R function. Dont try to type a single big expres-

    sion. Build it up instead. For example, it might be useful to declare and use a variable

    double wsquared;

    ...

    wsquared = w*w;

    5. After saving your file recompile and link, and correcting any errors. If you become

    baffled by a recurring error, ask a Demonstrator for help.

    6. Now run the program and look over the output does it look reasonable?

    % resonance > out

    10 .5

    % more out

    45

  • 8/2/2019 Comp Labnotes

    46/53

    If so, try plotting the output

    % gnuplot

    Then after the gnuplot prompt, type

    % plot "out"

    3.9.2 Generate a set of results for different damping

    1. Now you are ready to generate a set of results for different damping factors.

    Type the following

    % makeresults

    Makeresults is a script which runs the resonance program 6 times with increasing damp-

    ing of 0.1, 0.2, 0.4, 0.8, 1, and 2, and stores the output in files out.1, out.2, out.4, out.8,

    out1, and out2.

    2. Type the following

    % gnuplot

    Then after the gnuplot prompt, type

    gnuplot} load "screen.gnu"

    The file screen.gnu contains instructions to plot all your graphs out.1, out.2, out.4, out.8,

    out1, and out2.

    You can make a printable version by typing

    gnuplot} load "print.gnu"

    This creates a file called out.ps which can be printed using

    % lp out.ps

    3. Show a Demonstrator and get signed off.

    3.10 Summary

    You should have certainly become more confident about C programming in this session.

    But another point that should have come over is that it does not take that much effort to create

    a program to explore the performance of a simple physical system.

    Youll find similar plots in HLT, but yourplotting the graphs as you changed the damping factor

    is much more instructive.

    46

  • 8/2/2019 Comp Labnotes

    47/53

    4 Flying solo (ish...)

    Up to now you have encountered and used most of the basic constructs in C, all of whichare examples of more general programming concepts available in most/all languages: simple

    input/output, mathematical formulae, conditions, loops, function/procedures, and variables.

    The aim of the last two sessions is to put all of these ideas in to practice to develop a (simple)

    image processing application.

    Before that, we introduce the idea of an array of data.

    Summary of what you have to do

    Preparation Spend 5 minutes before the lab reading

    through and making sure you understand whatyoure doing

    Arrays spend about 30 minutes on this

    EXERCISE 4 use the remaining time (150 minutes)

    to work through the various stages of the exercise

    to create a simple image processing program

    4.1 Getting Started

    After logging on, type

    % /ecslab/demo/yr1/script4

    % cd session4

    4.2 Arrays

    Frequently it is necessary/convenient to read, manipulate and store collections of similar data,

    such as a set of numbered parameters

    ~ ~

    !

    ~

    . Most languages provide a compound

    data structure known as an array to serve this purpose. In C an array of data is declared byspecifying the number of data elements in square brackets after the variable name. For example,

    int day[7]; /* an array of 7 integers */

    float x[10]; /* an array of 10 floats */

    char alphabet[26]; /* an array of 26 characters */

    declares an integer array day of length 7, and so on.

    Note that in C (in constrast to some other languages, notably matlab) that the index always runs

    from 0 to (n-1) inclusive, and NOT 1 to n. So in our example, day[0] to day[6] are legal uses,

    47

  • 8/2/2019 Comp Labnotes

    48/53

    but day[7] is not. Often the sizes of several arrays are the same, for example, when dealing with

    x,y points on a graph. It is then convenient to define a size. For example,

    #include

    #define MAXPOINTS 100

    int main()

    {

    float x[MAXPOINTS], /* elements [0] to [MAXPOINTS-1] */

    y[MAXPOINTS];

    ...

    Now if you need to handle more points, you need only change the definition of MAXPOINTS,

    and not search through all your code for specific numbers. Also note that this size must be a

    constant: the following attempt to declare msg to be of size specified by n is not legal:

    ...

    int n = 5;

    char msg[n];

    }

    Arrays very often appear inside loops, indeed whenever you want to perform the same operation

    on every element of the array:

    #include

    #define MAXPOINTS 100

    int main()

    {

    int i;

    double x[MAXPOINTS], /* elements [0] to [MAXPOINTS-1] */

    y[MAXPOINTS],

    modsq[MAXPOINTS];

    ... etc ...

    for(i=0; i < MAXPOINTS; i++) {

    modsq[i] = x[i]*x[i] + y[i]*y[i] ;

    }

    }

    1. Compile, link and run the program arrays.c which you will find already in the ses-

    sion4directory.

    48

  • 8/2/2019 Comp Labnotes

    49/53

    2. Determine what it does, and how, and ensure it makes sense by discussing any questions

    with a demonstrator.

    4.3 Multidimensional arrays

    A double-indexed array is a very useful structure for storing data such as matrices and images.

    It is declared, for example as below:

    double x[5][10];

    x[0][0] = 4.0;

    x[4][9] = 3.0;x[5][8] = 3.2; /* Error! WHY? */

    Double-indexed arrays often appear inside nested loops. An example appears in the code ma-

    trix.c:

    1. Compile, link and run the program matrix.c which you will also find already in the

    session4 directory.

    2. Verify that it computes h where is a 3x3 matrix and is a 3-vector. Ensure all of

    the steps make sense to you and discuss any questions with a demonstrator.

    3. Modify the program so that it computes instead h (i.e. the transpose of times )

    4.4 EXERCISE 4

    To complete this session and the next(if you need it) you are asked to create a program to read

    in an image, to threshold the image into a binary one showing foreground and background, and

    to write it out again.

    Here is some pseudo-code that describes the program:

    0. BEGIN

    1. PROMPT USER FOR IMAGE FILE NAME

    2. READ IMAGE DATA FROM FILE

    3. PROMPT USER FOR THRESHOLD

    4. FOR EACH PIXEL IN THE IMAGE:

    5. SET TO 255 IF ABOVE THRESHOLD, 0 OTHERWISE

    6. PROMPT USER FOR SAVE IMAGE FILE NAME

    7. WRITE OUTPUT IMAGE

    8. EN D

    49

  • 8/2/2019 Comp Labnotes

    50/53

    To start the exercise, change directory into /exercise4 which was created for you when

    you ran script4 earlier.

    You will find the shell of the program in threshold.c in your exercise4 directory(printed below for your convenience). Your task is to fill in the missing bits of code after

    each comment, and then compile and run it successfully.

    Note how the comments mirror the pseudo code. This defines the sequence of actions the

    computer will take. However this order is not necessarily the best order in which to code. I

    suggest you tackle it in the following stages, building up the program by getting small sections

    to work first before making further additions (as we did in session 2):

    Step A Prompt the user for a filename

    You will need a printf call to print out a message to the user (see various examples in

    sessions 2-4), and a scanf call:

    scanf("%s", filename);

    Note the use of"%s", the string format code, and the fact that in C, a string is defined

    as an array of char (see the declaration of the variable filename at the top of the

    program).

    Add some code which prints out the filename you have just read:

    printf("Image filename is %s", filename);

    so that you can verify that your scanf did what it was supposed to.

    Now compile

    % gcc threshold.c -o threshold

    and execute to check the first stage works.

    Step B Prompt the user for an output filename

    You can insert very similar code at stage 6 to prompt the user for an output filename. Youhave a choice here: (i) you can either declare a new variable, e.g.

    char outfilename[256];

    remembering that the declaration must appear at the start of the main funtion (next to the

    other one), or (ii) reuse the variable filename, which by this stage is no longer needed.

    Best practice is (i).

    Compile and execute to check the second stage works. Your output should look some-

    thing like the following:

    50

  • 8/2/2019 Comp Labnotes

    51/53

    % threshold

    Enter input filename: myfile.pgm

    Image filename is myfile.pgm

    Enter output filename: myfileout.pgm

    Output image filename is myfileout.pgm

    %

    Step C Read the input image

    Load the file image.c into an editor and have a look at the functions imageread and

    imagewrite. Now look at the file image.h. Notice that while the .c file contains

    code which implements each function, the .h file contains simply the function proto-

    types, i.e. the function name, parameters, and return type.Now edit the file threshold.c to add a call to the function imageread (obviously

    this should afterthe user has been prompted for a filename, so just after the comment for

    stage 2 would be best):

    imageread(filename, image, &width, &height);

    Note that the integers width and height are changed by the function, so we pass in

    their addresses (see session 3, p41).

    Try to compile the code:

    % gcc threshold.c -o threshold

    I expect you get an error such as undefined symbol imageread or such-like. The rea-

    son is that although the compiler knows about the definition ofimageread from the

    file image.h which is included by threshold.c (see compiler directive #include

    "image.h" at the top of the code), there is no code that actually implements its opera-

    tions.

    This is easily rectified. Simply compile instead with the command:

    % gcc threshold.c image.c -o threshold

    The effect of this command is to compile your code, threshold.c andimage.c, thecode which implements imageread and imagewrite, and to link these together into

    one executable: threshold.

    This time it should compile without errors.

    You will also find an image in your exercise4 directory. You can view it using the

    image viewer xv:

    % xv tools.pgm

    51

  • 8/2/2019 Comp Labnotes

    52/53

    To check that your program (so far) works, I suggest you add a line after the imageread

    that prints out the values of width and height. Remember to recompile and then

    execute. When prompted, enter

    tools.pgmas the image, and your program shouldreport that the image is 250 columns wide by 190 rows high.

    Step D Write the output image

    Writing the output image is achieved simply by adding the line:

    imagewrite(outfilename, image, width, height);

    Note that for the image write, the variables width and height do not change value,

    and so it is their values, not their addresses that are passed in to the function.

    Again, compile and execute to test your program.

    To summarise the current state: your program should prompt for an input file and read it,

    then prompt for an output file, and write to it. At present the image is not changed at all,

    so you have effectively written an image copying program!

    You can test that it does what we expect by trying to view the output image using xv.

    Step E Threshold the image

    The final step involves actually changing the image pixels so that those less than the

    threshold are set equal to 0 (black), and the remainder to 255 (white).

    To access each pixel in turn you will need a nested loop, of the form:

    for (i=0; i

  • 8/2/2019 Comp Labnotes

    53/53

    Consult a demonstrator sooner, rather than later, if you get stuck.

    Once you have a working program, determine (by trial and error) a suitable threshold for the

    tools.pgm image that divides the image into foreground and background, and record thisvalue in your log.

    When youhave completed the exercise, print out your code, as usual get signed off by a demon-

    strator, and of course log out.

    Ensure that you have a record of attendance and completion on your lab sheet, and that

    the official register also shows completion it will save you the hassle of having to come

    back at a later date to prove it.

    Congratulations, you have now completed the Introduction to Computing Exercises.