% swe1labs.tex
%
% Lab Notes for Software Engineering 1.
%
% This is prepared as a LaTeX file, but is actually intended to
% be processed into HTML, using latex2html, for access via WWW.
%
% Barry McMullin.

\documentstyle[epsf,html,12pt,a4]{article}

\newcommand{\bks}{\mbox{$\backslash$}}

\newcommand{\C}{{\bf C}}
\newcommand{\atwork}{\htmladdimg{at_work.gif} (Under Construction...)}
\newcommand{\tty}[1]{{\bf #1}}

\newcommand{\hot}[2]{\htmladdnormallinkfoot{#1}{#2}}

\newcommand{\qt}[1]{{\tt "}#1{\tt "}}
\newcommand{\mdash}{---}

\begin{htmlonly}
\renewcommand{\qt}[1]{"#1"}
\renewcommand{\mdash}{~-~}
\end{htmlonly}

\externallabels{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/swe1root}
{../../swe1root/swe1root/labels.pl}

\begin{document}

\title{Software Engineering 1: Laboratory Exercises}
\author{Barry McMullin}
\date{Last Modified: 30th April 1996}
\maketitle

Note that this complete document is available in
\hot{LaTex}{swe1labs.tex} and plain
\hot{ASCII}{swe1labs.txt} forms, to allow downloading and
offline browsing.

\section{Introduction}

This document is one component of the hypermedia documentation for the
course \hot{Software Engineering 1}
{../swe1root/swe1root.html}. It
presents detailed instructions and background information for the
laboratory sessions.

In general, the notes for particular lab exercises will be added
to this document on an ongoing basis during the academic year,
with each new exercise being made available a few days before
the first section of the class is due to do it.

\section{General Comments on Lab Work}

The CAE laboratory itself should be used both for the scheduled
laboratory exercises, and also for \qt{private study}: the primary
way of studying software engineering is to do it! The laboratory
exercises are crucial to this course: you should learn more from
the time you spend in the laboratory than from lectures and
tutorials combined.

Each student attends one three-hour scheduled lab session every
two weeks.  {\em You should aim to spend at least three
further hours of private study time in the lab over the same
period.}  The scheduled lab sessions are deliberately structured
so that each student has a separate PC; however, for private
study you may find it easier to get at a machine, and also more
effective, to work together with one or two others\mdash provided
that you spend time discussing what is happening, and taking
turns at actually operating the PC.

For the first lab session you are required to bring along a new,
unused, copybook or notebook to be used as your lab logbook.
However, in contrast to most other laboratory subject, this
logbook will {\em not} be used to hold formal lab reports.
Instead, you will maintain the logbook just with your own
personal notes; but these personal notes will serve as the basis
for writing {\em separate\/} formal reports, which will actually
be submitted (and archived) electronically. This 
will be explained in more detail
during the lab sessions.

You should consult the
\hot{Software Engineering~1: Laboratory Report Guidelines}
{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/rptfmt/rptfmt.html}
for advice on how to prepare lab reports, and the criteria which will be
used in marking them.

\section{Session 1: Week 1/2}

This first several lab sessions are concerned simply with introducing 
general purpose
hardware and software tools which will be used in the remainder
of the course.  Given that you are reading these notes, you have
successfully completed the first phase of the exercise!

Stop at this point and read back over what you have written in
your logbook. Make sure you have a reasonably complete record
of what you have done so far (so that, if necessary, you could
redo it without further guidance).

In particular you should have some record of:

\begin{itemize}

\item The \hot{rules}
{http://www.eeng.dcu.ie/eenghome/cae\_rule/cae\_rule.html} 
and \hot{timetable}
{http://www.eeng.dcu.ie/eenghome/cae\_time/cae\_time.html} 
applying to users of the 
CAE laboratory.

\item The component physical parts of the PCs\mdash their names and
functions.

\item The procedure for \qt{booting up} a PC.  In particular you should have
carefully read the \hot{notice}
{http://www.eeng.dcu.ie/eenghome/aup.txt} 
regarding acceptable use
of the School's computer facilities.

\item How to {\em format} a new diskette from the MS-DOS
command level.

\item How to {\em check} the integrity of a diskette from the
MS-DOS command level.

\item How to initialise a diskette as a \tty{Netscape
Configuration diskette} from the MS-DOS command level.

\item How to start up the \tty{MS-Windows} environment.

\item How to use the \tty{MS-Windows} online \tty{Help}
facility, including searching and using hypertext links.

\item How to start up the \tty{MS-Windows} introductory
tutorial.  How to move, minimize, maximize, and otherwise resize
windows.  How to launch applications.

\item How to start \tty{Netscape}, and use
hypermedia links. How does navigating with \tty{Netscape} differ
from using \tty{MS-Windows Help}?

\end{itemize}

If your logbook fails to mention any of these things, take time 
now to make some additional notes.

At this stage you have created and are using
a {\em Netscape Configuration Diskette}. 
You should always insert this diskette {\em before} starting up a
\tty{Netscape} session.  {\em IMPORTANT: Do not remove it again until your
\tty{Netscape} session is over, and the diskette light has gone
off.}  This configuration diskette will hold personal
information about your use of \tty{Netscape}.  For example, you
can record a \qt{bookmark} file, identifying nodes that you have
visited, making it easy to revisit them.

For now, we want to configure Netscape to know your name and
email address\mdash so that, if you originate email from within
\tty{Netscape}, you will automatically be identified as the
author.\footnote{You will not be able to {\em receive} email for
the time being.  That will be dealt with in subsequent lab
sessions.} Follow these steps, within \tty{Netscape}:

\begin{itemize}

\item Drop down the
\tty{Options} menu.

\item Select \tty{Preferences}.

\item Select the
\tty{Mail and News} \qt{tab}.

\item Fill in the fields labelled \tty{Your
Name} and \tty{Your Email}.  Your email address will be something
like \tty{astudent@ugmail.eeng.dcu.ie}, but instead of
\tty{astudent} you have a username consisting of your first
initial followed by your surname, up to a maximum of 8
characters in total.  Do not use any spaces or punctuation, and
keep it all in lower case.

\item Select \tty{OK}.

\end{itemize}

Now, find out (using \tty{Netscape}) as much as you can about
the {\em Electronic Mailing List} facility operated by the School of
Electronic Engineering. In particular, read the information about the 
\hot{SOFTENG1-95}
{http://www.eeng.dcu.ie/\%7Emajordom/softeng1-95.info.html}
list.  Check out the \hot{archives}
{http://www.eeng.dcu.ie/\%7Emajordom/hm\_archives}.  

Finally: compose a short message (one
paragraph) which summarises your opinion of this course
({\em Software Engineering 1}) so far.  Mail this message to
\qt{\hot{SOFTENG1-95@mjmail.eeng.dcu.ie}
{mailto:softeng1-95@mjmail.eeng.dcu.ie}}.\footnote{If
you enter this address manually, omit the quotation marks.
But, in this particular case, you can just click on
the address and {\bf Netscape} should bring up a mail
composition window, already addressed to the correct address, and with
your name and return address automatically recorded.} 

Check the
\hot{archives}
{http://www.eeng.dcu.ie/\%7Emajordom/hm\_archives}
again to see that your message has been archived
successfully.
Note that, due
to a defect in {\bf Netscape} you may have to \qt{clear the caches},
before your message will become visible in the index.  To do this, drop down
the {\bf Options} menu, and select {\bf Preferences} again.
Select the {\bf Cache and Network} tab.  Click on {\bf Clear
Memory Cache Now}.  You will be asked to verify this\mdash click on
{\bf OK}. Similarly, clear the disk cache. Click on {\bf OK}
again to exit the {\bf Preferences} dialog.  The archive index
will be automatically reloaded and is now guaranteed to be up to
date.  If your message is {\em still} not showing up, then something
has gone wrong.

If your message {\em is} now visible\mdash congratulations:
you have successfully
completed the first lab exercise!\footnote{And your 
message is now\mdash immediately -
 accessible to the entire world wide Internet
 community!}  

\section{Session 2: Week 3/4/5}

\subsection{Background}

This session introduces the tools you need to create and
manipulate {\em text} files on the PC.  Text files are just
textual documents.  You might compose a letter or message
and save it on diskette in a text file.  Subsequently you
might edit it to correct mistakes or add more information.
You might copy it from one diskette to another for backup
purposes (in case one diskette gets damaged or lost).  You might
print it out or email it.  You might delete it off your
diskette when you no longer have any use for it.

We will be dealing with very basic so-called \tty{ASCII}
text documents.  ASCII (American Standard Code for Information
Interchange) is a standardised way of expressing text in
electronic (binary) form.  It essentially specifies a way of
encoding each possible character as an 8-digit binary number, or
byte.  ASCII supports the lower and upper case alphabetic
characters (\tty{a} to \tty{z} and \tty{A} to \tty{Z}),
the digit characters \tty{0} to \tty{9}, a variety of punctuation
characters such as \tty{; : . ? ( ) [ ] } etc., and finally a collection
of \qt{special} characters such as \tty{+ \& * \%} etc.

ASCII provides roughly the same capability for representing text
as used to be available with an old fashioned typewriter.
ASCII does {\em not} support more advanced or complicated kinds
of text such as accented characters, mathematical symbols,
underlining, bolding, varying sized characters, etc.
As such, ASCII might be regarded as pretty \qt{primitive}.

The great advantage of ASCII is that it really {\em is} a
standard.  ASCII encoded text files can be read and printed 
on virtually any computer system, and can be successfully
transmitted through any email system.  ASCII is a sort of
\qt{Lowest Common Denominator} of text file formats.

We will use ASCII files in this course for preparing lab
reports, and for preparing program files (in the \C\ programming
language).  \C\ programs will,
in effect, {\em be} ASCII files, and will be manipulated with
the same tools as we manipulate any other ASCII files.

\subsection{Managing Text: Using \tty{PFE}}

We will create and manipulate text files using an application
called the \tty{Programmer's File Editor} or \tty{PFE} for
short.  \tty{PFE} will allow you to enter text for a new file, save
it on your diskette, edit it again, save it again, print it,
and so on.

You will find \tty{PFE} in the \tty{Tools} group in \tty{Program
Manager}.  Start it up now.  Once it is started up, you might
want to move and resize both its window and the \tty{Netscape} window so
that they do not overlap too much, and you can see both easily.

Explore and experiment with the use of \tty{PFE} for a while. 
Have a look at the various menus. Read through the online help.
Try out the buttons on the button bar to see what (if any)
effect they have.

Now carry out the following exercise:

\begin{itemize}

\item Create a new text editing window.\footnote{Select \tty{New} on the
  \tty{File} menu.}

\item Type up a couple of paragraphs of text on {\em any} subject of
your choice.  

\item {\em Save} the file on your diskette, under the
name \tty{TESTING.TXT}.\footnote{Select \tty{Save} on the
\tty{File} menu.  This will bring up a file selection dialog. On
this you need to specify a disk drive\mdash \tty{A:} for the
diskette\mdash and the file name.} 

\item Exit from \tty{PFE}.

\item Start up \tty{PFE} afresh. 

\item Create a text editing window for the file
\tty{TESTING.TXT}.\footnote{Select \tty{Open} on the \tty{File}
menu.  This will bring up a file selection dialog again.}

\item Make some modifications to the file.  In particular, insert a
line at the top with your own name, and today's date.\footnote{This will
serve to identify your particular file when you come to print it out in
the next step.}
Save the file again.

Note carefully that, while you are editing
the file within \tty{PFE}, this is only changing a \qt{copy} of the file
loaded into \qt{main} memory.  This is a kind of semiconductor memory, which is
completely {\em volatile}\mdash the information will be lost is there is a
power failure or the machine is otherwise reset.  The copy of the file
on your diskette is {\em not} being modified.  To update the diskette
copy, you {\em must} save the file from within \tty{PFE}.  It is very
important to get into the habit of {\em saving early and often}.

\item Print your file out.\footnote{Select \tty{Print} on the
\tty{File} menu.}  As everybody will be trying to print at more or
less the same time, you needn't wait until it is physically printed,
but continue on with the exercise.

\item Exit from \tty{PFE} again.

\end{itemize}  

At this point you should be satisfied that, using \tty{PFE} you
know how to create, save, re-edit, and print, ASCII text files.

\subsection{Managing Files: Using \tty{File Manager}}

\tty{PFE} is adequate for basic creation and manipulation of
text files.  However, for more general management of disks and 
files\mdash formatting diskettes, 
organising files into \qt{directories}, copying files, deleting
files etc.\mdash you need a different tool, \tty{File Manager}. 
\tty{File Manager} has the further advantage that it can operate
on {\em all} kinds of files\mdash not just text files.  This isn't
much of an issue in this course yet, but will become one in the 
near future.

You will find \tty{File Manager} in the \tty{Main} group in \tty{Program
Manager}.  Start it up now.  Once it is started up, you might
want to move and resize both its window and the \tty{Netscape} window so
that they do not overlap too much, and you can see both easily.

Explore and experiment with the use of \tty{File Manager} for a while. 
Have a look at the various menus. Read through the online help -
particularly the section called {\em What is File Manager?}

Now carry out the following exercise:

\begin{itemize}
\item Create a new directory at the topmost
level on disk drive \tty{D:} with any name you wish (for
example, your own forename or surname etc.).\footnote{If you manage this
  successfully, you should be able to see the new directory listed by
  \tty{File Manager}\mdash for example as \tty{D:$\backslash$MYDIR} or
  whatever.}
Try to establish what, if any restrictions apply to naming
a directory\mdash either by experiment or by reading the help.

\item Delete the directory again.

\item Create a directory at the topmost level on your diskette
(drive \tty{A:}) with the name \tty{TMP}.

\item Move the file \tty{TESTING.TXT} from the topmost level of
your diskette into the directory \tty{TMP}.

\item Create a new directory on disk drive \tty{D:} called
\tty{MISC}. Copy the file \tty{TESTING.TXT} from directory
\tty{TMP} on your diskette into the \tty{MISC} 
directory.\footnote{To achieve
this you need two (sub-)windows open in \tty{File Manager}\mdash one
showing the contents of 
\tty{A:$\backslash$TMP}, the other showing 
\tty{D:$\backslash$MISC}. Then just {\em drag} the file
\tty{TESTING.TXT} across.}

Note how, when you {\em drag} a file, 
\tty{File Manager} {\em moves} the file if both the
starting and ending point are on the same disk, but {\em copies}
the file when they are on different disks.

\item Delete the whole directory \tty{MISC} from drive \tty{D:}
(including the file \tty{TESTING.TXT} which it contains).

\item Exit from \tty{File Manager}.

\end{itemize}

At this point you should be satisfied that you know how to use
\tty{File Manager} to examine what directories and files are on a
disk, to create and delete directories, and to move, copy, and
delete files.

\subsection{Managing email: Using \tty{Eudora Light}}

You have already seen, in session~1, how you can use
\tty{Netscape} to send email messages to one of the mailing
lists archived on the School web site, and how to read these
messages.  However, \tty{Netscape} does not support accessing or 
receiving {\em
personal} email.

To receive and manage email, in a general way, we will use the
\tty{Eudora Light} application.  \tty{Eudora} allows email to be
prepared and sent; it allows you to download email from your
personal email-box on the School server; and it allows you to
manage and organise you own archives of email messages you have
received.

Like \tty{Netscape} the effective use of \tty{Eudora} relies on
using a {\em configuration diskette} where \tty{Eudora} will
store specific information relating to your email account, and
will also store your received email messages.  You can use a
single diskette as both the \tty{Netscape} and \tty{Eudora}
configuration diskette.

A notice, detailing how to set up and use a \tty{Eudora}
diskette was posted to the \tty{Local-Notices} mailing list
within the past few weeks.  Find that message now in the web
\hot{archives}
{http://www.eeng.dcu.ie/\%7Emajordom/hm\_archives}.
In fact, look for {\em all} messages referring to \tty{Eudora Light}
(also known as \tty{Freeware Eudora}). Read these messages
carefully.

You will find \tty{Eudora} in the \tty{Internet} group in \tty{Program
Manager}.  Start it up now, and configure it, as described in
the message on \tty{Local-Notices}.  

Explore and experiment with the use of \tty{Eudora} for a while. 
Have a look at the various menus. Start up the viewer for the
online manual (also in the \tty{Internet} program group). Browse
through it (there will not be time to read it in detail).

The demonstrator will tell you the assigned password for your
account.  Verify that \tty{Eudora} can check for mail received
into your mailbox.  Try sending yourself email.  Try exchanging
email messages with the person beside you.  Send a message with
the following text:

\begin{verbatim}
    subscribe softeng1-95
    end
\end{verbatim}

to the address \tty{majordomo@mjmail.eeng.dcu.ie}.  See what
messages you receive back.  

You must now {\em change} your account password to one of your
own choosing.  Choosing a good password is not easy\mdash it must
be both hard for anyone (or any machine!) to guess, yet be
easy to remember. Briefly, your password should be 8 characters
long, use a mix of both upper and lower case letters (which are
considered to be distinct in passwords), some digits, and some
special or punctuation characters.  You may {\em not} use the
\qt{space} character in a password. Read through
this online advice on choosing
\hot{Good Passwords}
{http://www.alw.nih.gov/Security/Docs/passwd.html}.

When you have made up a satisfactory new password, which you are
sure you will be able to remember, use the \tty{Change Password}
option on the \tty{Special} menu in \tty{Eudora} to actually
change the password.  Note that this may fail for a variety
of reasons\mdash for example, if you type in the old password
wrongly, or the new password is too short, or does not have a
mix of both upper and lower case, or does not have any non
alphabetics. If the password changing fails, the old password
will remain in effect, so just go through the procedure again.

When you have succeeded in changing your password, check again
that your email access is still OK by sending yourself another
test message and seeing that you can receive it.

You should change your password again at least once every term
or so\mdash and {\em immediately} if you have any reason to suspect
that it may have been compromised.

Finally, using \tty{Eudora}, compose a short message (one
paragraph), summarising your experience of this lab exercise,
and mail it to \tty{SOFTENG1-95@mjmail.eeng.dcu.ie} .

That completes the exercise; you can now shut down all
applications, take out your diskette, exit Windows, and power
down the PC.


\section{Session 3: Week 6/7: Introducing C}
\label{session3}
\subsection{Preparation}

From this session onward it is {\em essential} that you study the notes
for the session carefully {\em in advance}.  The lab exercises are
getting increasingly extensive and demanding.  You will {\em not} be
able to study the notes for first time {\em and} carry out the required
exercises within three hours.

\subsection{Background}

In this session you will attempt, for the first time, to develop
an actual {\em program}.  You will be using the \C\ language.
This is a so-called \qt{high-level} language, so you will need to
translate the program into the \qt{low-level} or {\em machine language}
that the Central Processing Unit (CPU) can actually directly execute.
You translate the program using a tool called a {\em compiler}.

There are a wide variety of \C\ compilers available for PCs, each with
their own particular strengths and weaknesses.  We will be using 
\hot{DJGPP}
{http://www.delorie.com/djgpp} which is a
version of the {\bf GNU C Compiler} or \tty{gcc} for short.  This is
very widely used both on PCs and Unix platforms.  It has the further
advantage that it is free!

\C, and other languages closely related to it, are the {\em de facto}
industry standard programming languages for most general purpose
applications.  \C\ is a very sophisticated language in certain ways.
This makes it a powerful programming tool for the experienced software
engineer.  It also makes it a very dangerous and difficult tool for
beginners.

Therefore, in the first instance, you will be insulated from the full
complexities of the \C\ language by a specially developed device called
\tty{safe-c}.  This is, in effect, a package of pre-written building
blocks (or {\em functions} as they are called in \C), together with
a few other ancillary elements.  For the time being, the distinction
between \tty{safe-c} and \C\ \qt{proper} will not be apparent.  But later
on in the course, we will begin to uncover exactly the role that
\tty{safe-c} is playing, and separate it from standard \C.

Finally, this session is also the first to require you to prepare a {\em
formal} lab report.  Before going any further, please read carefully
through the \hot{Laboratory Report
Guidelines}
{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/rptfmt/rptfmt.html}, paying
particular attention to the {\em marking scheme}.  This is the format, and
marking scheme, that will be used in the lab exams by which this course
will be assessed.  Now is your opportunity to practise writing reports
according to the required format, and doing it in the lab, under the
same conditions as will prevail in the exams. Think of every lab session
from now on as a \qt{mock} exam.  Reports from these mock exams will be
reviewed during lectures, to give an indication of what approximate mark
could be expected for it.  You will get the maximum benefit from this if
you practise marking your report, according to the guidelines, yourself.

You must write the report {\em as you go along} in the lab session.

Start now, by using \tty{File Manager} to create a working directory called
\tty{softeng1} in the root directory of drive \tty{D:}.  Use \tty{PFE}
to create a file called \tty{report.txt} in this directory.  Insert into
this the required header text for the report, as specified in the
guidelines.  Keep \tty{PFE} running, with a subwindow open for this
file, throughout the lab session, so that you can add to it as you go
along.  Remember to save back to disk every time you add any significant
amount of text\mdash otherwise you run the risk of losing this text
completely if, for example, there is a power failure in the lab.

At the end of the session you will be required to finish the
report and submit it by email.

{\em Allow 15 minutes at the end of the session to do this.}

Specifically, even if you have not completed the assigned exercises,
stop working on them and submit the report anyway.  In the lab exams,
only the report is marked\mdash so if the report is not submitted you will
get zero marks!

Note that, because this particular lab session is very straightforward
and is largely concerned with introducing some new tools and procedures
it has relatively little technical content: you should therefore be
easily able to score over 80\%+ in your report for this session.  If you
can't achieve that then it indicates that you are not keeping pace with
the course.

\newpage
\subsection{Exercise 1: Hello World! (60\%)}

Here is the minimal \qt{Hello World} program already discussed in the
lectures:

\begin{verbatim}
  #include <safe-c.h>

  void main(void)
  {
    put_string("Hello World!\n");
  }
\end{verbatim}

Use \tty{PFE} to create a file called \tty{hello.c} in the directory
\tty{D:$\backslash$softeng1} containing the program listed above.

Start up the \tty{MS-DOS Prompt} application.  \tty{MS-DOS
Prompt} (or \tty{DOS}
for short) is a {\em command line interpreter}.  That is, it allows you
to type in textual commands which it then tries to carry out.  This is
an alternative style of user interaction, compared to the \qt{graphical}
style of using the mouse to point and click in order to get things to
happen.  This textual type interaction will be more convenient for many
of the interactions involved in developing \C\ programs.

\begin{quote}
On some PCs in the CAE lab {\bf DOS} is
configured to run \qt{full-screen}.  This means you can no longer
see the windows for other applications such as {\bf Netscape}
and {\bf PFE}.  This is quite inconvenient.  If this happens,
press {\bf Alt-Enter} (i.e. hold down the {\bf Alt} key and
press {\bf Enter}).  This will make {\bf DOS} run in a window
instead.
\end{quote}

Under \tty{MS-DOS Prompt} you will have, at any given time, a \qt{default
disk drive} and \qt{default directory} on that drive.  This simply means that
if you refer to a file, without explicitly stating what disk drive
or directory it is located in, then \tty{DOS} will assume it is
on the default drive and in the default directory.  The \tty{DOS}
prompt will indicate the current default drive and directory.
We are going to be working with files on drive \tty{D:} and in directory
\tty{softeng1}, so it will be convenient to make these the
defaults.

To change the default drive, simply type in the desired drive letter
followed by a colon, and press \tty{Enter}.  The prompt should change to
reflect the new default.  Try changing to drive \tty{A:} and back to
drive \tty{D:} now to see this happened.

To change the default directory (on the default drive) use the \tty{cd}
command (short for {\em Change Directory}):

\begin{verbatim}
    cd \tmp
\end{verbatim}

Note the leading backslash character $\backslash$ here.  This character is used
to separate drive specifiers from directory names, and directory names
from subdirectory or file names etc.  In this particular case, the 
$\backslash$
signals that \tty{tmp} is in the top-level or root directory of the
current drive.  If the $\backslash$ were omitted, 
\tty{DOS} would think that
\tty{tmp} was intended as the name of a {\em sub-}directory of the
current directory (whatever that might be).

Experiment with changing the current directory to make sure that you
understand its operation fully.  You can only change to directories that
exist.  You can, of course, check what directories (and files) exist
using \tty{File Manager}.  Alternatively you can use the \tty{dir}
command in \tty{DOS}.  You can get help on \tty{DOS} commands by using the
\tty{help} command.  Its operation is pretty self explanatory.
Experiment with it now.

Note that case is not significant in \tty{DOS} command, directory, file,
or drive names\mdash so, for example, \tty{CD} has the same effect as
\tty{cd} etc.

Make \tty{D:$\backslash$softeng1} your current drive and directory.  Use
\tty{dir} to check that the file \tty{hello.c} is present there.  You
can use the command \tty{type} in \tty{DOS} to type the contents of a
text file on the screen.  Try this now to check that \tty{hello.c} does
indeed contain what you expect.

Compile your program by giving the command:

\begin{verbatim}
  scc hello
\end{verbatim}

\tty{scc} is part of the \tty{safe-c} package.  It invokes the \C\
compiler in the appropriate way to ensure that the \tty{safe-c}
components get automatically combined with your program.

The program {\em should} compile without any problems\mdash if you have
entered it correctly.  But if any problems are encountered try to figure
out what is going wrong and fix them.  If you get stuck, seek help from
the demonstrator.

Check (using \tty{File Manager} or the \tty{dir} command in \tty{DOS})
what files now exist in your directory.  There should be a new file
called \tty{hello.exe}.  This is the executable file\mdash the file
containing the binary instruction codes that the CPU can directly
execute.  Make a note of the size of this file in your report.

To execute the program under \tty{DOS} you simply give its name as a
command:

\begin{verbatim}
    hello.exe
\end{verbatim}

In fact, it is enough to just say \tty{hello} as the command name -
\tty{DOS} will automatically search for a file with that name and the
\tty{.exe} extension.

Check that the file executes as you expected.  If it does not, try to
figure out why, and fix it.  Again, if you get stuck, ask for help from
the demonstrator.

If all has executed correctly, then congratulations\mdash you have just
entered, compiled, and tested your first \C\ program.

Make a directory called \tty{lab3} in the root directory of your
diskette. Copy the file \tty{hello.c} into this directory.  There is no
need to copy the file \tty{hello.exe} onto your diskette\mdash explain why
in your report.

\subsection{Exercise 2: Branching out! (40\%)}

Here is the program \tty{insult.c} introduced in the lectures:

\begin{verbatim}
    #include <safe-c.h>

    void main(void)
    {
      string_type s;

      put_string("Welcome to INSULT!\n");
      put_string("What is your name?\n");
      get_string(s);

      if (string_equal(s, "Barry\n"))
        put_string("Hi, smarty pants!\n");
      else
        put_string("oooh - I don't like *you*!!!\n");

      put_string("Bye bye from INSULT...\n");
    }
\end{verbatim}

Using this as a basis, or template, develop (plan, code, test, correct)
a program called \tty{sport.c} which will behave as follows:

\begin{enumerate}
\item Display a suitable welcome/identification message.
\item Ask the user to type in his or her favourite sport.
\item If the topic is \qt{Tennis}, display the message \qt{Tennis?
      I used to play Cricket!}.
\item If the topic is anything else, display the message
      \qt{What a silly game!} instead.
\item Finally display some suitable closing message.
\end{enumerate}

\subsection{Conclusion}

That completes the exercise. As previously explained, the formal lab
report, which you have prepared during the session,
must now be submitted by email.

Carry out the following procedure to submit your report.
You need to allow at least the last 15 minutes of the lab session
for this.

\begin{itemize}
\item Read quickly back through the report, correcting obvious errors,
and possibly adding some brief concluding remarks.

\item Close the \tty{PFE} subwindow.

\item Using \tty{File Manager}, make a copy of the report file in the
directory \tty{lab3} on your diskette.  This gives you a permanent copy
of the report as a precaution against it somehow getting lost or
corrupted in the mail system.

\item Using \tty{Eudora}, bring up a new message window to prepare to
email the report.

\item Fill in the \tty{To:} field as:

\begin{verbatim}
    softeng1-95-reports@mjmail.eeng.dcu.ie
\end{verbatim}

Its a good idea to also include yourself as an additional recipient (in
the \tty{Cc:} field) so that you get positive feedback that the message
successfully went into the mail system.

\item Fill in the subject of the message as simply \qt{Session 3 Report}.

\item To include the report file in the message, drop down the
\tty{Message} menu and select \tty{Attach File}.  This
will bring up a file selection dialog. Select the file where you have
saved the report 
(\tty{D:$\backslash$softeng1$\backslash$report.txt}).

\item BEWARE: \tty{Eudora} has several possible mechanisms for
\qt{attaching} files to a message, depending on the type of data in the
file (e.g. whether it is simply ASCII text, or some kind of word
processing format or whatever).  Only one of them will work correctly
for your lab reports.  If you get this wrong in the lab exam, the report
will not be correctly submitted and you will score zero.

The correct mechanism in this particular case is for \tty{Eudora} to
simply include the text from the file as part of the text of the
message.  It will do this if the button on the message window marked
\qt{TEXT->DOC} is {\em out} or {\em deselected}.  Check this now, and make
sure the button is in the correct state.\footnote{You may find it
convenient to make this the {\em default} for \tty{Eudora}. Drop down the
\tty{Special} menu and select \tty{Settings}.  Scroll down through the
categories and select \tty{Attachments}.  Put a cross in the box marked
\tty{Put text attachments in body of message}.  Now, whenever you bring
up a new message window, the \qt{TEXT->DOC} button will be deselected by
default.}


\item Press \tty{Send} to send the message.

\item If you have included yourself as an
additional recipient, then you should receive a copy back.  
Wait about 30 seconds and then check this.

\end{itemize}

This submitted report should be automatically archived on the school Web
site, under the archives for the \tty{softeng1-95-reports} mailing list.
However, this will only happen after the report has been previewed and
approved by the moderator, which should normally be within a couple of
hours.  You should make a point of checking whether your report appears
correctly in the archives in due course.  If not, do {\em not} submit it
again.  First, post a message on the \tty{softeng1-95} list, querying
what has happened.

\section{Session 4: Week 8/9: Quiz Time}

\subsection{Introduction}

This session is concerned with developing and reinforcing the
basic tools of \C\ programming already introduced.  The session
does {\em not} involve any significant new concepts, but merely
requires that you apply the techniques you have already learned
in slightly more elaborate ways.

You are again required to write a formal lab report, and submit
it by email, in exactly the same format and manner as in session
3.  This session also again involves creating, editing and storing
files on your PC (in suitable directories), 
and compiling \C\ source files to produce
executable files. 
If you are unsure of any aspect of doing these things, 
please review the
\htmlref{session 3 notes}{session3} 
again. The relevant instructions will {\em not}
be repeated here.

This session has two exercises.  In the first you are give a
program and told what it ought to do.  You are then asked to
test whether the program behaves as specified; and, if not, to
correct any defects you can identify.  In the second exercise
you are asked to develop a more ambitious program, based on the
given program.

\subsection{Exercise 1: Correction (60\%)}

Consider the program \hot{mquiz0.c}
{../src/mquiz0.c}.  This should prompt for the user's name; then
print \qt{Hello } followed by the user's name; then repeatedly ask
the user what the best album of all time is, unless and until
the answer \qt{Dark Side of the Moon} is given.

Test whether this program behaves as specified.\footnote{Note
  that, once you are viewing the program file in \tty{Netscape},
  you can use the \tty{Save as...} option on the \tty{File} menu of
  \tty{Netscape} to save a copy of the program in some suitably
  named file on your PC.} 
If not,
identify and correct any defects.  Carefully record each such
defect, and your correction, in your formal report.

\subsection{Exercise 2: Enhancement (40\%)}

The program \tty{mquiz0} will keep on repeating the question
unless and until the user is inspired to give the correct
answer.

Develop an enhanced version of this program, called
\tty{mquiz1}.  This should behave in the same way as mquiz0,
except that, if the user gives a wrong answer, the program
should then {\em ask} whether the user wants to try again. If the
user indicates that he or she does {\em not} want to continue
then the program should exit (remarking \qt{Good idea - `cos you 
don't know much about music, do you?}).

\section{Session 5: Week 10/11: Ever Decreasing Circles...}

\subsection{Introduction}

This session introduces the use of two new 
\tty{safe-c} data types\mdash \tty{integer\_type} and
\tty{floating\_point\_type}. 

A {\em data type} is a format for storing and manipulating some
particular \qt{kind} of information in a \C\ program.  So far
we have used just two data types: \tty{string\_type}
and \tty{boolean\_type}.  

\tty{string\_type} allows 
the input, output, and comparison of
arbitrary strings of \tty{ASCII} characters.  The length of the
string is variable, up to a certain
maximum length. The only manipulations allowed (so far) on
objects of \tty{string\_type} rely on using {\em functions} (or
\qt{subprograms}) provided by the \tty{safe-c} module:

\begin{itemize}
\item \tty{put\_string()} : Allows a string to be be displayed
in the \tty{MS-DOS} window in which the program is running.
\item \tty{get\_string()} : Allows a string to be read in from
the keyboard.
\item \tty{string\_equal()} : Allows two strings to be compared.
Generates a \tty{return} value which is of \tty{boolean\_type}. 
This will be \tty{TRUE} if the two strings
are {\em exactly} identical, and \tty{FALSE} otherwise.
\end{itemize}

\tty{boolean\_type} has only two
possible values (\tty{TRUE} and \tty{FALSE}) and is useful
in controlling \tty{if} and \tty{while} statements.  Values of
\tty{boolean\_type} can be manipulated with the following {\em
operators}:

\begin{verbatim}
        &&       Boolean AND. 
        ||       Boolean OR.
        !        Boolean NOT.
        ==       Test for equality.
        =        Assignment.
\end{verbatim}

In more detail, the meaning of these operators is as follows:

\begin{itemize} 

\item {\em Boolean AND}: Denoted by a double ampersand
\qt{\tty{\&\&}} (with no space between them). Takes two
operands.  If both operands are \tty{TRUE} it evaluates as
\tty{TRUE}; otherwise it evaluates as \tty{FALSE}.

\item {\em Boolean OR}:  Denoted by a double vertical bar
{\tt "||"} (with no space between them). Takes two operands. 
If either operand is \tty{TRUE} it evaluates as \tty{TRUE};
otherwise it evaluates as \tty{FALSE}.

\item {\em Boolean NOT}: Denoted by an exclamation mark
\qt{\tty{!}}.  Takes one operand.  If the operand is \tty{TRUE}
it evaluates as \tty{FALSE}; if the operand is \tty{FALSE} it
evaluates as \tty{TRUE}.

\item {\em Test for equality:} Denoted by a double equal sign
\qt{\tty{==}} (with no space between them).  Takes two
operands.  If both operands have the same boolean value it
evaluates as \tty{TRUE}; otherwise it evaluates as \tty{FALSE}.
This operator can be applied to operands of certain types other
than \tty{boolean\_type}, but its result is {\em always} of
\tty{boolean\_type}.  When the operands {\em are} of
\tty{boolean\_type} it is equivalent to the negation of the
boolean {\em XOR} (Exclusive OR) operator.

\item {\em Assignment}: Denoted by a single equal sign
\qt{\tty{=}}.  Takes two operands. The left hand operand {\em
must} be a variable.  The value of the right hand operand is
copied into, or assigned to, the variable named as the left hand
operand.\footnote{The assignment operator also technically
generates an \qt{evaluation result}, just as any of the other
operators do.  This evaluation result will be the value of the
right hand operand\mdash i.e. the same value as is stored in the
variable named as the left hand operand.  This allows an
assignment operation to be nested within a more complex
expression.  That is {\em sometimes} useful, but its use is
beyond the scope of the current session.}

\end{itemize}

The two new data types introduced in this session are both used
to represent, store, and manipulate {\em numbers}.  
\tty{integer\_type} can represent only whole numbers (positive
and negative); \tty{floating\_point\_type} can represent
fractional, or rational, numbers (positive or negative), 
using a form of scientific
notation.

The most basic operation or manipulation that can be performed
with these data types is to assign a value to a variable of that
type.  This uses the same assignment operator as for
\tty{boolean\_type}. For example:

\begin{verbatim}
  integer_type the_answer;
  floating_point_type pi;

  the_answer = 42;
  pi = 3.141;
\end{verbatim}

Note, incidentally, that the assignment operator
{\em cannot} be used with objects of \tty{string\_type}. Thus,
it would quite wrong to say something like:
\begin{verbatim}
  string_type s;

  s = "Hello world!";
\end{verbatim}

If you need to do something like that, use the function
\tty{assign\_string} instead:
\begin{verbatim}
  string_type s;

  assign_string(s, "Hello world!");
\end{verbatim}

Both the numerical data types allow
the four normal arithmetic operations:

\begin{verbatim}
        +       Addition. 
        -       Subtraction.
        *       Multiplication.
        /       Division.
\end{verbatim}

These operators all accept two operands, and evaluate with a result
which is of the same data type as the operands.  Note carefully
that when you divide two values of \tty{integer\_type} the result
is just the {\em quotient} and will {\em still} be of 
\tty{integer\_type}. Any remainder 
will be discarded. Thus, for example \tty{5/3} would evaluate
as \tty{1}. You can use the special {\em remainder} operator,
denoted by \tty{\%}, to separately calculate the remainder part
of an \tty{integer\_type} division if you like. So \tty{5\%3}
evaluates as the remainder after dividing 5 by 3, which is to
say \tty{2}. The remainder operator is not 
applicable to \tty{floating\_point\_type} (for obvious reasons?).

These numerical data types also allow various comparison operations:

\begin{verbatim}
        ==        Test for (exact) equality.
        >         Strictly greater than.
        >=        Greater than or equal to.
        <         Strictly less than.
        <=        Less than or equal to.
\end{verbatim}

All of these comparison operators yield a result of
\tty{boolean\_type}.

The detailed way that \tty{integer\_type} and
\tty{floating\_point\_type} are represented internally will not
be discussed here, except to say that they both rely on a {\em binary}
notation, because this matches best the actual physical nature
of the computer's memory system.
Functions are provided to convert between values of
these binary numerical data types and \tty{string\_type}\mdash which
indirectly allows input and output of these numbers (using
\tty{get\_string()} and \tty{put\_string()}).

All the data types and functions introduced here are specific to
the \tty{safe-c} module and you will {\em not} find them discussed in
standard \C\ texts.  However, all the {\em operators}
(arithmetic, boolean, assignment, comparison) are part of the
\C\ language definition and {\em will} be covered in the
textbooks.

More detailed information on these
new data types, and the facilities available for using 
them, is 
provided in the \hot{safe-c User Guide}
{../safe-c}.

You are again required to write a formal lab report in this
session, and submit
it by email, in exactly the same format and manner as in
sessions
3 and 4.  This session also again involves creating, editing and storing
files on your PC (in suitable directories), 
and compiling \C\ source files to produce
executable files. 
If you are unsure of any aspect of doing these things, 
please review the
\htmlref{session 3 notes}{session3} 
again. The relevant instructions will {\em not}
be repeated here.

The overall format of this session is very similar to session 4.
It has two exercises.  In the first you are given a
program and told what it ought to do.  You are then asked to
test whether the program behaves as specified; and, if not, to
correct any defects you can identify.  In the second exercise
you are asked to develop a more ambitious program, based on the
given program.

\subsection{Exercise 1: Correction (50\%)}

Consider the program \hot{circle0.c}
{../src/circle0.c}.  This should prompt for the user's name; then
print \qt{Hello } followed by the user's name; then ask
the user to enter the radius of a circle (in {\it m}); the program should
then calculate and print out the circumference and area of the
circle.\footnote{The circumference is given by the mathematical
formula $2\pi r$ ; the area by the formula $\pi r^2$.}

The program is very poorly laid out and formatted.  Reformat it
in a way that makes it easier to read and understand.\footnote{Note
  again that, once you are viewing the program file in \tty{Netscape},
  you can use the \tty{Save as...} option on the \tty{File} menu of
  \tty{Netscape} to save a copy of the program in some suitably
  named file on your PC.} 
Correct any \qt{obvious} mistakes.
Of course, you should note
what changes your make, and include a copy of the reformatted
program, in your formal report.

Now test whether the program behaves as specified.
If not, identify and correct any defects.  Carefully record each such
defect, and your correction, in your formal report.

\subsection{Exercise 2: Enhancement (50\%)}

The program \tty{circle0} calculates the circumference and area
of just one circle. 

Develop an enhanced version of this program, called
\tty{circle1}.  This should behave in the same way as
\tty{circle0},
except that it should repeat the
sequence (of requesting a radius, then calculating and printing
out the circumference and area) exactly {\em five} times. Each time
the prompt should change  (so the first time it should say
\qt{Enter radius 1:}, the second time \qt{Enter radius 2} and so
forth).

\section{Session 6: Week 12/13: Lab Examination 1}

Please see the 
\hot{General Examination Instructions}
{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/95-96/exams/general}, which
includes links to all the specific examination exercises for the
different sections of the class.

\section{Session 7: Week 14/15: Functional Decomposition}

\subsection{Introduction}

This session is concerned with practical experimentation with
the \C\ facilities for breaking down a program into smaller,
more manageable, pieces called {\em functions}.

The standard \C\ library makes available a large range of standard
mathematical functions.  These include standard trigonometrical
functions, \tty{sin()}, \tty{cos()} and \tty{tan()}.  These three
functions each accept one argument (of
\tty{floating\_point\_type}) and
\tty{return} a result (also of \tty{floating\_point\_type}). The
argument must be an angle measured in {\em radians}.  Often it is
more convenient to work with angles measured in {\em degrees} instead.
The ultimate objective of this session is for you to write your own
trigonometric functions (exploiting the existing standard functions)
which will accept arguments in degrees rather than radians. However,
we shall get there through a series of smaller steps.

Before this session it is essential that you review and understand the
very basic example programs, already introduced in the lectures, which
illustrate functional decomposition. These are:

\begin{itemize}
\item \hot{sum0.c}{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/src/sum0.c}:
This program prompts for two numbers, adds them, and prints out the sum.
It does not use functional decomposition at all.
\item \hot{sum1.c}{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/src/sum1.c}:
This is a modified version of \tty{sum0.c} in which a new function has
been defined, called \tty{get\_floating\_point()} which combines the
effects of the standard \tty{safe-c} functions \tty{get\_string()} and
\tty{string\_to\_floating\_point()}.  This illustrates how to define a
function which has to pass back, or {\em return}, some information to
the place which it was called from; and how to use, or access, that
information at the calling site.
\item \hot{sum2.c}{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/src/sum2.c}:
This is a further modified version, in which a second new function has
been defined, \tty{put\_floating\_point()} which combines the effects of
\tty{floating\_point\_to\_string()} and \tty{put\_string()}. This
illustrates how to define a function where some information has to be
passed {\em from} the calling site, {\em into} a function, and how that
information can be accessed within the function.
\end{itemize}

The session is divided into five separate exercises.  Each of these
builds on the previous one. It is important that you read through the
instructions for {\em all} the exercises, {\em in advance} of the lab
session. None of the exercises is very complex in itself, and you should
be able to complete all five in the time available. However, it is more
important to fully complete as many of the exercises as possible than to
make an incomplete attempt at them all. So, it is essential that you
take the exercises in the order given, and do not attempt to go on to a
following exercise until you have {\em fully} completed its precursor.

Each exercise involves {\em developing} a program.  Note carefully that
\qt{develop} here means writing, compiling (with no errors or warnings),
and {\em testing}.  The tests should exercise a reasonable range of
behaviour before you consider them complete.  The report {\em must}
specify exactly (including actual numerical values, where relevant) what
tests you carried out, what results you expected, and what results the
program generated.  If the actual results are not exactly the same as
the results you expected, you must comment on this.

\subsection{Exercise 1: The \tty{sin()} Function (20\%)}

Develop a program, called \tty{trig1.c}, which will prompt for an angle
value (in radians), and print out the {\it sine} of that angle.

Where appropriate, this program
should use the functions \tty{get\_floating\_point()} and
\tty{put\_floating\_point()} defined in the example program
\hot{sum2.c}
{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/src/sum2.c}. You
can simply cut and past the relevant section of that program
into your own program.

This program does {\em not} involve defining any additional
new functions of your own.

\subsection{Exercise 2: Angle Conversion (20\%)}

Modify \tty{trig1.c} as follows, renaming it as \tty{trig2.c}.

\tty{trig2.c} should prompt for an angle in {\em degrees}. It should
then calculate the corresponding angle in radians, using the equation:

\[ \theta_r = \theta_d \times \frac{\pi}{180} \]

where $\theta_d$ and $\theta_r$ denote the angle expressed in degrees
and radians respectively.

Having converted the angle to radians, it should then calculate, and
print out, the {\it sine} (this behaviour is unchanged from
\tty{trig1.c}).

The degrees conversion calculation should be carried out \qt{directly}
by suitable statement(s) within the \tty{main()} function.
That is, this program again does {\em not} involve defining any additional
new functions of your own.

\subsection{Exercise 3: Function Definition (20\%)}

Modify \tty{trig2.c} as follows, renaming it as \tty{trig3.c}.

\tty{trig3.c} should {\em behave} exactly as \tty{trig2.c}.  However,
instead of carrying out the angle conversion directly within the
\tty{main()} function, \tty{main()} should invoke or call a new
function, called \tty{deg\_to\_rad()}, to do this conversion.  This
should accept a single argument, of \tty{floating\_point\_type},
representing an angle in degrees. It should  \tty{return} a result, also
of \tty{floating\_point\_type}, being the corresponding angle in
radians. Of course, {\em you} have to provide the definition of this new
function.

\subsection{Exercise 4: Refinement (20\%)}

Modify \tty{trig3.c} as follows, renaming it as \tty{trig4.c}.

\tty{trig4.c} should behave exactly as both \tty{trig3.c} and
\tty{trig2.c}.  However, instead of calling \tty{deg\_to\_rad()} and
then calling \tty{sin()}, \tty{main()} should simply call a single new
function, called \tty{deg\_sin()}. This should accept a single argument,
of \tty{floating\_point\_type}, representing an angle in degrees. It
should  \tty{return} a result, also of \tty{floating\_point\_type},
being the {\it sine} of this angle. Again, {\em you} have to provide the
definition of this new function. It should {\em use} the
function \tty{deg\_to\_rad()} which you have already written.

\subsection{Exercise 5: Finale (20\%)}

Modify \tty{trig4.c} as follows, renaming it as \tty{trig5.c}.

\tty{trig5.c} should prompt for an angle in degrees, and then print out
the {\it sine}, {\it cosine} and {\it tangent} of this angle.  The
\tty{main()} function should be structured to invoke functions called
\tty{deg\_cos()} and \tty{deg\_tan()} to calculate the {\it cosine} and
{\it tangent} respectively. You will have to add definitions for
these functions, similarly to the definition of \tty{deg\_sin()}.

\subsection{Hints}

When defining a new function, you need to first prepare an adequate {\em
specification}.  This will consist of answers, expressed in plain
English, to the following questions:

\begin{itemize}

\item {\bf What will it be called?}

\C\ function names, like \C\ variable names, consist of a sequence of
characters, including upper and lower case alphabetics, the digits
\tty{0} through \tty{9}, and the underscore character \tty{\_}. The name
should always {\em begin} with an alphabetic.  Names can be as long as
you wish, but anything much longer than 20 characters becomes unwieldy
and error-prone and should usually be avoided.  All function names must
be unique within a given program. Most \C\ programmers use
{\em only} lower case alphabetics in function and variable names (i.e.,
no capitals).  However, this is only a convention, and is not a
compulsory part of the \C\ language definition.  Names of functions are
usually chosen based on {\em verbs} because they {\em do} something -
whereas names of variables tend to be based on nouns (they just
\qt{are}). It is important to think carefully about the names of both
functions and variables in a \C\ program.  While the compiler really
doesn't care (as long as the names are unique) these choices can make a
{\em big} difference to how easy or difficult it is for another human
being to understand how the program is intended to operate.

\item {\bf What (if any) information will be passed in from the
calling site?}

Many functions can behave differently based on certain information
passed into them by their calling function.  For example, the standard
function \tty{put\_string()} is able to print out {\em any} string on
the screen.  Which {\em particular} string it will print out on any
particular occasion is specified by the calling site\mdash the invocation
specifies a particular string to be passed {\em into} the function.

The specification of the information to be passed into a function will
thus determine the layout of its {\em argument list}. The argument list
states how many arguments the function will accept, what types they must
be, and what names will be used {\em within} the body of the function
to refer to these arguments.

\item {\bf What (if any) information will be passed back to the calling
site?}

Many functions generate a result of some sort, which must be made
accessible to its calling site, after the function has finished
execution.

In the special case of objects of \tty{string\_type}, this can be
achieved by the calling site passing {\em in} a string variable to the
function; any changes which the function makes to this string, will
still be visible, after the function terminates, at the calling site.
This is called {\em passing by reference}, and is the mechanism used,
for example, by the \tty{get\_string} function.

However, this does {\em not} work for information of other types.  Thus,
for example, if a variable of \tty{integer\_type} is passed into a
function, all that \qt{really} happens is that a {\em copy} of this
variable is made available to the function.  Any changes which the
function makes to that value are {\em lost} when the function exits.
This is called {\em passing by value}.  In this case, the idea of
passing in a variable for a function to modify cannot be used to allow a
function to pass information back to its calling site.  In that case,
you should use the \tty{return} value mechanism.  If you place a
\tty{return} statement in your function then, when that statement is
executed, the function will immediately terminate, and the specified
value will be made available at the calling site, in the
position where
the function was invoked.  This is the mechanism used, for example, by
the \tty{string\_floating\_point} function.  Typically, this
\tty{return} value is assigned to a variable at the calling site, so
that it can be stored for use in subsequent statements.

The \tty{return} mechanism {\em cannot} be used to pass back values of
\tty{string\_type}.  In that case, you {\em must} use the passing by
reference mechanism, where a string variable, belonging to the calling
site, is passed into the function as an argument, and modified by it.

The specification of the information to be passed back from a function
may thus lead to the specification of additional arguments (passing by
reference), or to the specification of a \tty{return} type (or,
possibly, both).

\item {\em What will the function actually do?}

That is, having stated what, if any, information if passed in, and what,
if any, information is passed back, you need to state, in plain English,
what the effect of the function is supposed to be.

\end{itemize}

The idea of defining a new function usually arises in the context of
some \qt{higher level} function which you are already writing.
Essentially, you want to defer coding some more detailed activity or
calculation. This is called \qt{top-down} design, and is a typical
strategy for all forms of engineering design, not just software.
So, for the time being, you just want to put in a call to a
function, which, at some later stage, you will define in detail.  The
coding of this function call will, implicitly, at least, answer all of
the questions we have just raised.

Having answered these questions, you should then enter the {\em skeleton}
definition of the function:

\begin{verbatim}
<return type>  <function name> ( <argument list> )
{
 <function body>
}
\end{verbatim}

You then go back and fill in the slots.  For example, suppose we decide
to define a function called \tty{foo}, which will accept one argument of
\tty{floating\_point} type, and generate no \tty{return} value, we can
immediately make out the following skeleton:

\begin{verbatim}
void foo(floating_point_type arg)
{

}
\end{verbatim}

You need to minimally provide this skeleton, just to allow an {\em
invocation} of the function to even be compiled properly.  You may well
temporarily put in a \qt{dummy} body to the function\mdash called a {\em
stub}\mdash just to allow you to test out the higher level invocation.  But,
eventually, you must come back and fill in the body of the function
definition with the actual \C\ statements which will make it, upon
invocation, carry out the activities specified for it.

\section{Session 8: Week 16/17: Projectiles}

\subsection{Problem Specification}

The purpose of this exercise is to calculate the theoretical trajectory
of a projectile in a constant gravitational field. In other words, we
want to calculate the path followed by, say, a ball thrown in the air.

We are going to make some simplifications.  We will work in just two
dimensions (i.e. as if we are looking exactly side on at the path of the
ball). We will also neglect air resistance, and will treat the
projectile as a point mass. This allows a simple analysis of the motion
of the projectile, using newtonian theory.

In our two dimensional ($x$ and $y$) coordinate system, $x$ will denote
horizontal position, and $y$ will denote vertical position.

The initial value of $x$ will be taken as zero.

A zero $y$ value will correspond to the projectile being on the ground.
The initial value of $y$ will be some positive value (in effect, the
height of the person throwing the ball).

$V_x$ will denote the horizontal component of velocity, and $V_y$ the
vertical component. We will assume that both $V_x$ and $V_y$ are
initially positive. Similarly, $A_x$ and $A_y$ will be the components of
acceleration.

The \qt{initial} information provided for a particular run of the program
will be the initial
height ($y$) and initial velocity components ($V_x$ and $V_y$) of the
projectile. These values will be assigned to suitable variables. You can
either code values directly into the program (in which case you will
have to change the program, and recompile, every time you want to try
different values) or you can have the program prompt for and read in
values when it starts running.

The output from the program will be a print out on the screen of
the numerical values
of $x$ and $y$ at successive, \qt{small}, intervals of time. The program
should terminate when $y$ becomes zero again (i.e. the projectile falls
back to earth). This print out may be captured into a text file
and a graph plotted of $y$ versus $x$ (one way of doing this
is described in detail in
the \htmlref{Hints}{hints8} section below).

Informally, the motion of the projectile is pretty simple: it moves
steadily to the right (positive $x$ direction), simultaneously going up
for a while (positive $y$ direction), and then coming down again to
land.\footnote{Technically, under the various idealizing assumptions we
  have made, it can be shown that the trajectory will be {\em
  parabolic}.}

Formally, at each time step, the new $y$ co-ordinate can be calculated
as:

\[y(t+1) = y(t) + \Delta y(t) \]

where (approximately):

\[\Delta y \simeq V_y \times \Delta t \]

In words, if the velocity in the $y$ direction is $V_y$, then, in a time
$\Delta t$, the projectile will move a distance of $V_y$ multiplied by
$\Delta t$; and the new $y$ position is the old $y$ position plus this
movement. This calculation would be {\em exact} if $V_y$ were {\em
constant}; if $V_y$ is {\em changing} (as it will be in our case) then
the calculation will still be {\em approximately} correct, as long as
$\Delta t$ is \qt{small}\mdash namely small enough that the percentage change
in $V_y$ in that time is \qt{negligible}.  Of course, you can only
estimate this once you have some idea of how quickly $V_y$ will be
changing...

The new $x$ co-ordinate may be calculated similarly.

Now, in principle, both $V_x$ and $V_y$ could {\em also} be
simultaneously changing, and have to be recalculated, at each time step.
But since we are neglecting air resistance, and since gravity works
straight down, there will be zero acceleration in the $x$ direction
($A_x$ is zero), so that $V_x$ will actually remain {\em constant}, equal to
its initial value. There {\em will} be acceleration in the $y$ direction
however, of value $-g$, where $g$ is the acceleration due to gravity at
the surface of the earth (about 9.81 meters per second per second).
This is {\em negative} because our $y$ co-ordinate is positive in the upward
direction and gravity works {\em downward} (last time I checked anyway...).
This {\em acceleration} in the $y$ direction will be constant (since $g$ is
not changing). Thus, the new $V_y$ at each time step can be calculated
as follows:

\[ V_y(t+1) = V_y(t) + \Delta V_y(t) \]

where:

\[ \Delta V_y = A_y \times \Delta t \]

That is, the change in the (vertical) component of speed is simply the
(vertical) acceleration multiplied by the time it acts over; and the new
speed is simply the old speed plus this change.\footnote{This change
  will be negative, because $A_y$ is negative; to put that
  another way, what goes up must come down!}

You should test your program carefully.  Explain, in your report, what
tests you carry out, how the program behaves, and whether it has passed
such tests.

\subsection{Hints}
\label{hints8}
\subsubsection{The \tty{main()} Function}

Your \tty{main()} function should declare variables to
represent the values of all the relevant quantities.  Think
carefully about naming these variables\mdash note, for example,
that variable names cannot involve subscripts, or greek
characters.  Think carefully about the {\em type} of each
variable: is it to be used to represent a {\em numerical}
value? If so, will that value be strictly integral, or
may it have a fractional part?

The overall structure of your \tty{main()} function will
consist of some initialisation (assigning initial values to
appropriate variables), followed by a \tty{while} loop
which carries out the repeated calculations of the new
$x$ and $y$ co-ordinate values.  This loop should continue
just so long as the $y$ value is greater than zero.
The repetition, or iteration, in your program should
be achieved using a \tty{while} statement.

It might be a good idea to start off with a highly simplified
version of the \tty{main()} function, having only a
variable to represent
$y$ and which just (for example) decrements
the $y$ value by a fixed amount each iteration.  This would
allow you to check, at this early stage, that you have
correctly implemented the \tty{while} loop and that it
terminates when appropriate.

\subsubsection{Functional Decomposition}

Try to use functional decomposition to break your program
into smaller, more manageable pieces.  This will make it
easier to write, test, and debug.

Where appropriate,
consider using the functions \tty{get\_floating\_point()} and
\tty{put\_floating\_point()} defined in the example program
\hot{sum2.c}
{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/src/sum2.c}. You
can simply cut and past the relevant section of that program
into your own program.

Define a new function of your own, which deals with printing
out the results, for one cycle of your calculations. This
can then be simply called or invoked from within the
\tty{while} loop of your \tty{main()} function\mdash which
should make the \tty{main()} function shorter and easier to
follow. Note that this function will have to accept two arguments
(being the current values for the $x$ and $y$ co-ordinates).

\subsubsection{Command Line Redirection}

\label{redirection}
If you want to plot a graph of the trajectory calculated by your
program, you will need to capture the program output in a file, rather
than having it simply displayed on the screen.

Perhaps the simplest way of arranging for a program to route its output
to a file (or, indeed, to take its input {\em from} a file), is to use
so-called {\em command line redirection}.

Suppose your program is in a file called \tty{foobar.c}.  After
successful compilation, you will have a executable file called
\tty{foobar.exe}.  Normally you would execute this simply by giving the
name \tty{foobar} as a command. However, if you want to use command line
redirection, you would give a command somewhat like this instead:

\begin{verbatim}
        foobar   >out.txt   <in.txt
\end{verbatim}

The $<$ serves as the \qt{input redirection} character in an MS-DOS command
line. The effect is that the input for \tty{foobar} will no
longer be taken from the keyboard, but from this file instead.
Similarly, the $>$ character in an MS-DOS command provides for output
redirection, to direct output to a file instead of the screen.

With any given command invocation you can choose to use no redirection
at all (as we have been doing up to now), or to use input redirection
only, or output redirection only, or both together.

\subsubsection{Plotting a Graph}

Sometimes you may find it useful to view the output of a program in the
form of a graph. There are a variety of ways of doing this. One simple
way is using a utility program, provided on the PC's in the CAE Lab,
called \tty{graph}. This program should be run as a {\em full-screen}
MS-DOS application. To do this, first open an MS-DOS window by double
clicking on the relevant icon in Program Manager.  Then make this window
take over the full screen by pressing \tty{Alt-Enter} 
(i.e. press and hold the \tty{Alt} key while you press the \tty{Enter} 
key also). 

If your program's output has been stored in a file
called \tty{out.txt}, you can then see a graph of this simply by giving the
following command:

\begin{verbatim}
        graph out.txt
\end{verbatim}

Note that \tty{graph} expects each line of its input file to contain
just two numbers.  The first is taken as the \qt{x} co-ordinate, and the
second as the \qt{y} co-ordinate, of a single point to be plotted.
\tty{graph} will automatically scale the axes in order to fit in all the
data points.

You can exit from the \tty{graph} program by pressing the \tty{Esc} key.
You can make the MS-DOS application revert from full-screen to a window by
pressing \tty{Alt-Enter} again.


\section{Session 9: Week 18/19: {\em Encryption}}

\subsection{Exercise 1: The Caesar Cipher (50\%)}

\qt{Encryption} is the process of disguising a message or text so that its
meaning will not be apparent to anyone who may intercept it,
accidentally or otherwise.

In this exercise you will work with a very simple encryption procedure.
This is called a substitution cipher, in which each letter of the
original message (the \qt{plaintext}) is replaced by a different letter to
generate the coded message (the \qt{ciphertext}).

To simplify matters further, we will restrict our plaintext to use only
the upper case letters \tty{A} to \tty{Z}, together with the space and
newline characters; furthermore, space and newline characters will be
left unchanged by the encryption.

In each case, the replacement letter will be a fixed number of letters
later in the alphabet compared to the original letter (and \qt{wrapping
around} back to \tty{A} again after \tty{Z}, as necessary). The number
of letters to count forward will be called the encryption {\it
key}.

Thus, with a key of 3, we would replace \tty{A} by \tty{D}, \tty{B} by
\tty{E} and so on, with, finally, \tty{W} being replaced by \tty{Z},
\tty{X} by \tty{A}, \tty{Y} by \tty{B} and \tty{Z} by \tty{C}.

This simple kind of cipher is sometimes called a \qt{Caesar Cipher}
after Julius Caesar, who is said to have used it for secure battlefield
messages.

To implement a Caesar cipher with a \C\ program, note that, when
accessing individual characters in \C, what you are \qt{really} dealing
with are {\em numeric codes} for the characters.  As such, you
can do any normal arithmetic (addition, subtraction etc.) and comparison
(greater-than, less-than etc.) operations on them.

The relationship between the characters, as displayed on your screen or
in your editor, and the {\em numeric} codes accessed within your \C\
program is strictly {\em arbitrary}.  It is not specified by the \C\
language standard.  It is thus open to anyone developing a \C\ compiler
to adopt any character numbering scheme they like; you cannot reliably
assume that the numbering scheme in effect for one \C\ compiler will be
the same as for another.  Strictly, you need to check the documentation
for your particular compiler to find out what the numbering scheme is.

However: there is one particular numbering scheme which is the most
widely used, and to which {\em most} \C\ compilers conform (including
{\bf DJGPP}): this is the so-called {\bf ASCII} scheme.\footnote{If you
  {\em really} want to know, \qt{ASCII} is an acronym for {\em American
  Standard Code for Information Interchange}.}
In {\bf ASCII}, the upper case letters \tty{A} to \tty{Z} have
consecutive numeric codes from 65 to 90. Thus, given a particular key
value (a number from 1 to 25) simple addition will encypher a letter as
required\mdash except that if the sum is greater than 90 you must \qt{wrap
around} to the start of the alphabet again by subtracting 26.

You are required to develop a program which will input a series of lines
of characters, and encode them with a Caesar cipher; as each line of
plaintext is input, the corresponding line of ciphertext should be
output. It is up to {\em you} to devise a mechanism whereby the user can
indicate that all lines have been input, and to implement the program in
such a way that it will then terminate.

The key for the encoding should be \qt{hard coded} into your program (as
opposed to be being read in at run time).  Thus, changing the key will
involve modifying the source program and recompiling.

You may find it handy to be able to run your program on an input 
{\it file} (and producing an output {\it file}) rather than working only
with the keyboard and screen. Use \htmlref{command line
redirection}{redirection} to achieve this.

\subsection{Exercise 2: Crytanalysis (20\%)}

Now think about the problem of cryptanalysis: that is, suppose you {\it
are} \qt{the enemy} and have intercepted a transmission known to have
been encyphered with a Caesar cipher. How would you set about trying to
decipher it? You may wish to challenge a colleague in the class to see
who can decipher the other's ciphertext message most quickly. Record
your conclusions in your report.

\subsection{Exercise 3: The Vigen\`{e}re Cipher (30\%)}
\label{vigenere}
Finally develop a program to implement the somewhat more sophisticated
{\it Vigen\`{e}re} cipher, invented in the 16th century by Blaise de
Vigen\`{e}re. This has the same basic idea as the Caesar cipher, but the key
no longer stays the same throughout the message: instead it follows some
periodic cycle.  A Vigen\`{e}re key is thus not a single number but a
sequence of some fixed length\mdash say 10, 3, 25, which would mean the
first letter should be shifted by 10, the second by 3, the third by 25,
and then back to 10 again etc.

\section{Session 10: Week 20/21: {\em Letter Frequencies}}

In a world where there are code {\em makers} there will, inevitably,
also be code {\em breakers}.  One of the simplest tools in the armoury
of a code breaker is a program to count the relative frequency of each
letter appearing in the cyphertext. For any given language there will be
a characteristic distribution of letter frequencies in the uncoded
message (the \qt{plaintext}).  The most commonly used letter in English is
\tty{e}, by a wide margin; \tty{t} is in second place, with \tty{a} and
\tty{o} nearly tied for third; \tty{i}, \tty{n} and \tty{r} are also
very commonly used.

If we know that a coded message uses any kind of 
simple substitution cypher (such
as the Caesar cypher we saw previously) then a simple count of the
relative frequencies will allow us to make a fairly good guess as to the
letters which have substituted for the most common english letters.
Often this would be enough to allow the remaining substitutions to be
easily guessed.

Of course, {\em real} cyphers are much more sophisticated and harder to
break than this (how would you tackle a \htmlref{Vigenere}{vigenere}
cypher for example?).
But letter frequency counts still form an essential tool for code
breaking, albeit in conjunction with many other techniques.

Try to develop the programs for this session {\em without} using
\tty{safe-c}.  You should use 
\htmladdnormallink{standard library}%
{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/stdlib}
functions declared in \tty{stdio.h}
for doing input and output\mdash for example, use \tty{getchar()}
for reading in the input file and use \tty{printf()} for printing
out results. Use functions declared in \tty{ctype.h} for testing
(or possibly altering) the characteristics of character code data
(e.g.\ distinguishing alphabetic from non-alphabetic characters;
or changing between upper and lower case etc.).

\subsection{Exercise 1: Counting A! (30\%)}

Your first task in this session is to write a program which will
read a file, and count how many times the character \tty{A} (or
\tty{a}) occurs.  The program should ignore the distinction
between upper and lower case, and should ignore all characters
other than \tty{A} (and \tty{a}). When the file has been
completely read, the program should output the total number of
\tty{A} characters found.

\htmlref{Redirection}{redirection} should be used to cause the
program to read the appropriate file via \tty{stdin}.

As usual, you should test your program carefully, and document any
problems etc.\ in your report.

\subsection{Exercise 2: More Counting... (30\%)}

Now enhance your program to count how many times each separate
alphabetic character occurs.  Again, it should ignore
distinctions between upper and lower case, and should ignore all
non-alphabetic characters. So it should generate 26 distinct
count values, one for each letter of the alphabet, and not
counting non-alphabetic characters at all.

Note that you can use a single {\em array},
with 26 elements (where the elements
are of type \tty{int}, say), to hold all the counts.
You will need to think carefully about how to access the
correct position or slot in this array to get the
correct count for any given letter found in the file.

When the file has been completely read, the program should output a
table showing the count for each of the letters \tty{A} to \tty{Z}.

Again, you should test your program carefully, and document any
problems etc.\ in your report.

\subsection{Exercise 3: Statistics (20\%)}

Next you are required to enhance the program further so that it
will also calculate the {\em total} number of all alphabetic
characters read, and output, for each character, both the actual
number of times it occurred, and the {\em percentage} this
represents of the total number of alphabetic characters
encountered.

Again, test and document the program carefully.

\subsection{Exercise 4: Plotting a Histogram (20\%)}

Finally: develop a further version of the program, which, instead of
outputing the relative frequencies as {\em numbers}, outputs a {\em
histogram}.  This will be made up of lines of varying width (made up of
asterisk characters) one line for each letter, from \tty{A} to \tty{Z}.
The letter with the most occurrences should be scaled to give a line
with, say, 60 \tty{*}'s. Then the lines for all the others should
be shorter in proportion. The display might look somewhat as
follows:

\begin{verbatim}
 A *************
 B ******
 C **
 D ***
 E ********************
 F ******
 G *
\end{verbatim}

\mdash and so on.

Note that histograms would normally be plotted with the
independent variable oriented {\em vertically}, whereas I have
described an {\em horizontal} orientation here.  If you have
time, try to alter your program again, to yield a histogram with
a vertical orientation (this is a substantially more challenging
task).

\section{Session 11: Week 22/23: {\em Simulating an RC Circuit}}

The program(s) developed in this session 
must {\em not} use any facilities of the
\tty{safe-c} library\mdash they {\em must} rely on the 
facilities of the \htmladdnormallink{Standard C Library}
{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/stdlib}
instead.

Consider the following 
schematic diagram of a simple RC circuit:

\begin{figure}
\centering
\mbox{\epsffile[120 500 420 690]{rc.plt}}
\caption{Simple RC Circuit}
\end{figure}

The capacitor is assumed to be initially charged up to some
voltage denoted {\it v(0)}, corresponding to a charge level of:

\[ q(0) = C v(0) \] 

The switch is closed at time
{\it t = 0}.  The capacitor then discharges by causing a current
to flow through the resistor.

Denote the instantaneous signals in the system as follows:

\begin{itemize}

\item $q(t)$ : The instantaneous charge on the capacitor at
time {\it t}. 

\item $v(t)$ : the instantaneous voltage
across the capacitor at time {\it t}.

\item $i(t)$ : the instantaneous
current discharging from the capacitor through the resistor,
at time {\it t}.

\end{itemize}

Suppose that, at some time {\it t}, 
the value of {\it q(t)} is known. It then follows that
the following values may be calculated:

\[ v(t) = q(t) / C \]

\[ i(t) = v(t) / R \]

\[ \frac{{\rm d}q}{{\rm d}t} = -i(t) \]

Consider now what happens over a \qt{small} interval of time,
which I shall denote $\Delta t$. If this interval is \qt{small}
enough we can take the current to be approximately constant over
this interval.  Thus, the change in the value of {\it q} over this
interval can be approximated by:

\[ \Delta q \simeq -i \Delta t \]

and the value of {\it q} at the end of the interval 
can be calculated (approximately) as:

\[ q(t + \Delta t) \simeq q + \Delta q \]

Since we now know the value of {\it q}, one time \qt{step} later, we
can now repeat all the calculations to calculate the values of
{\it v, i} and $\Delta${\it q} one time step later also \mdash and thus
calculate how much {\it q} will change by over one {\em further}
time step.  And so on.  By repeating this procedure, one can
calculate the state of the circuit (at least approximately) into
the {\em indefinite} future, once we know the state at some
initial time.

In fact, this basic method is so powerful that it can be
extended to (approximately) predict the time behaviour of
arbitrarily complex electronic circuits under arbitrary
stimulation \mdash and such simulations are a crucial tool in
the design of all modern electronic circuits.

\subsection{Exercise 1: Basic Simulation Program (60\%)}

Develop a program which will \qt{simulate} the
behaviour of a simple RC circuit, in the sense of providing
predictions of how the charge on the capacitor will vary over
time.  

The program should prompt for and read in values 
for the following parameters from the user:

\begin{itemize}
\item $R$ : Resistance (in $\Omega$).

\item $C$ : Capacitance (in F).

\item $q(0)$ : {\em Initial} value of {\it q} (in C).

\item $\Delta t$ : The duration (in s) of one time \qt{step}.
(In practise, choose $\Delta t$ to be a small fraction\mdash
less than 1\% say\mdash of the circuit time constant, which
will be given by $\tau = RC$.)

\item  $T$ : The value of {\it t} at which the program should stop.

\end{itemize}

When the program is executed, it should print one line on the
screen for each time step. Each line should show the time and
the calculated value for {\it q(t)} at that time.

\subsection{Exercise 2: Enhanced Simulation Program (40\%)}

Now enhance your program in the following ways.  

Instead of automatically prompting for the required parameter
values, the program should offer the user a choice of reading
the values from the keyboard or from a file (which would have
been prepared in advance).  When the user opts for reading from
the keyboard, the program should prompt for, and read the
parameters just as before.  Where the users opts for a file, the
program should prompt for the file name, and then read the
parameter values from the file (without issuing any prompts). If
the program encounters any difficulty reading the parameters
from the specified file, it should offer the user a choice
between giving up, or respecifying the file to read from, or
reverting to reading the parameters from the keyboard.

Once the program has successfully got a set of parameter
values, it should offer the user a choice between output to
the screen, or output to a file.  Again, in the former case,
the program should continue as before; but in the latter
case, it should prompt for the name of the file to output
the results to.

\section{Session 12: Week 24/25: {\em Exploring Pointers}}

Note that in this exercise you are {\it not} required to generate any
new programs of your own\mdash though you may wish to modify the
programs you are given.

This exercise is concerned with exploring the use of pointers in \C.

Specifically, you will examine programs where pointer variables are
created using pointer data types.  Thus, for example:

\begin{verbatim}
    int i;
\end{verbatim}

declares a variable, \tty{i}, of type \tty{int}; whereas the
declaration:

\begin{verbatim}
    int *i;
\end{verbatim}

declares that \tty{i} is a variable of type \qt{pointer to \tty{int}} or
\tty{(int *)}.  That is, \tty{i} itself does not hold an \tty{int}
value, but the thing it points {\em at} does.

Note that you can happily declare variables which point at other pointer
variables.  Thus:

\begin{verbatim}
    int **i;
\end{verbatim}

declares that \tty{i} is a variable of type \qt{pointer to pointer to
\tty{int}}.  The {\em value} of \tty{i} is a pointer; the thing it
points at is now {\em another} pointer variable; but the thing {\em
this} points at is an \tty{int}. And so on!

A pointer value can be produced using the \qt{address-of} operator, denoted
with the ampersand character \tty{\&}.  Thus, the following code
fragment {\em might} make sense:

\begin{verbatim}
    int i;
    int *ptr;

    ptr = &a;
\end{verbatim}

The net effect is that \tty{ptr} now points at \tty{a}.

You can display a pointer value using the \tty{\%p} format
specification with \tty{printf()}:

\begin{verbatim}
    printf("Address of variable a is: %p\n", &a);
\end{verbatim}

With our particular computer platform, addresses can be
thought of as binary numbers with 32 bits.  By convention,
they are displayed by \tty{printf()} in {\em hexadecimal},
or base-16, notation (where the digits \tty{0} to \tty{9}
as used as normal, but the letters \tty{A} through \tty{F}
are used to represent the base-16 digits for the numbers
10 to 15). So a typical result from executing the \tty{printf()} 
above might be something like:

\begin{verbatim}
    Address of variable a is: 0xbbbfc893
\end{verbatim}

The \tty{0x} prefix is a standard C notation for showing that
a number is in hex; this is then followed by 8 hex digits
(since one hex digit represents a number between 0 and 15, it
is equivalent to 4 binary digits; so a 32 bit number is
equivalent to 8 hex digits).  In any case, your only use for
looking at pointer values will be to assess whether or not
different pointer values are {\em equal}\mdash and you can do
{\em that} without knowing any of the details of interpreting
hex notation.

A pointer value is dereferenced with the \qt{dereference}
or \qt{indirection} operator, denoted with the asterisk
character, \tty{*}.  A dereferenced pointer may be used
{\em anywhere a variable name can be used}.

Thus, normally, a variable name evaluates as the value of a
variable; so a dereferenced pointer normally evaluates as
the value of the thing pointed {\em at}.  But a variable
name can also be used in an assignment, in which case its
value is altered (overwritten); similarly, a dereferenced
pointer can be used in an assignment, and the value of the
thing pointed {\em at} will be changed.

Note very carefully that, whenever you are dealing with a
pointer variable, you must be very clear about whether it
is its {\em own} value that is being referred to, or the
value of the thing pointed {\em at}; these are generally
very different things (they are usually even of different
{\em types}, never mind values).

A simple use of dereferencing is this:

\begin{verbatim}
    int i, j, k;
    int *ptr;

    ptr = &i;
    i = 25;
    j = 2 + *ptr;
    *ptr = j + 2;
\end{verbatim}

In this simple fragment, there are two variables of type
\tty{int}, and one of type pointer to \tty{int}. The
variable \tty{ptr} is given the value \tty{\& i}, so it
points at \tty{i}; \tty{i} is given the value \tty{25}; so
when \tty{j} is given the value \tty{2 + *ptr}, this means
\qt{2 plus the value of the thing \tty{ptr} is pointing at}
and this evaluates as \tty{27}; finally, \tty{*ptr}, which
is to say \tty{i}, is given the value \tty{j + 2} which is
to say \tty{29}.

Take a copy of the file \hot{ptr0.c}{../src/ptr0.c}. This
is a basic test program for investigating the idea of
pointers. Note that this program (and all the other
programs introduced in this session) is totally {\em
contrived}.  It does not do anything useful whatsoever.  It
is intended purely as a vehicle for you to experiment with
\C\ pointer variables and pointer operations.

First analyse the program by hand, and predict what you
think the outcome will be. Record this analysis in your
report. Then execute it and test your predictions.  Add
extra \tty{printf()} statements as you deem necessary in
order to check the values of variables at different stages
during execution. If the results differ from your
predictions then test more carefully until you can explain
the discrepancies. Note your results in your report.

Repeat the procedure described above for the file
\hot{ptr1.c}{../src/ptr1.c}.

Now consider the file \hot{ptr\_net.c}{../src/ptr\_net.c}.

The is again a contrived program. It does not do anything
useful. It merely serves to illustrate some further ideas
on the use of pointers.

To understand this example you will first need some
elementary understanding of \C\ {\em structures}.  Only the
basic ideas will be introduced here. For more detailed
information consult a textbook.

The idea of a \qt{structure} in \C\ is that you can group a
number of distinct data items, of distinct types, together
into one unit.  That collection of data items can then (for
some purposes at least) be manipulated {\em as} a unit.  In
particular, having once described the \qt{format} or
\qt{shape} of the unit, one can declare, in a single step,
\qt{structured variables} which have separate slots for all
the constituent parts or {\em members}.  Look at this
simple example:

\begin{verbatim}
    struct
    {
      int age;
      double IQ;
    } barry, john, mary, henry, susan;
\end{verbatim}

\tty{struct} is a keyword which introduces the declaration
of structured variables. This is followed by braces which
enclose a detailed description of the members of each
structured variable.  Finally come the names of the actual
variables\mdash five of them in this case. The effect of this
declaration is to create five variables, {\em each} of
which has two distinct members, one called \tty{age} the
other called \tty{IQ}. To access these members we use the
\qt{dot} operator, thus:

\begin{verbatim}
    barry.age = 29;
    john.age = 40;
    mary.age = barry.age;
    john.IQ = 150.0;
\end{verbatim}

and so on. But we can also, to a limited extent, manipulate
a structured variable as a whole\mdash for example, by
assignment:

\begin{verbatim}
    henry = john;
\end{verbatim}

This would assign the values of the members of \tty{john}
to each of the corresponding members of \tty{henry} in
turn.  Thus, it would be exactly equivalent to:

\begin{verbatim}
    henry.age = john.age;
    henry.IQ = john.IQ;
\end{verbatim}

So far, so good. It should be clear that structures might
be useful whenever you have information that naturally
divides into groups or units with a certain similarity.

This next point is that, if you are using structures at
all, it is often handy to be able to declare structured
variables (or function parameters for that matter), having
a given shape (i.e. a given set of members) in several {\em
different} places in your program.  Now you can certainly
do this in the \qt{obvious} way by simply repeating the
detailed declaration of all the members in each different
place.  But it would be nicer if the compiler could let you
declare the shape once, and then refer back to it later.
And, fortunately, it does\mdash actually in a couple of
different ways.  But I will just show one:

\begin{verbatim}
    struct person
    {
      int age;
      double IQ;
    };
\end{verbatim}

This time I have put an identifier (\tty{person})
immediately after the \tty{struct} keyword, and before the
left brace.  This does {\em not} create a structured
variable called \tty{person}.  Instead, \tty{person} acts
as a tag or identifier for this particular shape of
structured variable.  Once I have given this declaration,
then, at any subsequent point in the program, I can use
simply \tty{struct person} as a shorthand for the full
declaration.  So I could write, for example:

\begin{verbatim}
   struct person barry, john, mary;
\end{verbatim}

This would then create variables \tty{barry}, \tty{john}
and \tty{mary} with the same shape as before.  Then
somewhere later on (or inside some other function) I might
write:

\begin{verbatim}
    struct person henry, susan;
\end{verbatim}

Be clear on the advantage of adding an identifier, such as
\tty{person} to a particular shape of structure: it just
saves having to re-enter the detailed description of the
shape in several different parts of a program.

One slight difficulty might be evident here: in reading a
program one can easily become confused between identifiers
such as \tty{henry}, which refer to actual variables, and
\tty{person} which simply identifies an abstract shape for
variables which {\em might} get declared at some stage.  It
would be ridiculous, for example, to try to refer to
\tty{person.age} because there is no such variable as
\tty{person}.  Rather, \tty{person} simply provides a name
for a {\em template} from which variables might be created. 
Once you get used to using structures this should not cause
any problem. Once you see the keyword \tty{struct} you will
expect to see it followed either by a left brace or a name
for a particular shape of structure.  But when you are just
starting off, it may be a good idea to adopt some kind of
systematic identifier convention\mdash i.e.\ to choose your
identifiers so as to clearly distinguish between those that
refer to actual variables and those that simply refer to an
abstract shape. One simple convention that I sometimes use
is to append \tty{\_s} (for \qt{structure}) to the end of
any identifier that refers to a structure shape.  So I
would actually use the identifier \tty{person\_s}.  But
note carefully that is only a convention: it has no
significance for the compiler at all\mdash it is purely a
device to remind a {\em reader} of what's going on.

OK, now we can declare a structure shape, and give it an
identifier; we can declare variables or parameters of that
shape; and we can access the members of such variables.  We
now join these ideas up with the idea of a pointer. 

Roughly speaking, we can embed, within a structured
variable, a pointer member that points at something else.
In particular, we can embed a member that can point to
another structured variable of the same type or shape.  And
once we can do that, we can create indefinitely large
networks of structured variables that are linked together
by pointers.  This turns out to be an immensely powerful
programming idea\mdash which, regretfully, we shall not be able
to pursue properly in this introductory course.  For now,
you simply have to take it on faith that this idea {\em is}
potentially useful.  The question for us is simply what
language features we need to use to do it.

At this stage, look again at the example program
\hot{ptr\_net.c}{../src/ptr\_net.c}. This first introduces the
declaration of the structure shape called \tty{bucket\_s}:

\begin{verbatim}
    struct bucket_s
    {
      struct bucket_s *black, *white;
      int quantity;
    };
\end{verbatim}

This says, simply, that any structure of this shape will
have three members, called \tty{black}, \tty{white} and
\tty{quantity}. The \tty{quantity} member is simply of type
\tty{int}; but \tty{black} and \tty{white} are pointers to
(other?) structures of the same shape. Of course, they do
not automatically point at any particular other structures:
but they {\em potentially} can, if suitable assignments are
made.

Four actual variables of this structured type or shape are
then declared:

\begin{verbatim}
    struct bucket_s n0, n1, n2, n3;
\end{verbatim}

{\em Each} of these will have the three separate members
already described.  They have been declared outside of any
function so they are visible and accessible to {\em all}
functions.

The rest of the program then involves setting up particular
linkages between these structures (via the \tty{black} and
\tty{white} members) and using these linkages to indirectly
access various members in different ways. I repeat that
none of this achieves any useful purpose: the only purpose
of the exercise is for you to test whether you have a
sufficient grasp of what's going on to be able to
accurately predict what members will be accessed in each
case.  There is one final facility of \C\ you need to
understand in order to to this: the so-called {\em arrow}
operator.  Consider this fragmentary program:

\begin{verbatim}
    struct person_s
    {
      int age;
      double IQ;
    };

    void main(void)
    {
      struct person_s barry;
      struct person_s *p;

      p = &barry;

      (*p).age = 44;

    }
\end{verbatim}

In this program there is a structured variable called
\tty{barry}, and a pointer variable called \tty{p}.  For
the purposes of the example, \tty{p} is made to point at
\tty{barry}, and then the \tty{age} member of \tty{barry}
is indirectly accessed via \tty{p}.  This is done with the
construction \tty{(*p).age}.  That is, \tty{p} is first
dereferenced using the \tty{*} operator; this yields the
thing \tty{p} points at (namely \tty{barry}), and the dot
operator is then used to access the \tty{age} member of
this structure. The parentheses around \tty{*p} are
necessary here because the dot operator takes precedence
over dereferencing by default. So if I simply write
\tty{*p.age}, the compiler thinks I want to first take the
\tty{age} member of \tty{p} and then dereference that. Now,
since \tty{p} isn't even a structured variable, and
therefore has no members at all (never mind a particular
one called \tty{age}) this cannot make sense, and the
compiler would simply generate an error.  But in more
complicated cases the compiler might not even diagnose the
error effectively.  Anyway, the point is that if you are
starting with a pointer, and you want to get at a member of
the object being pointed at by that pointer, then you must
use something like \tty{(*p).age}.  This is moderately
convoluted; worse still, it turns out that this kind of
operation or access is actually needed very commonly in \C\
programs that operate on complicated data structures.  The
\C\ language therefore provides a single operator, the {\em
arrow} operator, which {\em combines} the effects of
dereferencing {\em and} accessing a member of the structure
thus accessed. It is written like this:

\begin{verbatim}
      p->age = 44;
\end{verbatim}

But try to get clear that \tty{p->age} is simply shorthand
for \tty{(*p).age}: if you ever find the arrow operator
confusing, then try replacing it by the \qt{longhand}
version, with an explicit dereferencing and explicit dot
operator.

Now, with all that in mind (!) let's return to the final
part of the exercise, and the program
\hot{ptr\_net.c}{../src/ptr\_net.c}.

First try to draw out on paper the relationships between
the structures \tty{n0}, \tty{n1}, \tty{n2} and \tty{n3}
immediately after execution of the statement at line
\tty{77} (the invocation of the function
\tty{red\_connections()}). Do this by {\em analysing} the
program manually, {\em not} by {\em executing} it.  The
diagram should show graphically what each pointer member of
each structure is pointing at.

Next attempt to predict the values of the \tty{quantity}
members of each structure immediately after execution of
the statement at line \tty{78} (the first invocation of the
function \tty{massage()}).  Check your predictions by
executing the program (you'll have to add some \tty{printf()}
statements to print out the values you are interested in). 

{\em Explain any discrepancies.}

Note that I really do mean that\mdash do not go any further
unless and until you can explain all discrepancies between
your predictions and the actual results.

Now draw a new diagram showing the relationships between
the structures immediately after execution of the statement
at line \tty{79} (the invocation of the function
\tty{blue\_connections()}). Repeat this diagram one last
time for the situation immediately after execution of the
statement at line \tty{80} (the invocation of the function
\tty{yellow\_connections()}).

Finally, predict the values of the \tty{quantity} members
of each structure immediately after execution of the
statement at line \tty{81} (the second invocation of the
function \tty{massage()}).  As before, check your
predictions by executing the program, and explain any
discrepancies.

\section{Copyright}

This Hypermedia Document is copyrighted, \copyright\ 1994--1996, by
\hot{Barry McMullin}{http://www.eeng.dcu.ie/\%7Emcmullin/home.html}.

Permission is hereby granted to access, copy, or store this work, in
whole or in part, for purposes of individual private study only. The
work may {\em not\/} be accessed or copied, in whole or in part, for
commercial purposes, except with the prior written permission of the
author.

\begin{latexonly}
\newpage
\appendix
\section{Listing 1: {\tt mquiz0.c}}

\small
\begin{verbatim}
#include <safec.h>

viod Main(void)
{
  string_type albums;
  string_type name;
  boolean_type asking;

  put_string("Welcome to mquiz0!\n");
  put_string("What is your name?\n");
  get_string(name);
  put_string("Hello ");
  put_string(name);

  asking = TRUE;
  while (asking)
  {
    put_string("Here is your question:\n")
    put_string("What was the best album of all time?\n");
    get_string(album);
    if (string_equal(album, "Dark Side of the Moon\n"))
      put_string("Yes - you are obviously an expert!\n);
      ask = FALSE;
    else
      put string("No - don't you know *anything*?\n");
  }
}     
\end{verbatim}

\newpage
\section{Listing 2: {\tt circle0.c}}

\small
\begin{verbatim}
#insert <safe-c.h>

void main(void)
{
  floating_point_type radius, string_type s;

put_string("What is your name? "); get_string(s);
  put_string("Hello ")
    put_string(s);
  put_string(
"Please enter the radius (in m):");
  get_string(s);
    radius == string_to_floating_point(s);
  floating_point_to_string(s, radius * 6.28319);
put_string("The circumference is: ");
    put_string
(s);put_string
(" meter(s)/n");
  floating_point_to_string(s, 3.41457 * radius);
    put_string("The area is: ");
      put_string(s);
        put_string(" meter(s)/n");}
\end{verbatim}

\newpage
\section{Listing 3: {\tt ptr0.c}}

\small
\begin{verbatim}
/*
  ptr0.c


  B.McMullin
  30th April 1996.
*/

#include <stdio.h>

void main(void)
{
  int i,j,k;
  int *p, *q, *r;
  int **s, **t, **u;

  i = 7;
  j = 23;
  k = i * j;

  p = &k;
  q = &i;
  r = p;
  
  *r = k;
  *p = (*p + *r) * 5;
  i = *(&j);

  s = &q;
  u = &p;
  t = s;

  p = *t;
  *p = **u * i;
  **s = i + j + k;
  j = 0;
  r = p = &j;
  s = &r;
  t = s;
  u = &p;
  p = &k;
  **u *= (*p * **s) * (i * j * k);

  /* What are the final values of i, j, k? */

/*
  printf("i = %d\n", i);
  printf("j = %d\n", j);
  printf("k = %d\n", k);
*/
}
\end{verbatim}

\newpage
\section{Listing 4: {\tt ptr1.c}}

\small
\begin{verbatim}
/*
  ptr1.c

  B.McMullin
  30th April 1996.
*/

#include <stdio.h>

void main(void)
{
  int i, j, k,
      *p, *q, *r, *s,
      **t, **u, **v;

  i = 0;
  p = &k;
  q = &i;
  r = &j;
  s = r;
  t = &q;
  u = &p;
  v = &s;
  j = *q;
  k = j;

  while ((j <= 15) && (j >= -15))
  {
    j++;
    s = r;
    r = q;
    q = p;
    p = s;
    v = u;
    u = t;
    t = v;
    (**t)--;
    (**u)++;
  }

  /* What are the final values of i, j, k? */

/*
  printf("i = %d\n", i);
  printf("j = %d\n", j);
  printf("k = %d\n", k);
*/
}
\end{verbatim}

\newpage
\section{Listing 4: {\tt ptr\_net.c}}

\small
\begin{verbatim}
/*
  ptr_net.c

  A test program illustrating structures and pointers.

  B.McMullin, February 1993.

*/

#include <stdio.h>

struct bucket_s
{
  struct bucket_s *black, *white;
  int quantity;
};

struct bucket_s n0, n1, n2, n3;

void red_connections(void)
{
  n0.black = &n1;
  n0.white = &n3;
  n3.black = n0.black;
  n3.white = &n0;
  n1.white = NULL;
  n1.black = &n2;
  n2.white = n3.black;
  n2.black = n1.white;
}

void blue_connections(void)
{
  n0.white = &n1;
  n1.black = &n0;
  n0.black = n0.white->black;
  n1.white = n1.black->white;

  n2.black = &n3;
  n3.black = &n2;
  n2.white = n2.black->black;
  n3.white = n3.black->white;
}

void yellow_connections(void)
{
  struct bucket_s *p;

  p = n0.white;
  n0.white = n1.white;
  n1.white = n2.white;
  n2.white = n3.white;
  n3.white = p;

  p = n0.black;
  n0.black = n1.black;
  n1.black = n2.black;
  n2.black = n3.black;
  n3.black = p;

}

void massage(void)
{
   n0.black->quantity = 2 * n3.white->quantity;
   n1.black->quantity = 2 * n2.white->quantity;
   n0.white->quantity = 2 * n2.quantity;
}

void main(void)
{
  n0.quantity = 2;
  n1.quantity = -3;
  n2.quantity = 4;
  n3.quantity = -5;

  red_connections();
  massage();
  blue_connections();
  yellow_connections();
  massage();

/*
  printf("n0.quantity: %d\n", n0.quantity);
  printf("n1.quantity: %d\n", n1.quantity);
  printf("n2.quantity: %d\n", n2.quantity);
  printf("n3.quantity: %d\n", n3.quantity);
*/
}
\end{verbatim}

\end{latexonly}


\end{document}

