<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">% swe1root.tex
%
% Course 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.
% Last edited: 27th February 1995.

\documentstyle[html]{article}

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

\begin{document}

\title{Software Engineering 1: Course Notes}
\author{Barry McMullin}
% \date{October 1994}
\maketitle

This is the online hypermedia documentation for the course {\em
Software Engineering 1}.

This is a required course for all students enrolled on Stage~1 of
the
\htmladdnormallink{B.Eng.\ (Electronic Engineering)}
{http://www.eeng.dcu.ie/eenghome/ee_info/ee_info.html} or
B.Eng.\ (Telecommunications Engineering) programmes
offered by the
\htmladdnormallink{School of Electronic Engineering}
{http://www.eeng.dcu.ie/eenghome/eenghome.html} of
\htmladdnormallink{Dublin City University}
{http://www.compapp.dcu.ie/DCU_home.html}.

\htmladdimg{at_work.gif} These online notes are under construction, and
will be incrementally extended and corrected as the year progresses.
Thus, early in the year you will find many sections to be empty, but
these will be filled out as we reach the relevant stages in the course.

\section{Introduction}

The course provides an introduction to {\it Software
Engineering\/} - which is to say the skill of developing {\em
software\/} or {\it programs\/} for digital computers.

The vast majority of modern technological products - from
dishwashers to communications satellites, CD players to
industrial robots - include at least one, and often many more,
embedded {\it microprocessors}.  A microprocessor is the central
processing component of a general purpose computer, implemented as
a single integrated circuit (IC).  The specific behaviours or
functionalities of the completed product are then realised by
providing these microprocessors with appropriate sequences of
instructions, or {\it software}. Software is thus a crucial
foundation for virtually all modern technological products - and
software development is an essential and pervasive skill for
every engineering discipline. This is reflected in the design of
the engineering programmes in DCU, where Software Engineering
takes a prominent role all stages - beginning with this
very important introductory course.

The objective of the course is that, on completion, you
should be able to design, code, test and debug small, but
complete, programs. The course introduces a modern high level
procedural language (ANSI C), supported on a general purpose
computing platform (ISA hardware, running MS-DOS and MS-Windows).

The course is preparatory in nature, providing necessary
foundations for a variety of courses in subsequent stages of the
relevant programs.

\section{Syllabus}

(Subject to revision.)

\begin{description}

\item[Background:] Introduction to stored program digital
computers.  Historical perspectives.  The nature of software
engineering: issues of cost, reliability and efficiency. The
von~Neumann architecture, and the idea of a sequential machine.
Evolution of computers and programming languages.

\item[Characters and Text:] Computerised text. Characters and
character sets. The 7-bit ASCII character set. Text files. Text
editing. Directories. Text files as computer programs: the
concepts of translation, execution, and debugging. The use of
an Integrated Development Environment (IDE).

\item[Identifiers:] Concept of {\it identifiers}. File and
directory names as identifiers. Identifier uniqueness. Syntax of
identifiers in \C\ programs. Reserved identifiers
in \C\ (keywords). Conventions and guidelines on identifier usage.

\item[Data:] Concepts of data type, constants, and variables.
Type \tty{int}. \tty{int} constants and range. Declaring
variables.

\item[Operators:]
Arithmetic operators:
\tty{+} (addition),
\tty{-} (subtraction),
\tty{*} (multiplication),
\tty{/} (quotient),
\tty{\%} (remainder).
Negative operands: direction of quotient truncation and sign of
remainder. Exceptions: overflow and divide-by-zero. \tty{int}
values corresponding to "truth" and "falsehood".
Equality operators:
\tty{==} (equal to),
\tty{!=} (not equal to).
Relational operators:
\tty{&gt;} (greater than),
\tty{&gt;=} (greater than or equal to),
\tty{&lt;} (less than),
\tty{&lt;=} (less than or equal to).
Logical operators:
\tty{\&amp;\&amp;} (AND),
\tty{||} (OR),
\tty{!} (negation).

\item[Expressions:] Forming expressions. Concept of expression
evaluation. Sequential nature of expression evaluation. Order of
evaluation: operator precedence and associativity; forcing
associativity with parentheses.

\item[Assignment:] The concept of assignment. Operator side
effects. The assignment operator (\tty{=}): evaluation and side
effects. Increment (\tty{++}) and decrement (\tty{--}) operators.
Type \tty{unsigned int}; type conversion.

\item[Programs:] Skeleton structure of a \C\ program: the {\tt
main} function. Declarations and statements. Comments. The
concept of flow of control. Types of statements: expression, {\tt
if}, \tty{if-else} and \tty{switch} statements. Compound
statements. The idea of iteration and the \tty{while} statement.
Symbolic constants and \tty{\#define}. Input and output by direct
modification and examination of variables within an Integrated
Development Environment. Monitoring execution: tracing and
breakpoints.

\item[Development Cycle:] Specification. Algorithm design.
Coding. Compilation and linkage. Testing: selection of test
cases. Exception handling. Defensive design. Debugging.

\end{description}

\section{Instructors}

The lecturers for the course are
\htmladdnormallink{Dr.\ Barry McMullin}
{http://www.eeng.dcu.ie/\%7Emcmullin/home.html},
and {\it Ms.\ Fiona Lodge}.

The laboratory demonstrator for the Tuesday sessions is
{\it Fiona Murray}, and for the Thursday sessions, {\it Feargal Costello}.

\section{Textbook}

The course is designed around the textbook:

\begin{quote}
  {\bf Illustrating C (ANSI/ISO Version)}\\
  {\it Donald Alcock}\\
  Cambridge University Press, 1992.
  ISBN: \tty{0-521-46821-3}
\end{quote}

The cost is approximately IR\pounds~14.

\begin{quote}
This is a required course text. Every student enrolled
on the course {\it must\/} acquire a copy of this book.
\end{quote}

\section{Lectures}

Chapter and page numbers relate to the assigned textbook.
% The course materials are scheduled so that the complete textbook
% should be covered once over terms~1 and~2 (lectures 1--20). Term~3
% (lectures 21--26) is currently reserved for revision of the complete
% course, and is not scheduled in detail. In any case, this
% schedule may be adjusted as necessary.

\subsection{General Comments on Lectures}

I find the subject of software engineering endlessly
fascinating, and get a great kick out of successfully solving a
programming problem. The down side is that this subject can be
almost equally endlessly annoying and frustrating, particularly
when you are trying to come to grips with it for the very first
time.  This course has been evolving over the past several years,
but one basic principle has remained constant: I see my role not
as a teacher or instructor, but as a {\it facilitator}.

The reason is that software engineering is a subject which is
dominated by {\it doing}. It cannot be primarily learned by
listening or reading, though both of these can play a subsidiary
role; it must be learned by taking control, and {\it doing}. The
frustration of the subject lies in the fact that, particularly at
first, this doing is necessarily uninformed and feels very much
like thrashing around in the dark - and will frequently end in
failure; but the joy lies in the fact that the failures are
always ultimately understandable and correctable - and
this understanding and correction delivers tremendous satisfaction.

Given this emphasis on doing, I consider the time you will spend
in the laboratory (both scheduled lab sessions, and private study
time) as being the most central and important component of the
course. Nonetheless, a small lecture component is still useful to
complement this practical work, and to provide overall structure
and {\it pacing\/} to the course.

There are two scheduled lectures and one tutorial each week. In
practise, I expect all three sessions to be tutorial in nature. This
reflects an increasing emphasis on active, personal, study time. The
lectures will closely follow the textbook. I work on the assumption that
you will have studied the assigned material in the textbook, and the
related notes provided here, {\it before\/} each lecture. In this way
the lecture sessions can be interactive in nature.

Note that attendance at lectures for this course is not monitored. It is
entirely under your own control and discretion.

Delivering the lectures on this basis has several significant
advantages:
\begin{itemize}
\item I am relieved of the tedium of presenting extensive,
repetitive, and usually rather boring, notes in the lectures.
\item Perhaps more importantly, you are freed of the tedium (not
to mention writer's cramp) of transcribing them.
\item The lectures can be used to allow discussion,
clarification (and sometimes even correction!) of the textbook
material. Further, should you choose to play an active role in
the lectures, they can be used to explore those topics which you
find particularly interesting or difficult in more detail.
\item Since all the written materials for the course are
available to you independently of attendance at lectures, you can
decide for yourself whether or when it is worth your while to
attend the lectures.  For example, if you happen to already be
proficient in certain aspects of software engineering, and are
satisfied that you completely understand the assigned materials,
then you may well decide to miss certain lectures and allocate
the time for some other, more pressing, studies. However, I recommend
that you adopt this position only with {\it extreme caution!}
\item Conversely, should you miss a lecture for some reason
outside your control, or otherwise fall behind in the course,
then because the written materials are all available to you, and
the schedule is explicitly laid out in advance, you will have the
flexibility to schedule in extra study time to make up.
\end{itemize}

In summary, my intention in designing this course is to {\em
empower\/} you, the student. That is, I hope that you will be
able to enjoy and benefit from this course precisely in
proportion to the energy and effort you are willing to invest in
it. No more, no less.

% \subsection{Newsgroup: \tty{dcu.eeng.teaching.swe-01.lectures}}

% \atwork

% The local newsgroup \tty{dcu.eeng.teaching.swe-01.lectures} is
% set up specifically for the discussion of topics directly relating to
% the course lectures. This includes both administrative notices
% (e.g.\ if a lecture has to be rescheduled or relocated) and
% technical questions to do with the course content.  I would
% particularly encourage you to post queries or questions relating
% to the scheduled lecture materials {\it in advance\/} of each
% particular lecture; I will review this newsgroup shortly before
% the lecture, and can thus response to your queries in as timely a
% manner as possible. Having said that, you should, of course, also
% use the newsgroup to post comments (and/or criticisms, questions,
% etc.) after each lecture, particularly where you might feel that
% an answer I have given in the lecture is still obscure or
% inadequate.  For my part, I intend to use the newsgroup to respond to
% such postings, and also, where appropriate, to continue
% discussions which could not be completed within the lecture time.

\subsection{Term 1: Weeks 1--10}

\subsubsection{Weeks 1--2: Background}

The course is introduced with background discussion of computers,
computer programming, and some demonstration of particular computer
tools which will be used during the course.

\subsubsection{Week 3--4: Chapter~1 pp.~1--10}

\paragraph{Overview}

Chapter 1 is short, but very important. If you can successfully
master it, and complete its one associated exercise (p.~10)
then you will have laid down an excellent foundation for tackling
the substantive topics which will follow - and they will follow
very quickly indeed! Conversely, if you experience any difficulty
with anything in this chapter, this is your
opportunity to get your questions answered quickly.

In brief, chapter~1 introduces a problem (the calculation of
repayments on a loan) which can be solved "by hand" (i.e.\ by
manual calculation), but which can more conveniently be solved by
programming a computer, in a suitable language, "once and for
all".  The bulk of the chapter is then concerned with presenting
and dissecting such a program, written in \C.

\paragraph{First Step: Understand the problem!}

\begin{quote}
\ldots\ I think that there is only one way to science - or
to philosophy, for that matter: to meet a problem, to see its
beauty and fall in love with it; to get married to it, and to
live with it happily, till death do ye part - unless you should
meet another and even more fascinating problem, or unless,
indeed, you should obtain a solution.  But even if you do obtain
a solution, you may then discover, to your delight, the existence
of a whole family of enchanting though perhaps difficult problem
children for whose welfare you may work, with a purpose, to the
end of your days.

\begin{quote}
Realism and the Aim of Science\\
Preface 1956, p.~8\\
{\it Karl Popper}
\end{quote}
\end{quote}

Your first step in tackling any software engineering project is
to ensure that you fully understand the statement of the problem.
Indeed, many senior software engineers (classified as {\em
Systems Analysts\/}) specialise in nothing {\it but\/} clearly
stating the problems to be solved by software systems!

Alcock presents a formula for calculating loan repayments.  Ask
yourself do you {\it believe\/} this formula before going any
further. If you {\it do\/} believe it, try to say exactly {\em
why}.  In any case, try to {\it test\/} the formula in any way
you can dream up.  You may not be able to prove that it is
definitely {\it right}, but you should be able to think of at
least some {\it partial\/} tests which it should pass. For
example, does it give the correct answer for the limiting case of
the principle being \pounds 0? Can you think of any other
comparable tests?

Next, actually carry out the sequence of instructions which
Alcock lists on p.~2, for at least a few different cases. Carry
out these instructions as exactly and literally as you possibly
can (you will need to get a friend to act as the "client", and
then alternate roles).  If you find anything in the instructions
which you think is obscure or ambiguous - which you cannot
immediately see how to carry out - then make a note of it.
% and post a query on the lectures newsgroup.

\paragraph{What's a "high-level" computer language?}

The next sections of the chapter present a \C\ program to make a
computer carry out, in effect, the same sequence of actions to
calculate loan repayments.  Note that essentially the
same \C\ program will work on practically any computer. This is a
key advantage of using a so-called "high-level" language - it
can be automatically translated or "compiled" into a form which
can be executed on practically any computer.  However, the
precise procedures for entering the program, and arranging for it
to be translated and executed will generally vary from computer
to computer.  For this reason, Alcock cannot and does not give
detailed instructions for how to do this; however, you are
given the appropriate detailed instructions, for the computers
which you will be using, in the notes for
\htmlref{Laboratory Session 2}{lab2}.

Alcock next dissects this simple program in great detail, to
explain, at least in a superficial sense, what its components
are, and how they are interpreted by the computer.  Ask
yourself at this point if you can explain why a {\it special\/}
language such as \C\ is necessary at all - why can the computer not
simply understand the original instructions written in English on
p.~1?

\paragraph{Watch for the new technical terms!}

Note that Alcock introduces a variety of technical terms in this
chapter - such as {\it directive}, {\it block}, {\it statement}
etc.  He generally italicises such technical terms on the first
occasion on which they are used. This specialised technical
language is very important in this subject - as, indeed, it is in
most other engineering subjects; if you do not realise which
terms are being used with specialised meanings, and what those
meanings are, from the very start, then you will quickly find
that you are becoming very confused.

So, I suggest you acquire a notebook to use exclusively as a glossary
for the duration of this course. Organise it alphabetically.  Each time
you come across a word which seems to be used in a special technical
sense, write it in, together with a definition in your own words, and an
example or two.  You may well have to go back over certain definitions
at various times, and revise or correct them - but that is perfectly OK.
If there are words that seem to have a technical meaning, but you cannot
quite see what the meaning is, then \htmlref{e-mail}{feedback} a question,
or ask in the lecture.

Start constructing your glossary now, by going through the
whole of Chapter~1 carefully.

\paragraph{Caution: On Program Style}

In dissecting the initial example program Alcock comments that:
\begin{quote}
  "You have complete freedom of layout. Statements may be typed
  several to a line, one per line, one to several lines."
\end{quote}

His point here is that as far as the computer - or more
precisely, the \C\ compiler - is concerned, many details of
layout or formatting of the program are irrelevant. This is true.
However, you should notice that programs have effectively two
parallel, but quite distinct, purposes:

\begin{enumerate}
\item To represent a suitable sequence of instructions which
(after compilation) the computer can execute to accomplish some
task. This is the role which Alcock explicitly recognises and
discusses.
\item To {\it document\/} that set of instructions so that some
{\it person\/} can understand how the computer is accomplishing
the task. This becomes vitally important whenever it is necessary to
modify or extend the behaviour of a program - or to correct
previously undetected malfunctions.  Alcock does not explicitly
refer to this purpose of the program at all.
\end{enumerate}

It should be clear that, in its role as {\it documentation\/} for
another human being, the details of layout and formatting of a
program are {\it very\/} important. A poorly formatted program
may be perfectly "correct" - in the sense of generating the
correct answers to the problem at hand - but may be virtually
impossible for a human being (even the original author) to
decipher if it becomes necessary to enhance it (or even to decide
whether it may malfunction in certain circumstances).

Another aspects of program design which is similarly constrained
is the choice of {\it identifiers\/} - names for variables and
other objects which the program uses.  The computer is largely
insensitive to particular identifiers, as long as, in each
context, they unambiguously identify the "correct" object. In
particular, the computer does not care whether an identifier is
"meaningful" in human terms.  The names \tty{P}, \tty{Principal}
and \tty{bZ34ywT} are all equally valid to the
machine, as along as they are used consistently (unambiguously).
However, the net effect if entirely different from the point of
view of someone trying to understand how the program works. So
try to get into the habit, from the very start, of taking care
with the formatting and layout of your programs, and with your
choice of identifiers. These things may not directly affect the
functioning of your program, but they will seriously affect how
long it actually takes you to get the program working
satisfactorily!

\subsubsection{Week 5--7: Chapter~2 pp.~11--19}

\paragraph{What's all this about "Boolean" variables?}

Alcock is at pains to point out that \C\ does {\it not\/} support
"Boolean" variables. What does this mean?

Well, certain other programming languages (notably {\it Pascal\/} and
its descendants) support a special kind of variable which can only
hold or be assigned one of {\it two\/} distinct values - usually
referred to as \tty{TRUE} and \tty{FALSE}.\footnote{These are
  called "Boolean" variables in reference to the notable 19th
  century mathematician {\it George Boole}. Boole's greatest work
  was entitled {\it An Investigation of the Laws of Thought on
  Which Are Founded the Mathematical Theories of Logic and
  Probabilities}, published in 1854. Boole reduced logic (the
  analysis of the truth or falsity of complex propositions) to a
  simple algebra, thereby incorporating logic into mathematics.
  Boole's two-valued, or binary, algebra is the simplest form of
  his more general {\it boolean algebra}.}
Now Boolean variables would be quite different in kind from the
numeric variables we have seen so far in \C. Admittedly, as we
shall see in more detail later, the total number of distinct values
that can be accommodated in any type of \C\ variable
(such as type \tty{int} or type \tty{float}) is always {\it finite},
but it is still much bigger than two!

So why are we worried about all this anyway?

Well, it turns out that, in many programs, it is desirable for
the program to have a "choice" of things to do, depending on a
variety of factors that only become known when the program is
actually executing.  In effect this means that we want the
program to be able to evaluate some proposition or condition and
classify it as being "true" or "false".

To allow this, a programming language normally provides operators
to test or compare various conditions - such as whether certain
numbers are equal, or one is greater than the other etc.  If the
language supports Boolean variables as such, then the result of
applying or evaluating such an operator would be one of the
Boolean values normally denoted \tty{TRUE} or \tty{FALSE}. In
\C\ however, there is no special Boolean data type, so, instead, the
so-called {\it logical\/} operators simply generate {\em
numeric\/} results, with the number \tty{0} being
interpreted as signalling "false" and the number \tty{1}
signalling "true".\footnote{Technically, the result of applying
  a \C\ logical operator is of the particular \C\ numeric data
  type called \tty{int}.}

The {\it logical\/} operators would never generate any value
other than \tty{0} or \tty{1}. However, where, in effect, a
Boolean value is examined or used for some purpose in a \C\
program, {\it any\/} \ \tty{int} value may be introduced, with the
convention that all non-zero values (including \tty{1} of course)
are classified or interpreted as meaning "true".

\paragraph{Making a statement!}

Now that we have some logical operators available to us, how can
we use their results to control the flow of execution in a
program?

The answer is that there are special kinds of \C \ {\em
statement\/} where the exact effect of the statement can depend
on a value generated at execution time (usually by a logical
operator). But what {\it is\/} a "statement" anyway? Let's back
up and review the concept a little.

We have seen examples of \C\ "statements" already, in the
introductory chapter; they were things like:

\begin{verbatim}
  R = Rpct / 100;
\end{verbatim}

or:

\begin{verbatim}
  printf("\nEnter: Principal, Rate%, No. of yrs.\n");
\end{verbatim}

These are all what we might term "simple" statements:
they are the components of a program that are carried
out, in sequence, when the program is executed. Technically,
these particular statements are all examples of what are called
{\it expression\/} statements: that is, as we shall see later, we
can always think of the execution of these statements as
involving, in effect, the evaluation of an "expression".

In any case, the "statement" notion is much broader than is
accommodated by just expression statements.  We shall see other
more complex kinds of statement shortly. But first note that
statements in general should be distinguished from the other
major "kinds" of program component. As well as statements,
other program components we have seen are {\it comments}, {\em
preprocessor directives}, and {\it declarations}.

{\it Comments\/} are simple pieces of text delimited by the
special tokens \tty{/*} and \tty{*/} which are ignored by the
compiler, but serve to provide some additional information to a
{\it person\/} reading the program:

\begin{verbatim}
/* WOTCOST; Computes the cost of a loan. */
\end{verbatim}

{\it Directives\/} are the components of a program signalled by the
\verb%#% character. They are special instructions which
control the way the rest of the program is translated or
compiled; we say that they play a role only at "compile time".
The only example we have seen so far is the
\verb%#include% directive - e.g.\ as follows:

\begin{verbatim}
  #include &lt;stdio.h&gt;
\end{verbatim}

Its effect is to tell the compiler to also compile an extra
separate file (in this case, one called \tty{stdio.h}) as an
integral part of the compilation of our own file.

{\it Declarations}, roughly speaking, "prepare the ground" for
statements to be subsequently executed. So far, the only
declarations we have seen have been concerned with {\it creating
variables\/} with given names and types, e.g.\ as follows:

\begin{verbatim}
  float P, Rpct, R, M;
\end{verbatim}

Recall that declarations and statements can act as {\em
sub-\/}components: in particular, they may be combined to form a
{\it block\/}, by enclosing them within braces; and a block, in
turn, can form part of a {\it function definition}. This notion of
{\it hierarchical structure}, with components within components
within components, is a very important and pervasive one in the
design of all complex engineering systems.

For now, note that technically a block is, itself, regarded as a
special kind of {\it statement}. In fact, it is also
alternatively referred to as a {\it compound statement}. The
significance of this is that anywhere in a program where it is
"grammatically" (or "syntactically") legal to place a
"simple" statement then it will also be legal to put in a whole
block, comprising an indefinitely large group of declarations and
statements. It follows, logically, that a block may itself be a
component of a larger more encompassing block and so on! Granted,
there is no obvious reason why this might be useful yet, but
we'll get there in due course!

\paragraph{Branching and Looping}

So far we have two kinds of statement: "expression" statements,
and "block" or "compound" statements. Expression statements
are just executed. The (simple) statements within a block are
executed in simple sequence.  As yet we have no way of making the
execution of a program depend on, or vary in sympathy with, a
logical value determined at execution time.

There are two principle kinds of variation we typically might
want: branching (or, as Alcock says, {\it selection\/}) and
looping.  In branching we have {\it alternative\/} things we
might want our program to do; in looping we want to do a
particular thing {\it repeatedly\/} - over and over again.  \C\
provides several different ways of achieving both of these
effects; but for the time being, it is sufficient to have at
least one way of doing each in our \C\ armoury, and that is what
Alcock now introduces. He presents the \tty{if - else} kind of
statement to achieve branching, and the \tty{for} statement to
achieve looping or "iteration".

Examine the formats which Alcock specifies for the \tty{if-else}
and \tty{for} statements very carefully. Notice that, in each
case, the statement format contains one or more other statements
as {\it components\/} nested within it. In the case of an {\tt
if} statement, the nested statement is to be executed if and
only if the {\it expression} value fed into the \tty{if} is
"true" (non-zero); in the case of \tty{if-else} exactly one or
the other of the nested statements will be executed depending on
whether the {\it expression\/} is classified as "true" or
"false"; and in the case of the \tty{for}, the nested statement
is what gets executed repeatedly.

\begin{quote}
{\it My point here is to draw your
attention to the fact that the nested statement is grammatically,
or "syntactically", allowed to be any kind of statement at
all.}
\end{quote}

So, as Alcock shows in his example, the statement nested within
an \tty{if} can, itself, be another \tty{if} statement (complete
with a further, nested, statement); equally, the nested statement
could be a \tty{for} statement or, indeed, a {\it compound\/}
statement. The latter means that, with one \tty{if} statement, we
can control execution of a whole block of statements - simply by
enclosing them in braces to make a single compound statement.

Furthermore, the nesting of statements within statements can, in
theory, be made as deep as we like!  However, in practice,
programs get rather difficult for human beings to understand if
statements get nested {\it too\/} deeply within each other - so
don't get carried away with this!

\paragraph{A Shady Character?}

A computer clearly has to be able to deal with "text" as
well as "numbers", if we are going to use it for general
purpose information processing.  We need to be able to print out
headings, or textual prompts at the very least. More generally,
we want to be able to carry out "processing" on textual
information: sorting, searching, formatting etc.

Text is ultimately made up of basic components we call {\em
characters}.

But what exactly counts as a "character"?

In the English speaking world we tend to be happy with upper and
lower case alphabetics, some digits, and a selection of
miscellaneous brackets, punctuation, and other "special"
characters. Even that still leaves room for tremendous variety in
{\it style} and {\large size}.

But to handle text in most languages of the European
Union we need to add a large variety of {\it accented\/}
characters (\'{a}, \"{u}) etc.; and if we move further afield,
things get even more complicated: in the middle East we need
arabic and hebrew alphabets, in the CIS we need (at least) the
cyrillic character set, and in the far East we need even more
elaborate character sets to handle Japanese, the various kinds of
Chinese, and so on.

Further, if we want to deal with mathematical notation, we
need to be able to deal with things like sub- and super-scripts
($x^{y_1}$), and so forth.

So what should count as a "character", or even how many
"distinct" characters we might want to deal with, is a fairly
difficult question to deal with.

However, we have to start somewhere!

In the case of computers, the start was historically based on
good old fashioned typewriters, or, more strictly, {\em
teletypewriters}. Teletypewriters, or teletypes, were automatic
electric typewriters which could be remotely hooked together, so
that whatever was typed on one was automatically printed on the
other also. In the early days of computers, teletype machines
were already fairly freely available, and were a convenient
mechanism for both keying input information into a computer, and
for printing output information from the computer.

However, it was in the nature of teletype technology that they
could only support a rather limited range of characters:
typically just the upper and lower case roman alphabet, digits 0
to 9, and a variety of "special" characters. Furthermore, if
these devices were to work properly with each other it was
essential that they all adhere to some single {\em
standard\/} - both for the characters to be supported, and the
way they should be encoded (something akin to the "dots" and
"dashes" of the earlier {\it Morse\/} code).

A set of just 96 such characters, plus 32 non-printable
"control" characters, together with a standardised
way of encoding these into electrical impulses (as strings of
"highs" and "lows", or "ones" and "zeros" - i.e.\ binary
numbers) was therefore devised, and became a {\it de facto\/}
standard, known as the {\it American Standard Code for
Information Interchange}, or \tty{ASCII} for short.

Because it only allows 96 characters, based on the roman
alphabet, \tty{ASCII} is very limited.  It doesn't include any
accented characters, or even the \pounds\ sign. It doesn't allow
for variations in size, or style. It can't deal properly with
mathematical notation. And it does not address non-roman
alphabets at all.

Nonetheless, \tty{ASCII} has become a sort of "lowest common
denominator" or {\it lingua franca\/} of computers.  They can
virtually all deal with \tty{ASCII} encoded text.

In particular, the text that makes up computer programs is
normally limited to the \tty{ASCII} character set (or some even
more restrictive character set), to ensure that the programs can
be potentially processed on the widest possible variety of
computers.

Now, the \tty{ASCII} code is certainly not the {\it only\/} way
of representing textual material in computers, and the standard
for the \C\ language does not absolutely require either that the
characters making up a \C\ program, or the characters making up
textual material being processed by the program, must be encoded
in \tty{ASCII}. Instead, the standard simply stipulates certain
restrictions on the encoding, which are summarised by
Alcock.\footnote{Alcock rather misleadingly talks of certain
  characters being {\it stored\/} in a certain "order" and/or
  "contiguously"; what he means is that characters are {\em
  encoded\/} in a certain order or contiguously.}
\tty{ASCII} text satisfies these restrictions, and also has some
additional properties which Alcock notes.

As it happens, in the implementation of the \C\ language which
you will be using, characters are, indeed, encoded in \tty{ASCII}
and these properties do hold. However, the point to be made here
is that in general, in your programs, you should not {\it rely\/}
on these latter properties (specific to the \tty{ASCII} coding),
since they are not {\it guaranteed\/} to hold on all computers
implementing the \C\ language - except, of course, where your
program is specifically intended {\it only\/} to work with
\tty{ASCII} encoded text.

\paragraph{The {\it newline\/} Character - and other
vagaries!}

One special problem in dealing with characters is how to represent the
idea of a "line break" or a "new line". In the \tty{ASCII} character set
there are actually two separate numeric codes associated with the idea
of line breaking - one called "carriage return" the other called "line
feed". The terminology goes back to mechanical typewriters and
teletypes, where moving on to a new line required two separate actions:
the "carriage" carrying the roller and paper had to be moved back to the
extreme right (so that the left hand edge of the paper was relocated
under the printing position) {\it and} the paper had to be "fed"
through the roller by the correct amount for a new line.  Of course,
these quaint historical origins have rather little to do with the
operation of modern computer displays; but the distinction between
moving the print position (the cursor) {\it down} a line, and moving it
{\it back} to the left hand margin still exists, and so the distinct
functions of the two \tty{ASCII} control codes still apply.
Nonetheless, it is conventional in \C\ programming to have a single
control code which is denoted by the sequence \verb#\#\tty{n} and which
has the effect of {\it both} moving down a line, {\it and} moving back
to the left hand margin. This special character is called the {\it
newline} character.

Why cannot a newline simply be represented in the \C\ file by,
literally, inserting a new line? Why do we need this special sequence
\verb#\#\tty{n}?  The basic answer is that line breaks are used in a \C\
program to try to lay it out in a legible manner; and that if we put in
line breaks in the \C\ file where what we really want is to have the
program {\it emit} a line break at run time, then this will disrupt and
interfere with the formatting of the \C\ program.  In fact, within \C\
string constants, which is where line breaks are usually desired, it is
{\it illegal} to insert a literal line break, and a compiler error would
be generated.  So it is necessary to invent some kind of more or less
artificial way of indicating the idea of a line break, or the "newline"
character within a \C\ string, and \verb#\#\tty{n} is the way it is
done.  Note that when you write a statement like:

\begin{verbatim}
    printf("\n");
\end{verbatim}

then the string which is actually stored internally in the computer at
run time (and passed as an argument to \tty{printf()}) contains just
{\it one} character - the \tty{ASCII} newline character, and {\it not}
the two separate \tty{ASCII} characters backslash and the letter
\tty{n}. In turn, what the \tty{printf()} function actually "sends" to
the screen is {\it not} the two separate characters \verb#\#  and
\tty{n}, but rather the single \tty{ASCII} {\it newline}
character.\footnote{Its actually even more complicated than this, but I
  will spare you any further details!}

The sequence \verb#\#\tty{n} is called an "escape" sequence: the idea is
that the character \tty{n} is "escaping" from its normal interpretation,
and is, instead, being given a special interpretation.  Its a "sequence"
because the \tty{n} must be preceded by the special "escape" character,
which, in this case, is the backslash character, \verb#\# . The use of an
escape sequence to represent a special \tty{ASCII} character (such as
newline) introduces a difficulty of its own: what if we want to actually
put the backslash character itself into a string?  How can we {\it
prevent} it being interpreted as an "escape" character?  Well, the
answer is obvious enough: if we want to incorporate, literally, the
backslash character \verb#\#  into a \C\ string, we simply escape this
escape character itself: i.e., we write \verb#\\# .  Thus to print the
backslash character using \tty{printf()} we would write:

\begin{verbatim}
    printf("\\");
\end{verbatim}

As well as the newline character, denoted \verb#\#\tty{n} there are a
variety of other special \tty{ASCII} characters which can be represented
in \C\ by escape sequences.  Try out these sequences for yourself, and
try to establish their effect: \verb#\#\tty{r}, \verb#\#\tty{b},
\verb#\#\tty{t}.

\paragraph{Variables, Data Types and Arrays}

A "simple" variable in \C\ can store or record a {\it single} "value".
What {\it kind} of value depends on the {\it data type}: variable of
type \tty{int} can hold positive or negative integers, up to about $\pm
32000$; type \tty{long} variables can hold integers up to about $\pm
2\times 10^{9}$; \tty{float} variables can hold positive or negative
rational numbers, with a precision of about 9 significant digits, and a
range up to about $10^{\pm 38}$.  The type \tty{char} is a little
stranger: its values can be regarded {\it either} as integers (with a
range from 0 to 255) {\it or} as \tty{ASCII} characters, represented in
single quotes, e.g., \tty{'a'}, \tty{'Z'}, \tty{'9'}, \tty{'+'},
\tty{'('} and so on.

But the basic point remains that one variable can store or record just
one value.

Now, if we want to store a whole lot of values (and this is a very
common requirement) we could simply declare as many separate, simple,
variables as are needed.  This is a perfectly satisfactory approach for
many purposes.

BUT: in many cases, we don't just want a whole lot of separate values -
we want our program to be able to automatically scan or iterate or
repeat some operation over all these values. If the values are all
stored in separate variables this will be very clumsy, if not impossible
to code.  This is so because each repetition or iteration would need
to refer to a different variable - with a different {\it name}.  That
means that the \C\ code for each iteration is necessarily different.  If
I want to do the same thing to three variables called \tty{x}, \tty{y}
and \tty{z}, then I will have to program (at least) three separate
statements.  Granted, the statements will be almost identical - but not
quite {\it exactly} identical, because the relevant variable name will
have to be changed from \tty{x} to \tty{y} to \tty{z}. This means I
can't possibly achieve the required repetition with, say, a \tty{for}
statement: because there {\it is} just one substatement controlled as
the substatement of a \tty{for}, and that substatement would have to
name some particular one of the three variables \tty{x}, \tty{y} or
\tty{z}.

This may not be too much of a problem if I just want to repeat something
over two or three different variables - it will not be too much of a
problem simply to copy the relevant \C\ source statements, and edit the
separate copies to deal with the different variables
as appropriate.  But what if the repetition is to be over 50, or 100, or
even 1000 different values?  Then duplicating, and varying, the \C\ code
for each different variable is going to be very laborious, and very
error prone.

Well, the \C\ language provides a special mechanism for dealing with
this kind of situation.  If you want a set of data items, {\it all of the
same type}, then instead of declaring a separate variable for each one,
you can declare a single {\it array} variable:

\begin{verbatim}
    int foobar[100];
\end{verbatim}

The square brackets on the declaration signal that \tty{foobar}
is some kind of array; the number inside the square brackets says how
many elements are in the array; and the type - \tty{int} in the case -
gives the type of the {\it elements}.  So this declaration creates a
single "array" variable, called \tty{foobar}; but \tty{foobar} in turn,
is actually made up of a whole lot (100 to be precise) of individual,
simple, \tty{int} variables.

Note that arrays already have an advantage over separate variables, in
that they are much more concise to declare. In the example above, if we
did not have the array mechanism, we would have had to declare 100
separate variables - something like this:

\begin{verbatim}
    int foobar1, foobar2, foobar3, foobar4, foobar5;
    int foobar6, foobar7, foobar8, foobar9, foobar10;
\end{verbatim}

and so on!

Once an array is declared, the individual elements can be accessed by
indexing the array name.  That is, we can use statements like:

\begin{verbatim}
    foobar[10] = 42;
    foobar[24] = foobar[5] * foobar[4] * 163;
    printf("This is element 9 of foobar: %i\n", foobar[9]);
\end{verbatim}

Array indices in \C\ always start at zero.  So if an array has 100
elements, the valid indices run from 0 to 99.

Note carefully at this stage that an array is a quite different {\it
kind} of object from its elements.  The kinds of things you can
typically do to a complete array are quite different from the kinds of
things you can do to its elements.  Thus, in the case of \tty{foobar}
above, it is perfectly reasonable to write:

\begin{verbatim}
    foobar[0] = foobar[0] + 10;
    printf("%i", foobar[0]);
\end{verbatim}

which has the effect of increasing the value of the zero'th element of
\tty{foobar} by 10.  But it would be silly to write:

\begin{verbatim}
    foobar = foobar + 10;
    printf("%i", foobar);
\end{verbatim}

\tty{foobar} itself - the whole array, as opposed to one of its elements
- is not a number (even though all its elements {\it are}).  Adding 10
to an array is simply not a sensible or meaningful kind of thing to try
to do to a complete array. Similarly, if we give \tty{printf()} a format
specification, \tty{"\%i"}, which signals to it to expect a further
argument of type \tty{int}, then it would be totally confusing to give
it a whole {\it array} of \tty{int} values instead.

Are there {\it any} operations which it makes sense to carry out or use
on a complete array, as opposed to individual elements of it? Well, there
are, but they are relatively few.  The only one we will have immediate
use for is in passing a complete array to a function - somewhat as was
attempted above with \tty{printf()}. But whereas \tty{printf()} has not
been designed to be capable of accepting a whole array as a single
argument, it is perfectly possible, and useful, to write your {\it own}
functions which can accept such array arguments.\footnote{This
  possibility is not pursued in detail by Alcock at this stage, but is
  raised implicitly in Exercise~4 of the chapter.}

In the example given above, the elements of \tty{foobar} are simply of
type \tty{int}.  But the elements of an array can, themselves, be arrays
- and so on.  This allows the creation of data objects which can be
thought of as multi-dimensional arrays:

\begin{verbatim}
    int two_dim_foobar[20][30];
\end{verbatim}

This makes \tty{foobar} an array with 20 elements, where each of these
elements is, in turn, an array with 30 elements, and each of these is a
simple variable of type \tty{int}. The elements can then be accessed as
you would expect, but now needing two indices to identify a particular,
simple, \tty{int} element:

\begin{verbatim}
  two_dim_foobar[10][5] = foobar[6] / foobar[7];
\end{verbatim}

Multidimensional arrays turn out to be useful in many engineering
applications.  For example, if I am writing a program to plot points on
a graph, I could conveniently set up a two dimensional array to record
which points are marked, and which left blank. Similarly, Alcock's
\htmladdnormallink{\tty{MATMUL}}{matmul.c}
program provides a business calculation example where two
dimensional arrays are useful.

Anyway: so far we have just looked at declaring array variables, and
accessing particular elements.  While this simplifies the declarations
somewhat, it is not yet clear that it addresses the original problem -
our desire to be able to easily and conveniently repeat a single
operation over a whole set of different variables, without having to
code a separate statement for each one. Thus, we can now refer to
array elements \tty{foobar[0]} through \tty{foobar[99]}, instead of, say,
to the completely separate variables named \tty{foobar0}, \tty{foobar1}
and so on down to \tty{foobar99}. But how does this make it easier to
repeat operations over these elements?

The key notion here is that the index of an array is not limited to
being just a particular, literal, number, such as in \tty{foobar[7]}.
The index is technically allowed to be an arbitrary {\it expression}.
Thus we could refer to \tty{foobar[2+20]}, or \tty{foobar[(10+3)*2]}.
This is still not terribly useful. But, in an expression, we can put
{\it variables}.  Thus we can have a program fragment like:

\begin{verbatim}
    int foobar[100];
    int index;
    .
    .
    .
    index = 6;
    .
    .
    .
    printf("%i", foobar[index]);
\end{verbatim}

This will have the effect of printing element 6 of \tty{foobar}. What
advantage does this have over simply writing \tty{printf("\%i",
foobar[6])}? Not much yet, but now consider {\it this} code fragment:

\begin{verbatim}

    int foobar[100];
    int index;
    .
    .
    .
    index = 6;
    printf("%i\n", foobar[index]);
    index = index + 1;
    printf("%i\n", foobar[index]);
\end{verbatim}

This has the effect of printing elements \tty{6} and \tty{7} of
\tty{foobar}. Still, so what? The so what is that, if you examine this
fragment carefully, you will see that the two \tty{printf()} statements,
even though they print out two {\it different} elements of \tty{foobar},
are actually textually {\it identical} statements.  Not just "almost"
the same, but strictly identical.  Their different {\it effects}, when
they are executed, arise because the effect depends on the value of the
variable \tty{index} at the time of execution - and that actually
changes between the two statements in this example.

What's so significant about the two \tty{printf()} statements being
absolutely identical? Well, because of this {\it absolute} identity, it
is not necessary to actually repeat them in the \C\ source file at all:
the two separate invocations of this statement can be collapsed down as
the substatement of a \tty{for} statement as follows:

\begin{verbatim}
    for (index = 6; index &lt;= 7; index++)
      printf("%i\n", foobar[index]);
\end{verbatim}

Granted, it is not terrible exciting just to replace a single
duplication of a statement.  But it becomes terribly useful if we have a
large number of duplications.  For example, suppose we want to print out
{\it all} the elements of \tty{foobar} rather than just elements \tty{6}
and \tty{7}? Instead of writing something like:

\begin{verbatim}
    printf("%i\n", foobar[0]);
    printf("%i\n", foobar[1]);
    .
    .
    .
    printf("%i\n", foobar[99]);
\end{verbatim}

with 100 separate statements, each differing only ever so slightly from
the others, we can have a single \tty{for} statement:

\begin{verbatim}
    for (index = 0; index &lt;= 99; index++)
      printf("%i\n", foobar[index]);
\end{verbatim}

Now {\it that's} a real benefit.

Make sure you understand that this kind of collapsing down, using an
iteration statement like \tty{for}, only works if there is absolutely no
variation in the {\it text} of the statement being repeated - although,
of course, there can be a large variation in the {\it effect} of that
text each time it is executed. Go back over the example above, and satisfy
yourself that you cannot achieve the same effect - collapsing down to a
single \tty{for} statement - if the program were using 100 separate
variables with separate names instead of an array.\footnote{Note that the
  names of separate variables {\it must} be textually different, even if
  only "slightly" so.}

Note also that, although I have built up this example using the specific
idea that the thing we want to iterate or repeat is the printing out of
an element of the array, the concept and argument does not rely in any
way on just {\it what} it is we want to repeat.  Exactly similar
considerations would have applied if we wanted to increment each
element, or take its square root, or add it into a cumulative total, or
whatever. Alcock's two example programs
\htmladdnormallink{\tty{MATMUL}}{matmul.c} and
\htmladdnormallink{\tty{BUBBLE}}{bubble.c} provide, of course, more
comprehensive examples of the same ideas.  It is a good idea to at least
attempt to see how you might try implementing either of these programs
if you did not have the possibility of using arrays open to you, but
were forced, instead, to simply declare as many separate, simple,
variables as are necessary. You should find that, in that case, you
cannot use \tty{for} statements to repeat the required operations over
different variables, and you would therefore be forced to "manually"
duplicate blocks of \C\ code many times over, and then edit each copy to
deal with slightly different variable(s).  The whole thing becomes
incredibly cumbersome!

\paragraph{The Dreaded Array Indexing Bugs}

It is vitally important in \C\ programming to ensure that you never use
an array index which is out of range - for example, if \tty{foobar} is
an array declared as having 100 elements, then referring to
\tty{foobar[100]}, or \tty{foobar[-6]} would be indexing errors.  For
somewhat obscure and technical reasons, the \C\ compiler cannot detect
such errors, nor, in general, can they be automatically detected at run
time. But the effects of such errors tend to be highly variable, very
strange, and potentially very confusing.  The nett result is that array
indexing errors are among the most difficult to find and correct in \C\
programming.  It is very important, therefore, to get into the habit
very early on of being very careful indeed about array indices.

This is straightforward enough with simple numeric indices, such as
\tty{foobar[10]} and so on. Although, for beginning programmers it is
still very common to make errors "at the margin" - i.e. to forget that
the valid indices start at zero instead of 1, or make some related
mistake. So even with a simple indexing expression such as
\tty{foobar[j]} it is important to carefully examine how the value of
\tty{j} is being generated or manipulated to make sure that it cannot go
out of range.

But what about more complicated index expressions, such as in:

\begin{verbatim}
    foobar[(x + y) * z] = w + 1;
\end{verbatim}

If you put something like this in a program, you need to very carefully
examine what the values of \tty{x}, \tty{y} and \tty{z} can possibly be,
and try to guarantee that there are absolutely {\it no} circumstances in
which the index expression might yield a value which is outside the
bounds of the particular array. In practice this kind of analysis is
difficult and error prone.  It is better to adopt a style of {\it
defensive programming} where you deliberately try to make the program
itself warn you if something is going wrong.  Thus, the statement above
might be replaced with the following:

\begin{verbatim}
  index = (x + y) * z;
  if( (index &lt; 0) || (index &gt;= 100)
  {
    printf("\nArray indexing bug - Controlled Crash!!!\n");
    exit();
  }
  foobar[index] = w + 1;
\end{verbatim}

The operator \tty{||} is called {\it logical OR} and will evaluate as
\tty{TRUE} (non-zero) if either of its operands is \tty{TRUE}.  The
function \tty{exit()} is a library function which causes the program to
immediately and unconditionally terminate.\footnote{The prototype for
  the \tty{exit()} function is in the header file \tty{stdlib.h}, so you
  should \tty{\#include} this header at the top of your file if you
  intend to use the \tty{exit()} function.}

So the effect of this code is that the index is first calculated and
stored in the variable \tty{index}. Then this value is compared with the
valid limits.  If it turns out, for whatever reason, to be invalid, a
warning message is printed and the program is terminated. Of course, if
the index is valid, then execution simply continues around the \tty{if}
statement, no message is printed, the program is not terminated, and the
index is used to actually index into the array.

At first sight this defensive programming may seem like a lot of
additional effort. But to repeat: array indexing bugs {\it do\/} happen;
and if you have not adopted this kind of defensive programming strategy,
they are {\it extremely} difficult to track down and isolate.  Thus the
small additional effort of the defensive checks is usually far
outweighed by the reduction in time (not to mention sweat and tears)
required to debug the program. Of course, some judgement will always be
required as to whether to add extra checking code - but if in doubt, it
is always safer to add it.  There is also a question over what to do if
an indexing error {\it is} detected: the example above shows just about
the crudest possible reaction.  There are much more sophisticated
possible approaches to reacting to unexpected events in a program (so
called "exception handling").  By all means, feel free to experiment
with formulating your own approaches to this if you think you can
improve on the very crude mechanism shown above.\footnote{In particular,
  you might have a look at the standard library facilities for "process
  control" described in pagese 171--176 of {\it Illustrating C}
  - though this is not for the faint hearted!}

\subsubsection{Week 8-10: Chapter~2 pp.~20--26}

\paragraph{What's a function anyway?}

In \C\ a {\it function} is a unit of code that can be used, or called,
or invoked, from some other place in the program.  Better names for this
idea, used in other languages, are "subprogram", "subroutine", or
"procedure". But, for reasons which, no doubt, seemed sensible at the
time, the designers of \C\ plumped for the word "function" and I am
afraid we are stuck with it!

Functions are handy because they allow you to break a program down into
manageable chunks, where each chunk is quite small (typically 10--20
lines) and does just one or two definite things. Thus each chunk is
pretty readable or understandable in its own right.  If a single
function starts getting too complicated, then we chop some coherent
piece of it out and wrap it up in a function of its own, which now is
merely "called" by the original function.

Functions are also handy because they support "re-usability" in a
program.  Thus, if there is a particular generic kind of manipulation
which has to be done in two or three, or 20 different situations in a
program, we can write a function to do this manipulation; then each time
we need that manipulation, we call the function, instead of repeating
all the detailed code.

In fact, we have been using functions all along already, without really
noticing it.  The block of code in our programs with the following
outline:

\begin{verbatim}
    int main(void)
    {
    .
    .
    .
    }
\end{verbatim}

is technically the definition of a {\it function} whose name is
\tty{main()}.\footnote{In general when I refer to the name of a function
  I include a pair of parentheses after the name, as in
  \tty{main()}. I adopt this convention so that, whenever I use a name,
  you can easily tell whether it is intended as the name of a function
  or of a variable. In fact, the compiler works much the same way: when
  it sees a name in an expression, it looks to see whether the name is
  followed by a left parenthesis, and, if so, it knows that the name is
  supposed to refer to some function.}

All \C\ functions have names, just like variables.  When you are
defining your own functions, you get to pick the names, again just as
with variables.

But the function name \tty{main()} is special in this regard.  {\em
Every} \C\ program is required to have a function called \tty{main()}.
Normally functions get invoked or executed by some {\it other} function
calling them, or transferring control to them.  But if this were true of
{\it all} functions then we would have an infinite regress, with no way
for {\it any} function to get started in the first place.  What is
special about the function called \tty{main()} is that it does not have
to be called or started up by any prior function - it is started up
automatically as the first function to be executed when the whole
program is started executing. In fact, it will normally cause {\it very
bad things} to happen if \tty{main()} {\it is} actually called by any
other function...

OK, so, in a sort of a way we have already seen what a function {\it
definition} looks like, in the form of the definition of the
\tty{main()} function.  We have also seen what function {\it calls} or
{\it invocations} look like, because we have used some of the so-called
{\it standard library functions}, such as \tty{printf()},
\tty{scanf()}, \tty{sin()}, \tty{cos()}, and so on.  So calling a
function basically involves just putting its {\it name} into a statement
(or, more precisely, into an {\em expression}).  When (or if) the
statement gets executed, then that will cause the function to be
invoked, and control will pass, temporarily, into the called function;
that function will do its thing, and then control will pass back to
where the function was called (the so-called "calling site").

Thus, consider this simple program:
\begin{verbatim}
    #include &lt;stdio.h&gt;

    int main(void)
    {
      printf("Help: I'm trapped in the computer!!!\n");

      return(0);
    }
\end{verbatim}

When the program is started, execution will start at the \tty{main()}
function.  This is why a function called \tty{main()} must be present:
otherwise the computer has no way of knowing where in our program
execution {\it should} start.  This may not seem like much of a problem
at the moment: after all, our program only has one function, so that is
"obviously" where execution should start - regardless of what the
function is called.  But very soon we will see programs where the
program consists of more than one function and some ambiguity would then
necessarily arise. Even still you might think the computer could simply
start execution at the first function that is defined (or the last for
that matter) rather that looking for a function of a particular name.
Indeed, with many other programming languages that {\it is} the approach
adopted.  But, again for reasons best known to the original \C\ language
designers, they decided to take the approach of insisting that a
function with the specific name \tty{main()} must always be present, and
that that is where execution will start...

Anyway: in the example above execution starts at the function
\tty{main()}.  The very first statement of this function is then a call,
or invocation, of the standard library function called \tty{printf()}.
So execution is transferred to that function.  In the meantime, the
\tty{main()} function is essentially put into suspended animation. So
\tty{printf()} is executed, which, in this case, means that the string
\tty{"Help: I'm trapped in the computer!!!}\verb#\#\tty{n"}
will be printed out on the
screen. Once \tty{printf()} has done that, it "terminates", or, more
technically, executes a \tty{return} statement, which returns control to
the calling site - in this case, the function \tty{main()}. So now,
\tty{main()} becomes re-animated, and continues execution with its next
statement.  This is a \tty{return} statement which causes \tty{main()}
itself to terminate. Now, as just explained, when a function executes a
\tty{return} this normally causes control to return to wherever the
function was called {\it from}; but this is a bit tricky with
\tty{main()} because, technically, \tty{main()} was not called from {\it
anywhere} (or not, at least, from any other {\it function}).  In
practice, when the \tty{main()} function does a \tty{return} then the
whole program is terminated, and control is returned to the "external
environment" - in our case the Turbo-C++ IDE.  This makes a sort of
sense since \tty{main()}  was the first, or "top-level" function to be
invoked, and in this contrived way, its "calling site" simply {\it is}
the "external environment"...

So: be sure you have the basic idea of a function as a unit or chunk of
code that can be "invoked".  With this facility at our disposal, a
complete program need no longer consist of just one function, called
\tty{main()} (together with whatever standard library functions
\tty{main()} calls).  Instead, once \tty{main()} starts to get a bit
long or complicated, we break down the work that \tty{main()} is doing,
and the statements that constitute it,
into some set of more or less coherent sub-blocks.  Each of these is
then hived off into a "function" of its own.  We will give each such
function some name; this should be as meaningfull as possible, but we
have essentially complete freedom in this (as we have in naming
variables).  Whereas the name of the top-level function is constrained
to be precisely \tty{main()}, the functions called by \tty{main()} can
have any names we like.  These additional functions which we name and
write are called {\it user-defined} functions to distinguish them from
standard library functions.

In the simplest case then, the outline of a \C\ program now looks
something like this:

\begin{verbatim}
    void function1(void)
    {
      /* Statements making up function1() appear
         here... */
         .
         .
         .

      return;
    }

    void function2(void)
    {
      /* Statements making up function2() appear
         here... */
         .
         .
         .

      return;
    }

    void function3(void)
    {
      /* Statements making up function3() appear
         here... */
         .
         .
         .

      return;
    }

    int main(void)
    {
      function1();
      function2();
      function3();

      return 0;
    }
\end{verbatim}

This program consists of the definitions of four functions called
(rather unimaginatively!) \tty{function1()}, \tty{function2()},
\tty{function3()} and \tty{main()}. When the program is started up,
execution will begin at \tty{main()} (even though \tty{main()} is
actually the {\it last} function to be defined!); execution immediately
transfers to \tty{function1()}, and \tty{main()} is suspended; when
control is \tty{return}'ed from \tty{function1()} to \tty{main()}, then
\tty{main()} goes on to call \tty{function2()} and is again suspended
while \tty{function2} is executed; similarly, when \tty{function2()}
executes its \tty{return} statement control comes back to \tty{main()},
and then \tty{function3()} is invoked; finally, \tty{function3()}
executes its \tty{return}, control comes back to \tty{main()}, and
\tty{main()} itself executes a \tty{return}, causing the complete
program to terminate, and control comes back to the IDE.

Be clear that you understand how this function call/return mechanism
allows \tty{main()} to be broken down into smaller, hopefully simpler,
chunks. In this, admittedly contrived, example, the operation of
\tty{main()} itself has actually become trivial - it just calls the
functions \tty{function1()}, \tty{function2()} and \tty{function3()} in
sequence. All the complicated stuff that might have been in \tty{main()}
has been split up, and moved into the "sub-" functions.

Of course, this process of breaking things down can be repeated
indefinitely.  Thus, in the example above, if the function
\tty{function1()} turned out to be still too complicated it might be
broken down into smaller pieces still:

\begin{verbatim}

    void function1a(void)
    {
      /* Statements making up function1a() appear
         here... */
         .
         .
         .

      return;
    }

    void function1b(void)
    {
      /* Statements making up function1b() appear
         here... */
         .
         .
         .

      return;
    }


    void function1(void)
    {
      function1a();
      function1b();

      return;
    }
\end{verbatim}


And, of course, it might turn out that any of these functions can
conveniently be used (or called) multiple times, possibly from multiple
other functions.  In the outline above, it might turn out that
\tty{function1b()}, say, could usefully be called both by
\tty{function1()} and by \tty{function3()}, for example.  Indeed, if we
do a good job in designing the program - in deciding just exactly how
"best" to break it down - we may be able to achieve quite a high level
of such re-usability!

Note that in laying out the outline example program above, I have chosen
to place the function definitions is essentially "reverse" order - if
\tty{function1()} would call \tty{function1a()} at run-time, then I have
placed the definition of \tty{function1a()} {\it before} the definition
of \tty{function1()} in the \C\ source file.  This ordering is not
absolutely required, but it is an excellent rule of thumb - and you
should stick to it unless and until you have some very good reason for
diverging from it.  But be clear on this point: the order in which the
function definitions appear in the source file has no effect whatsoever
on the order in which the functions will actually be invoked.  The
function called \tty{main()} will {\it always} be the first function
invoked, regardless of whether it is positioned at the top, the middle,
or the bottom, of the source file! And the next function to be
invoked will depend exclusively on what statement in \tty{main()} causes
a function to be invoked; and whatever function that actually is, it
will be invoked next regardless of whether it is located in the source
file before or after the definition of the function \tty{main()}.  The
ordering of the functions in the source file affects how the {\it
compiler} translates the file - and it is to facilitate the compiler
that I give you the rule of thumb of ordering the definitions in reverse
order to the order in which they are invoked.  Ordering them in this way
ensures that the compiler never has to attempt to translate a call or
{\it invocation} of a function without already having translated the
{\it definition} of the function - and it turns out that this makes the
compiler's job easier, and can avoid a variety of compile time problems
and errors.  But regardless of whether this ordering is adopted or not, it
will not affect the order of function {\it execution} at run-time!

\paragraph{Moving Data Around}

All right: so far the concern here has been with the {\it concept} of a
\C\ function, and an outline of how they can be defined and used.  Now
we need to get down to some more nitty gritty specifics!

In general, if we want to decompose a program into a set of functions
then, for the functions to co-operate or interact properly they will
need to, in some sense "share" data between them.  By "data" here I
essentially mean variables.  How can the required data sharing be
achieved?

\C\ supports two quite different models for sharing or exchanging data
between functions.  We will consider them in turn.

\subparagraph{Thinking Global...}

In this model the data (the variables) are made
"global": global variables are declared before, and outside of, the
first function definition in the source file.  Global variables are
visible and accessible to {\it all} functions.  Thus, if one function
wants to call another sub-function\footnote{I use the term
  "sub-function" loosely in this kind of context to distinguish between
  one "calling" function and a second function which is "called".
  However, "sub-function" is not a technical term of the \C\ language:
  to \C\ all functions are "equal" - there is no kind of
  precise distinction between "functions" and "sub-functions".}
and have that sub-function carry out some
operation on some particular data values, the calling function can first
store the data values in some global variables, then call the
sub-function; the sub-function can then access the variables and do the
processing; if some "result" is generated, it can be made available to
the calling function by storing it in another global variable.

Have a look at the file \htmladdnormallink{TRI-GLBL.C}{tri-glbl.c}.
This is a somewhat contrived example program, showing functional
decomposition and the use of global variables.  Examine the program and
try to understand how it is supposed to work. Note that, given my rule
of thumb of defining functions in reverse order, the sensible way to
read a \C\ source file is to start at the {\it bottom} and work
backwards.  That is, you should generally start by looking at the
\tty{main()} function.  Try to get some understanding of it in isolation
first. Then start looking at the functions which \tty{main()} calls to
get some extra detail on what is going on. Then, if necessary (it does
not arise in this particular program) you can have a look at the
functions which are called by that function in turn, and so on,
effectively working your way back toward the top of the source file.

Play with \htmladdnormallink{TRI-GLBL.C}{tri-glbl.c}.
In particular, experiment with single
stepping through it.  Try to predict where execution is going to go
next at each stage, and then check whether you are right.  Use the
\tty{Watch} window to monitor the variables. Again, try to predict when
changes are going to happen, and see if you get it right. Notice how
execution transfers to a sub-function, then returns to the calling site.
Notice how the global variables are allowing information to be accessed
or shared between different functions.  Try varying the program
somewhat: e.g.\ to calculate the area of a rectangle, or square; or to
repeat the calculation for a number of times; or to initially print out
some kind of "welcome" message before doing any calculations; or extend
the program to be able to calculate areas of several different shapes -
so that it first has to ask for the kind of shape to be identified (e.g.
saying "Enter 1 for triangle, 2 for square:" or something like that),
and then read the appropriate data for the particular shape, and do the
appropriate calculation.\footnote{Note that the function for printing
  out the result will not have to vary or be modified...}

Note that in \tty{TRI\_GLBL.C} none of the (sub-)functions actually have
a \tty{return} statement as such.  A feature of \C\ functions is that if
execution reaches the end of the function definition - i.e.\ the brace
which closes the definition - then the function will be terminated
anyway and control will automatically return to the calling site, just as
if a \tty{return} statement had been executed.  Thus, if you have a
simple \tty{return} statement as the very last statement in a function
definition it can actually be omitted - and usually is.  By a "simple"
\tty{return} statement I mean one without an operand - unlike the
\tty{return} statement in the \tty{main()} function which has an operand
(namely \tty{0}). The significance of this operand will be explained
shortly: for now the point to note is that, if a \tty{return} statement
does have an operand, then, even if it {\it is} the last statement of a
function definition, this \tty{return} statement cannot be omitted.

\subparagraph{Thinking Local...}

OK, so much for using global variable for co-ordinating or sharing data
access between functions in a \C\ function. What is the alternative?

The alternative mechanism arises if we choose to make the data -
the variables - {\it local} to individual functions.  Local
variables are declared immediately after the opening brace of a
function definition. Local variables are visible and accessible
{\it only} within the function in which they are defined. Indeed,
the storage for the variables is only allocated at all when the
function is invoked and is deallocated again when the function
terminates - so the variables only actually "exist" as long as
the function is active.

Now it follows directly from the "privacy" of local variables that they
cannot be used to share data between functions.  Therefore, if our
functions are using local variables, and if we need to share this data,
we need some mechanism for "passing" the data from one function to
another.  This generally arises just precisely when one function is
calling another (call the latter the sub-function).  Actually there are
then two sub-issues: getting data {\it from} the function to the sub-function,
and getting data (results) {\it back} to the calling site from the
sub-function.  \C\ provides separate mechanisms, with rather different
characteristics to deal with these two directions of data flow - from
calling site to called function, and from called function back to
calling site.

Note that in any particular case of one function calling
another we may need to transfer data in only one of the two directions,
so they really are quite separate. Indeed, as we have already seen with
the use of global variables above, we can have functional decomposition
of a program without using {\em either\/} of these data transfer
mechanisms. In designing a program - in breaking it up into functions -
each case has to be assessed individually.

\subparagraph{A (Short) Digression}

We will look at the separate data transfer mechanisms in turn,
below; but first: a digression.  A common confusion among
students is between the notion of moving data around {\it inside}
a program - between the functions making up a program - and
moving data between the program and the outside world (screen,
keyboard, diskette files etc.).  Granted these two things are
both involved with moving data around. And granted, it turns out
that to do the latter (move data into or out of the program) we
also have to do the former (move data around {\it within} the
program - specifically between our own user-defined functions and
those standard library functions, such as \tty{printf()} and
\tty{scanf()}, which actual do the direct exchange of data with
the outside world). But still, the two concepts are quite
different and should be kept distinct. We very frequently do the
former without the latter (i.e.\ move data around {\it within}
the program without exchanging data with the outside world). I
will use (and reserve) the terms "input" and "output", and also
"reading" and "writing", with the technical connotation of moving
data between the program and the outside world.  When dealing
with data movement {\it within} the program I will use an
alternative set of terms, to be introduced below.  I encourage
you to adopt this more precise vocabulary also.

\subparagraph{Getting data {\it into} a function}

All right: let's consider moving data from a function to a sub-function -
from a calling site to a called function.  We have already seen examples
of this in using the standard library functions: in the function call we
simply list the data to be passed in, separated by commas if necessary,
and within brackets, thus:

\begin{verbatim}
    printf("Hi there...");
\end{verbatim}

Here the function \tty{printf()} is being called, and the string
\tty{"Hi there..."} is being passed in. Similarly, with:

\begin{verbatim}
    x = sin(y);
\end{verbatim}

In this case the function \tty{sin()} is being called, and the value of
the variable \tty{y} is being passed in to it.  Again, with:

\begin{verbatim}
    printf("The answer is %i", result);
\end{verbatim}

The function \tty{printf()} is being called, but now two separate data
items are being passed in - the string \tty{"The answer is \%i"}, and
the value of the variable \tty{result}.  These two are separated by a
comma.

These values passed in to a function are called {\it arguments} to the
function.  They are, if you like, the values which the function is
supposed to operate on or process in some way. And, as already noted, a
function may not need any arguments - if, for that particular function,
what it is supposed to do does not need or rely on any data values to be
processed.

In general, function arguments are actually {\it expressions}.  That is,
any argument can involve a more or less complicated expression.  In that
case, the expression is {\it evaluated}, to yield a resulting value, and
that value is what is actually passed into the function as the argument
value.  Here is an example:

\begin{verbatim}
    printf("%f", ((x * x) + (y * y))/(z + 3.141));
\end{verbatim}

In this case the second argument is actually the expression
\tty{((x * x) + (y * y))/(z + 3.141)}.  When execution reaches
this invocation of \tty{printf()}, the expression is evaluated
first, and the resulting value is what actually gets passed in to
\tty{printf()}.  Note that \tty{printf()} itself neither knows
nor cares how this value was generated - {\it all} it sees is the
resulting value.  This is what is described as "passing by
value"; it is discussed by Alcock on page 21, and is specifically
described by him as "fundamental to the \C\ language". Be clear
about this particular point: since \C\ only allows values to be
passed as arguments, nothing that a called function does with an
argument given to it can affect or change the original source of
the argument. Consider an example. Suppose there is a function
called \tty{foobar()} which expects to be given an argument of
type \tty{int}.  Then a fragment of code where \tty{foobar()} is
called might look like this:

\begin{verbatim}
    int main(void)
    {
      int i, j, k;
      .
      .
      .
      foobar((k + i) * 15);
      foobar(j);
      .
      .
      .
    }
\end{verbatim}

In both calls to \tty{foobar()} the argument is technically an
expression and is evaluated before \tty{foobar()} is actually
started up.  This is clear enough with the argument \tty{(k + i)
* 15}, but it is true also even in the trivial case of the argument
being simply \tty{j}.  In the latter case what happens is {\it
not} that the {\it variable} \tty{j} gets passed to
\tty{foobar()}, but only that the current {\it value} of \tty{j}
is passed in.  The significance is that \tty{foobar()} absolutely
cannot alter or modify the {\it variable} \tty{j}; in fact,
\tty{foobar()} doesn't even know of the existence of such a
variable! {\it All} \tty{foobar()} knows is the value it is given
- it does not know whether that value resulted simply from taking
the value of a single variable, or from evaluating some
arbitrarily more complicated expression.

Some languages {\it do} support a mechanism whereby whole
variables {\it can}, in effect, be passed as arguments.  In that
case, the called function can be given access to a variable
actually belonging to the calling site (not just a copy of its
current value); and the called function can, if it wishes, {\it
change} the value of that variable, and that change will be
visible back at the calling site when control returns there.
Such a facility is a called "passing by reference" - because, in
effect, what is passed is a reference or handle whereby the
called function can get at the original variable, rather than
just a copy of its value.  BUT: the \C\ language does {\it not}
support passing by reference - it {\it only} supports passing by
value.\footnote{A technical exception here is in the case of {\it
  array} arguments. \C\ has some special rules for what happens
  when an array name is used in an expression (without any index)
  - such as when an array is specified as an argument.  The nett
  effect is that arrays "sort of" get passed by reference: but
  the details of this are beyond the scope of the current
  discussion.}
Fortunately, it turns out  that this is not a significant
limitation because the effect of passing by reference can be
"simulated" using passing by value, in combination with certain
other features of the \C\ language. However (as should be clear)
this issue only becomes important in the context of trying to get
data {\it back} from a called function to the calling site - so
it will be considered again below.

As noted with \tty{printf()} above, a function can accept a number of
arguments.  In general, functions are designed so that they expect some
definite, unique, number of arguments, be it 0, 1, 10, or whatever.  In
that case the function {\it must} be called with just that number of
arguments - no more, no less.\footnote{Both \tty{printf()} and
  \tty{scanf()} are exceptions to this rule - they can deal with
  varying numbers of arguments.  But this is highly exceptional:
  most of the library functions we deal with will only accept
  fixed numbers of arguments; and {\it all} of the user defined
  functions covered in this course will only accept fixed numbers
  of arguments.}

Function calls are actually even more restrictive than this
in general.  Not only must the call provide precisely the correct
number of arguments, but they must be of the correct {\it data
types}.  Remember: the data type defines the "kind" of
information represented by a data value or a variable - such as
\tty{int}, \tty{double} etc.  So if a function has been designed
to accept two arguments, the first of type \tty{int}, the second
of type \tty{float}, then every call or invocation of that
function must include precisely two arguments - no more, no less
- and they must be of precisely those types.\footnote{Again,
  \tty{printf()} and \tty{scanf()} are exceptions to this general
  rule; but also again, it is beyond the scope of this course to
  consider this very exceptional behaviour in any further
  detail!}

The compiler will usually try to enforce these rules - i.e. it
will try to check every invocation of a function to see that the
arguments match the design or specification of the function in
both number and type(s).  But the compiler can obviously only do
this correctly if it {\it knows} how many arguments, of what
types, are expected. In the case of user-defined functions it
{\it will} know these things if it has processed the function
{\it definition} before it sees any invocation of it.  This
condition will be satisfied if the program file is laid out as
suggested earlier - in "reverse" order - which, of course, was
precisely the reason for suggesting that ordering.

The situation with library functions is a little
more complicated.  The whole idea of library functions is that
they have been pre-written and compiled ahead of time, so, by
definition, their {\it definitions} will not be available to the
compiler.  But although the full definitions of the library
functions are not available, short "interface specifications"
{\it are} provided.  These interface specifications tell the
compiler, for each function, exactly what arguments are expected,
and of what types.  Such a specification, for one function, is
called a {\it function prototype}.  Function prototypes for the
standard library functions are provided in the standard {\it
header files} - files like \tty{stdio.h} and so on.  So: if you
want to use or invoke any standard library function in your
program, you must ensure that an appropriate header file is first
scanned by the compiler, so that the compiler will then be able
to check that the invocation is legal.  This is done with the
\tty{\#include} directive.  If you are ever in doubt as to which
header file to include to provide the prototype for a particular
library function, look up the function in the Turbo-C++ on-line
help system - the header file will always be listed
there.\footnote{In some cases, the prototype for a particular
  function may be included in several different header files; in
  such a case you just have to insure that at least one of them
  is \tty{\#include}'d in your file.}

Having said all that, be warned: the ability of the compiler to
detect mismatches between the arguments {\it expected} by a function
and the arguments actually {\it provided}, is still less than
perfect. You should still take some care yourself in coding any
function call, and not rely completely on the compiler to check
these things for you!

\begin{quote}
{\it So the format of a function call or function invocation is
always {\bf function\_name} followed by a left bracket - {\bf (} -
followed by zero, one, or more argument expressions, separated by
commas, followed by a right bracket - {\bf )}.  The arguments must
match what is expected by the function in both number and types.
The compiler will try to check for this if - and only if - it has
earlier processed either a full definition of the function, or at
least a prototype, typically found in a \tty{\#include}'d header
file.}
\end{quote}

So much for the {\it invocation} of functions with arguments - but how
does this get represented in the function {\it definition}?

In all the function definitions given so far (including
definitions of \tty{main()}), the functions did not accept any
arguments.  This was denoted by the keyword \tty{void}, placed
between the brackets after the function name:

\begin{verbatim}
  void foo(void)
       /*  ^^^^ This denotes that foo()
                will not accept *any*
                arguments! */
  {
    /* Statements making up foo() go here... */
    .
    .
    .
  }
\end{verbatim}

Note carefully that, in this example, the keyword \tty{void}
appears {\it before} the function name {\it also} - but in that
position it has quite a different significance, nothing to do
with the {\it arguments} which \tty{foo()} accepts. We'll
consider this again later.

OK: that was the special case of a function which does not accept
any arguments.  Where a function {\it does} accept arguments,
this is denoted or coded by replacing the keyword \tty{void} with
a list of names and types for the arguments: these are
technically called the {\it parameters} rather than the
arguments.  The difference is this: the {\it arguments} are the
values which get generated at the calling site; the {\it
parameters} are effectively a special kind of variable, belonging
to the called function, into which the argument values are copied
when the function is invoked.  If you like, all the calling site
can see are the arguments (or argument expressions) - it cannot
see the parameters as such; and all the called function can see
are the parameters (and their values) - it cannot see the
original expressions, or arguments, from which they were derived.
In this sense, arguments and parameters are like two views of the
same thing: but the calling site only has the argument view, and
the called function only has the parameter view.

The format for a parameter list, in a function definition is
something like this:

\begin{verbatim}
    void foobar(int max, int min, double ecstasy)
\end{verbatim}

This heading part of the function definition says that
\tty{foobar()} will accept exactly three arguments.
\tty{foobar()} will refer to these as \tty{max}, \tty{min} and
\tty{ecstasy}.  The first two must be of type \tty{int}, the
third of type \tty{double}.  Whenever \tty{foobar()} is invoked,
the arguments at the calling site will be evaluated; parameters
called \tty{max}, \tty{min} and \tty{ecstasy} will be created;
and the argument values will be copied into them; then execution
will proceed with the statements in the body of \tty{foobar}.
The parameters are then effectively a special kind of local
variable belonging to \tty{foobar}.  Within \tty{foobar()} they
can be used just like any normal variable.  In particular, their
values can be referenced, as one would normally reference the
value of a variable - by using its name in an expression.
Thus, a fragment of \tty{foobar()} might be the following:

\begin{verbatim}
    void foobar(int max, int min, double ecstasy)
    {
      .
      .
      .
      if (ecstasy &lt; 0.0) printf("\nOh dear...");
      else
        if (ecstasy &gt; 100.0) printf("\nI don't believe it!");
      .
      .
      .
  }
\end{verbatim}

Since parameters are a form of local variable you can, of course,
{\it change} their values: but by doing so you overwrite the
original value - the argument - passed in from the calling site.
So this should only be done with care! Note also that, when the
function terminates, the parameters, just like all other local
variables, are disposed of, and their values lost.  Changes to a
parameter within a called function, just like changes to a local
variable, have absolutely no effect on anything at the calling
site.

\subparagraph{Getting data back {\it out} of a function}

All right: that's passing data {\it into} a function, both from the
point of view of the calling site (argument expressions) and
from the point of view of defining the called function (parameter
variables). Now we turn to the complementary question of getting
information {\it back} from the called function to the calling
site.

The simplest, and arguably most convenient, mechanism provided
for this in \C\ is the use of so-called "return" values.
Essentially, a function can terminate using a form of the
\tty{return} statement which specifies a value (it actually has a
complete expression in general: but this will be evaluated to
yield some particular, single, value, of some particular type).
If a function terminates in this way, the specified value is
retained and made available back at the calling site.  In effect,
wherever the function name appeared at the calling site, its
name gets replaced by the returned value, and execution
then continues at the calling site.

Consider this simple example, using the library function
\tty{sin()}:

\begin{verbatim}
    x = sin(0.5);
\end{verbatim}

In this case the function \tty{sin()} is invoked (incidentally
being passed one argument, the \tty{double} value \tty{0.5}).
\tty{sin()} is executed, and when it terminates, it does so using
a \tty{return} statement.  That \tty{return} statement specifies
a return value.  Back at the calling site, the name of the
function is effectively replaced by this value, and execution
continues, so that this value is then assigned to the variable
called \tty{x}.\footnote{When I say that the name of the function
  is "replaced" by the returned value, I do not, of course, mean
  literally that the text of your program is altered. Rather I
  mean that the way to understand what happens next at execution
  time is to imagine the return value appearing in the place
  occupied by the function name.}

That was a simple example.  Here is a somewhat more complicated
one:

\begin{verbatim}
    printf("Answer: %f", sqrt(sin(x) + cos(y)) * 2);
\end{verbatim}

When this is executed, what happens? Well, \tty{printf()} cannot
be started before its arguments have been evaluated.  To evaluate
the second argument, \tty{sqrt()} (a function for extracting
square roots) must be invoked - but again, that cannot happen
until {\it its} argument has been evaluated.  So the calls to the
\tty{sin()} and \tty{cos()} functions have to happen first. It
does not matter which is done first - lets say it is \tty{sin()}.
Its argument is evaluated - simple, it is just the value of the
variable \tty{x}.  This is passed in and \tty{sin()} gets
executed.  In due course it terminates with a \tty{return}
statement, specifying a return value.  This is retained in
temporary storage at the calling site. The argument for
\tty{cos()} is then evaluated - again simple, just the value of
\tty{y}. When \tty{cos()} terminates, again with a \tty{return}
statement, its return value comes back to the calling site and
gets added to the value returned earlier from \tty{sin()}.  This
is now the argument value for \tty{sqrt()} so \tty{sqrt()} is
started up, with the value passed in to it.  Again, in due
course, \tty{sqrt()} terminates with a \tty{return} statement,
and specifies a return value.  This value is multiplied by
\tty{2}, and the resulting value is the second argument for
\tty{printf()}, so \tty{printf()} can now finally be invoked. It
will do its thing (printing out the text \tty{Answer:} followed
by the value of its second argument, regarded - correctly - as a
\tty{double}),  and will then terminate.
\tty{printf()} actually also ends with a \tty{return} statement
which specifies a return value, and this will indeed be passed
back to the calling site (this return value signals whether
\tty{printf()} executed without detecting any difficulties). In
this particular case, the return value is not used at the calling
site - it is not, for example, stored in a variable, or used in
some further expression evaluation. So it is simply discarded,
and execution proceeds to the next statement.

Phew!

That covers how return values are used at the calling site, and
we have also given the gist of how the return value is
implemented in the function definition - namely by using a
\tty{return} statement with an appropriate operand expression.
But let's just detail this with another example:

\begin{verbatim}
    double silly_sum(double apples, double oranges)
    {
      return (apples + oranges);
    }
\end{verbatim}


Note that the \tty{void} that we were previously placing in front
of the function name, in the heading, has now been replaced by
\tty{double}.  This is a general rule.  The word that comes {\it
before} the function name in the heading specifies the {\it type}
of return value (if any) which the function will yield.  If the
function does not yield any value, then the return type must be
specified here as \tty{void}, as indeed, we have generally been
doing up to now.  But if the function {\it does} return a value,
then the type of that value must be advertised or notified ahead of
time, by specifying it here in the heading. So, in our case, just
from the heading, we know that the function \tty{silly\_sum()}
must terminate using a \tty{return} statement, with an operand
which is of type \tty{double}.  If there is a subsequent
inconsistency in the definition of \tty{silly\_sum()} - if it
does not contain any \tty{return} statement, or it has a
\tty{return} statement with no operand, or it has a \tty{return}
statement with an operand which is not of type \tty{double} -
then the compiler will complain bitterly.

As an aside, note that we have consistently been defining the
function \tty{main()} as if it returns a value of type \tty{int},
and then actually ending it with a \tty{return} statement
specifying a return value of \tty{0}:

\begin{verbatim}
    int main(void)
    {
      .
      .
      .
      return 0;
    }
\end{verbatim}

This is, to say the least, a trifle odd. \tty{main()} is not
being called by any other function - it is automatically started
as the very start of program execution. We already mentioned
that, for that very reason, it would not make sense for the
parameter list of \tty{main()} to be anything other than
\tty{void}.  Yet, notwithstanding that, we are defining
\tty{main()} as if it makes sense for it to be passing a return
value back to some calling site. Why is this?

Well, this is yet another of those funny historical oddities of
\C.  The essential idea is that the return value from
\tty{main()} is passed back to the enclosing "environment" -
wherever the program was started up from.  In our case, this is
the Turbo-C++ IDE. The general idea is that this return value
could be used to signal whether program execution was
"successful" or not - with \tty{0} signalling success, and
anything else indicating some kind of failure.  However, this
idea of signalling success or failure to the enclosing
environment doesn't actually serve any useful purpose in the case
of running programs under the Turbo-C++ IDE.  Using it under
other environments (where it might be useful) is beyond the scope
of this course.  In fact, for our purposes, it would be legal, and
preferable, to define \tty{main()} as not returning any value at
all, and omit any \tty{return} statement from it:

\begin{verbatim}
    void main(void)
    {
      .
      .
      .
    }
\end{verbatim}

Unfortunately Alcock has insisted in showing \tty{main()} as
yielding a return value of type \tty{int}, so, in the interests
of consistency with his presentation, I have stuck with that...

OK: time for another substantial example. Let's revisit the
triangle area calculating program, but now avoiding the use of
global variables, and moving data around with arguments and
return statements instead.  Have a look at
\htmladdnormallink{TRI-LCL.C}{tri-lcl.c}. Compare it with
\htmladdnormallink{TRI-GLBL.C}{tri-glbl.c}. Again experiment
with single
stepping through it.  Try to predict where execution is going to go
next at each stage, and then check whether you are right.  Use the
\tty{Watch} window to monitor the variables (including the
various function parameters). Note that because
the variables are now all {\it local}, they only exist at all when the
relevant function is active.  Furthermore, it is a characteristic
of the \tty{Watch} window that only variables of the function
which currently contains the execution highlight bar are
  visible.\footnote{Other functions may be "active" -
  \tty{main()} is active all the time, for example - but
  be temporarily suspended while a sub-function is executing. Their
  variables still exist, and will become visible again in the
  \tty{Watch} window as execution returns to them...}
Again, try to predict when changes are going to happen, and see
if you get it right. Notice how the parameters and return values
are allowing information to be moved around between the different
functions.  Again, try varying the program somewhat: e.g.\ to
calculate the area of a rectangle, or square etc.

Now notice one particular difference between
\htmladdnormallink{TRI-GLBL.C}{tri-glbl.c} and
\htmladdnormallink{TRI-LCL.C}{tri-lcl.c}.
In \htmladdnormallink{TRI-GLBL.C}{tri-glbl.c} I used a single function
(\tty{read\_dimensions()}) to prompt for and read in both the
dimensions of the triangle; whereas, in
\htmladdnormallink{TRI-LCL.C}{tri-lcl.c} I have broken this down into
two separate functions, \tty{read\_base()} and \tty{read\_height()}.
Stop for a moment, and see if you can figure out why I made this
change...

Well, if I had retained the original structure of
\htmladdnormallink{TRI-GLBL.C}{tri-glbl.c},
but without using global variables, then the
function \tty{read\_dimensions()} would have to somehow return
{\it two} distinct pieces of information.  But that cannot be
done with the \tty{return} mechanism in \C.\footnote{OK: this is
  a little white lie.  It {\it can} be done, but only using the
  mechanisms of \tty{struct} data types. This is beyond the scope
  of the current discussion, but have a browse in Chapter~8 of
  {\it Illustrating C} if you want to explore this further...}
The \tty{return} statement can only have one operand, and thus
only a single value can be passed back to the calling site.
Indeed, if you think about the way the returned value is handled
at the calling site (being inserted wherever the function name
appeared) it should be clear why this must be so: if more than
one value was returned then there would be no unambiguous way of
deciding what to do at the calling site.

So: I elected to re-organise the program to remove the need for a
function which would return more than one value - by replacing it
with a pair of functions, each of which individually only return
one value.

This works fine.  But it also gives me an excuse for mentioning
an alternative way for getting information back from a called
function to the calling site - a way which does not suffer the
limitation of the \tty{return} mechanism, which can only handle a
single value.

First recall the earlier discussion of "passing by value" and
"passing by reference".  Clearly, if we had a mechanism for
passing by reference we could use this to get as many distinct
items of data as we like back from a function: we just pass ("by
reference") that number of variables {\it into} the function; the
function then stashes the relevant results in these variables;
and when the function terminates, and control returns to the
calling site, those results can be accessed - as many of them as
you like.

But, of course, \C\ does not support passing by reference. So
what can we do?

The answer is that we can achieve the effect of passing by
reference, in a somewhat roundabout way: we can pass, as values,
and using the normal \C\ passing by value mechanism, the {\it
addresses} of some variables.  Using these addresses, the
function can then, indirectly, get at the variables, and deposit
results in them - exactly as if the variables {\it had} been
passed by reference.

In fact, we have already been implicitly using this mechanism,
though without drawing too much attention to it.  It is the way
we have been getting information back from the standard library
function \tty{scanf()}:

\begin{verbatim}
  scanf("%d %f %f", &amp;i, &amp;x, &amp;y);
\end{verbatim}

In this case the additional arguments to \tty{scanf()} are {\it
addresses} or {\it pointers} to variables.  We generate the
address of a variable by preceding its name with the "address-of"
operator, denoted with the ampersand character, \tty{\&amp;}.

Of course, this mechanism is used by \tty{scanf()} precisely
because \tty{scanf()} is {\it supposed} to be able to get more
than one item of information back to the calling site.  In fact,
a single call to \tty{scanf()} can be used to pass an
indefinitely large number of separate items back, just according
to how the format specification string is laid out.

Can you use this mechanism in your own user-defined functions?

Yes - but it is quite messy.  To define a function of your own
which uses this mechanism you need to know two new things: how to
specify that the type of a parameter is an address or pointer;
and given an address or pointer, how to "de-reference" it -
access the thing pointed at.  The program
\htmladdnormallink{TRI-LCL1.C}{tri-lcl1.c} gives an example, if
you want to have a look - but we will not consider this in detail
here.

\subparagraph{Preferences?}

We have seen two radically different styles of getting
information into and out of functions: the use of global
variables and the use of parameters and return values.  Which is
best?

Unfortunately there is no simple answer. Both kinds of mechanism
are provided in \C\ precisely because, in different circumstances
they each have their own advantages.

For people just starting out to learn to program the global
variable mechanism is conceptually easier to deal with, and
actually syntactically easier to use in programs.  Therefore I
recommend that you start out by using this mechanism, unless you
have some specific reason for doing otherwise.

However, quite quickly you will probably discover some of the
drawbacks of using global variables.  At that point it is worth
getting familiar with both parameter and return value mechanisms
and trying them out.

Once you are technically happy that you can use both kinds of
style then, with experience, you will get a feel for the
particular circumstances in which each is appropriate.  But:
until you are comfortable with judging this I recommend that you
actually try to avoid or minimise your use of global variables.
You will find that this requires you to think rather harder about
how to design your programs; and will also make the design and
coding somewhat more cumbersome at times.  However, it is a fact
that the use of global variables makes programs prone to a
variety of subtle problems and bugs - due to non-obvious and
un-intended interactions between functions, via changes in global
variables. Such bugs are particularly difficult to isolate and
correct. Therefore you will find that avoiding the use of global
variables - except where they have some overwhelming advantage to
recommend them - will save you a lot of program development time
in the long run.

\paragraph{Recursion}

Alcock chooses to introduce recursion toward the end of
Chapter~2.  I'm not sure I agree with the need for this.
Recursion - functions which invoke themselves - is an interesting
programming concept, and it does permit very elegant solutions to
certain programming problems.  On the other hand, there is never
a situation where the same effect as recursion cannot be achieved
using conventional iteration mechanisms, such as \tty{for}
statements.

In any case, all I will add to Alcock's discussion are the
following brief comments:

\begin{itemize}

\item When {\it any} function is invoked, storage is allocated for its
local variables (including parameters, if any).

\item This storage will be deallocated when the function
terminates.

\item Recursive functions are a special kind of function. This
may seem trite, but it follows that you need to understand the
{\it general} concept of a function reasonably well before you
try to understand the idea of a recursive function...

\item If a function is invoked again while it is still already
active - i.e.\ if a recursive invocation is made - then
additional storage is allocated to hold a new set of local
variables for this new invocation. Each invocation thus has an
entirely separate set of variables and parameters - even though,
within each invocation, these are referred to by the same names.
There is no confusion because the computer keeps careful track of
which invocation is being executed, and therefore which copies of
variables or parameters to refer to.

\item At first sight it seems that recursive function invocation
must be fatal: surely the computer will be caught in an infinite
regression, invoking ever more copies of the same function, until
something horrible happens (like it runs out of storage to hold
any more variables) and the whole thing crashes? This certainly
{\it can} happen; but recursion can also be made benign.  It is
made benign by ensuring that, at each nested invocation, {\it
something} is changing (typically a parameter value); and at
some, finite, point, this will result in a copy of the function
which does {\it not} make a further, nested, recursive call to
itself, but instead terminates.  That then allows its caller to
terminate, and its caller in turn, so that the whole nest of
recursive calls can finally unwind, and return control to
wherever the very first instance of the function was called from.

\item But recursion will only be benign and controlled in this
way if you, the software engineer, make it so.  Recursion is
intrinsically dangerous stuff - use it with extreme caution!

\end{itemize}

%***************




\subsection{Term 2: Weeks 11--20}

\subsubsection{Week 11--12: Chapter~3 pp.~27--38}
\atwork

\subsubsection{Week 13--14: Chapter~3 pp.~39--49}
\atwork

%
% \subsubsection{Week 6: Chapter~4 pp.~50--59}
% \atwork
%
% \subsubsection{Week 7: Chapter~4 pp.~60--64}
% \atwork
%
% \subsubsection{Week 8: Chapter~5 pp.~65--72}
% \atwork
%
% \subsubsection{Week 9: Chapter~5 pp.~73--78}
% \atwork
%
% \subsubsection{Week 10: Preparation for Midsessional Test}
% \atwork
%
%
% \subsubsection{Week 11: Chapter~6 pp.~79--91}
% \atwork
%
% \subsubsection{Week 12: Chapter~6 pp.~92--106}
% \atwork
%
% \subsubsection{Week 13: Chapter~7 pp.~107--115}
% \atwork
%
% \subsubsection{Week 14: Chapter~7 pp.~116--124}
% \atwork
%
% \subsubsection{Week 15: Chapter~8 pp.~125--133}
% \atwork
%
% \subsubsection{Week 16: Chapter~8 pp.~134--142}
% \atwork
%
% \subsubsection{Week 17: Chapter~9 pp.~143--153}
% \atwork
%
% \subsubsection{Week 18: Chapter~9 pp.~154--162}
% \atwork
%
% \subsubsection{Week 19: Chapter~10 pp.~163--175}
% \atwork
%
% \subsubsection{Week 20: Chapter~10 pp.~176--194}
% \atwork
%

\section{Laboratory}

\subsection{General Comments on Lab Work}

The CAE laboratory itself should be used both for the scheduled
laboratory exercises, and also for "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.  {\it 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 - 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 you lab logbook.
However, in contrast to most other laboratory subject, this
logbook will {\it 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 {\it separate\/} formal reports, which will actually
be submitted electronically for marking. This is a new initiative
in the academic year 1994/95, and will be explained in more detail
during the first lab session.

You should consult the
\htmladdnormallink{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.

\subsection{Term 1: Weeks 1--10}

\subsubsection{Session 1: Week 1/2}

This first session is primarily concerned with introducing the
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).

Your next task is the following:

\begin{itemize}
\item Start up the \tty{File Manager} program. Browse through its
on-line help to get a general idea of what the program is and how it can
be used.

\item Using \tty{File Manager}, 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} - for example as \tty{D:$\backslash$MYDIR} or
  whatever.}
Try to establish what, if any restrictions apply to naming
a directory - either by experiment or by reading the help.

\item Use the \tty{Notepad} program to create a text file
containing a {\it short} description of your experiences during
Orientation week - what you enjoyed, disliked etc. Save this with
the filename \tty{ORIENT.TXT} in the directory you have just
created.  Ensure that it is no more than 2,000 bytes long. If
necessary, go back and make it shorter.

\item Save a copy of this file on {\it both} your diskettes, in a
top level directory called \tty{LAB\_1}. Delete the original file and its
directory from drive \tty{D:}.\footnote{You will have to
  "format" the diskettes first.  Disk formatting and file
  copying and deleting operations are all carried out with the {\tt
  File Manager}: again, consult the online help for details!}

\item Using the \tty{Terminal} facility of the \tty{Wnqvtwsk} program,
consult the DCU library On-line Public Access Catalog (OPAC) to find any
books written by {\it Donald Alcock}.\footnote{Login as "opac".}
Make a note of any you locate.

\item Still using the \tty{Terminal} facility of \tty{Wnqvtwsk} change your
password on the computer \tty{ugmail.eeng.dcu.ie}.

\item Use the \tty{Mail} facility of \tty{Wnqvtwsk} to exchange at least 2
e-mail messages with other student(s) in the class. Arrange for copies
to be sent to your own mailbox also. Save these messages.

\item Compose, using \tty{Notepad}, a {\it brief} formal report
on the lab session. Include copies of the file \tty{ORIENT.TXT},
and the e-mail messages you exchanged. The complete report must
be no more that 5,000 bytes long. Mail it to your
demonstrator.\footnote{This will be \tty{DemoA}, \tty{DemoB},
  \tty{DemoC} or \tty{DemoD}, where the last letter is the letter of
  your section in the class.}
Arrange to save a copy of the {\em mailed} message (including the time
and date stamp) on both your diskettes in the directory {\tt
LAB\_1}.\footnote{Note that you can specify multiple recipients for a
  mail message by separating them by commas, and you can send mail to
  yourself, though it will not be visible until you exit \tty{Mail} and
  re-enter it again.}

\item Shut down any programs you still have running - and go for
a well deserved lunch!

\end{itemize}

\subsubsection{Session 2: Week 3/4}

\label{lab2}

Carry out Exercise~1 of Chapter~1 of {\it Illustrating C}.

\paragraph{Exercise~1}

Implement the loans program.  This is an exercise in using the tools of
your particular C environment.  It can take a surprisingly long time to
master a new editor and get to grips with the commands of an unfamiliar
interface.  If all else fails, try reading the manual.

\paragraph{Preparation}

In advance of the lab, prepare a file, called \tty{WOTCOST.C},
containing the program as listed on page 3 of the textbook.\footnote{If
  you did not do this in advance - shame on you. Do it now!}

Now, using \tty{File Manager}, create a directory called
\tty{SWE1\_TC} in the root directory of drive
\tty{D:}.\footnote{If this directory already exists you can leave
  it there, but delete all files and/or subdirectories which may be in
  it.}
Copy the file \tty{WOTCOST.C} into this directory.

\paragraph{The Turbo-C++ IDE}

\label{tc_ide}

You will be using the {\it Turbo C++} "Integrated Development
Environment", or IDE, to create, compile, test, and debug (i.e.\
correct) your C programs. The IDE application is started up using the
Turbo~C++ icon in \tty{Program Manager}.

Note that the IDE was developed before Microsoft Windows became
standardised; while the IDE uses menus, windows, dialog boxes etc.\ in
much the same way as Microsoft Windows, the details vary significantly.
Experiment, and use the on-line help as necessary, to get a better feel
for how things behave within the IDE.

The IDE provides various facilities for developing \C\ programs.

It allows {\it editing} of \C\ program files. This is an alternative to
\tty{Notepad}. You will probably still find it convenient to
use \tty{Notepad} for creating and editing any text files {\it
other\/} than \C\ program files; but it will be handier to use the
editor built into the IDE for \C\ program files.

Next the IDE allows programs to be {\it compiled}. Compiling means
translating the relatively high level instructions of the \C\ program
into sequences of the very much simpler and basic instructions that the
microprocessor in the PC can actually execute or carry out. During
compilation, certain kinds of "warning" and "error" messages may be
issued.  Error messages mean there is something so badly wrong with the
program that compilation cannot even be completed. Warning messages
indicate that the compilation could be completed, but the compiler is
suspicious that the program still does not make "sense".

The IDE also supports {\it linking}.  Linking means combining the
instructions generated from your particular program with additional
"standard" sets of instructions, for doing "standard" things, like
arithmetic, or displaying information on the screen, or reading
information from disk files etc.  These additional instructions are held
in "libraries". Your program cannot actually be executed until it has
been linked with any required libraries. Linking can also yield further
warning and/or error messages.

Note that, even if your program compiles and links without any warning
or error messages, this does not at all mean that all errors have been
eliminated.  It simply means that you have a program which is complete
or valid {\em enough\/} to be actually executed: but it may not do
anything like what you intended. Indeed, it is virtually unknown for a
program of any significance to work properly first time.

So: the IDE also provides various facilities for testing and debugging
the program. The program can be simply executed; but it can also be
executed one step at a time; or the values of variables can be examined
or modified, and so on.

\paragraph{Hints}

This section contains hints on using the Turbo-C++ IDE. It would be
preferable if you could refrain from reading it!!!  Try
experimenting first.  If the results of this seem totally
incomprehensible, try browsing through the on-line help.  Come
back to look here only in the last resort (short of asking the
demonstrator).

\subparagraph{IDE Edit Windows}

Before you can do anything else (such as {\it compile}) a \C\
program with the IDE you must load the file into an IDE {\it
edit} window. These are very like \tty{Notepad}: they
provide basic text editing facilities.

To open an edit window, and load \tty{WOTCOST.C} into it,
drop down the \tty{File} menu and select the \tty{Open} menu item.  This
will bring up a file selection dialog box, quite similar to (though also
slightly different from) a conventional Windows file selection dialog.
You should be able to use this to select \tty{WOTCOST.C}. An edit window
will be opened. You should be able to see the text of \tty{WOTCOST.C}.
If you cannot do this, then ask for help from the demonstrator.

Once you have an IDE edit window successfully opened, experiment
with editing the text, saving it, closing the edit window, and
reopening it.

It is possible to have several edit windows open
simultaneously. Each normally accesses a separate
file.\footnote{I strongly discourage the use of multiple edit
  windows simultaneously accessing the {\it same} file: this
  usually ends in tears! In fact, at this stage in your programming
  education, you would do well to restrict yourself to a maximum of 3
  simultaneous edit windows (even accessing different files), at any
  given time.}
The name of the file being accessed or edited is shown in the
title bar of each edit window.

\subparagraph{Compiling}

Once the program text is loaded in an edit window you can {\it
compile} it: that is, translate the "high level" statements of
the \C\ language into sequences of the much simpler, "low
level" instructions which the microprocessor in the PC can
directly carry out. This so-called {\it object} code will
normally be stored in a file with the same name as the source
file, but the extension \tty{.OBJ}. In our case then,
the object file will be called \tty{WOTCOST.OBJ}.

Note that you will not need to copy object file(s) onto your
diskettes for backup. They can always be recreated simply
by recompiling again.

To compile you must first make the edit window (containing the
\C\ program text) {\it active}.  The active window in the IDE is
identified by having a {\it double} line border. Initially this
probably will not be a problem: the edit window will be the only
window you have opened in the IDE.  But later on you will have
several windows open in the IDE; then it is important to remember
that compiling will only work with an edit window selected.

To compile, drop down the \tty{Compile} menu, and select
the \tty{Compile to OBJ} menu item.  The compilation will then
be attempted.  It is quite likely that the compiler will issue
several warning and/or error messages.  These will be displayed
in a separate \tty{Message} window.

\subparagraph{The Message Window}

When the \tty{Message} window is active, you can scroll
up and down through it highlighting one message at a time. As
each message is highlighted, a highlight bar will also be moved
about in the corresponding edit window. The highlight in the edit
window gives a {\it rough} indication of where the compiler
"thinks" the problem is located. Be wary of this: the compiler
(like most computer programs) is not at all smart. The most you
can rely on is that the problem, whatever it is, is either in the
line highlighted by the compiler, {\it or somewhere before it}.

Be wary also of the actual text of the message. The compiler will
do its best to diagnose the problem. It will try to give a
meaningful description of it. But, it will often fail miserably
at this! So treat the actual text of the message with
some scepticism. A message {\it always} indicates that {\it
something} is amiss with your program.  But the actual problem
will {\it often} be in a different place, and of a different
kind, to that suggested by the compiler.

If you press the \tty{Enter} key while the \tty{Message} window is
active, the IDE will automatically make the (relevant) edit window
active, and position the cursor as near as possible to where it
"thinks" the problem is. The text of the message will also be
temporarily redisplayed in the bottom of the edit window. This text will
disappear as soon as you move the cursor around in the edit window. You
can make the \tty{Message} window active again by clicking
anywhere over it.

"Error" messages are more serious than "warning" messages.
But at this stage in your education, you should consider all
messages issued by the compiler as indicating {\it problems}.

Do not go past the compile stage until you have managed to get a
completely "clean" compilation - with absolutely no error or
warning messages. If you find that you simply cannot make any
sense of some compiler message (after making a sincere effort!)
then call the demonstrator for help.

\subparagraph{Linking}

Once you have got a clean compilation, you can go on to the {\it
linkage} phase. This is where, if necessary, certain standard
"library" procedures or routines are added to the code produced
by compiling your program. These standard routines deal with
things like reading data in from from the keyboard, or writing it
out to a disk file; or calculating mathematical functions such as
{\it sin()} and {\it log()} etc. There are a very large number of
such standard routines, or "building blocks", available. This
saves individual software engineers from having to develop these
standard procedures themselves from scratch.

You will not be able to actually run or execute your program
unless it can be successfully linked.  The output of the linkage
phase is called the {\it executable} file. This will normally be
stored in a file with the same name as the source file, but the
extension \tty{.EXE}. In our case then, the executable
file will be called \tty{WOTCOST.EXE}.

As with object file(s) you will not need to copy executable
file(s) onto your diskettes for backup. They can always be
recreated whenever necessary..

To carry out the linkage, first ensure that the (relevant) edit
window is active.  Then drop down the \tty{Compile}
menu. Select the \tty{Link EXE file} menu item.

As with compilation, problems may be detected during the
linkage phase, and messages may be displayed in the edit window.
In this case, however, the IDE will not be able to even {\it
guess} where the problem is located in the original source file.
This is because, at linkage time, the IDE is really only dealing
with the \tty{.OBJ} file: it is no longer dealing with
the source file.  It cannot relate problems now arising with the
\tty{.OBJ} file back to some particular location in the
source file: the relationship between these two files is too
complex to allow this. But: you can rest assured that, if the
linkage phase results in messages in the \tty{Message}
window, there really {\it is} something wrong with your source
program.

Do not go past the linkage stage until you have managed to get a
completely "clean" link - with absolutely no error or warning
messages. If you find that you simply cannot make any sense of
some linkage message (after making a sincere effort!) then call
the demonstrator for help.

\subparagraph{Running the Program}

Once you have got a clean compilation, followed by a clean
linkage, you can finally try "running" or "executing" your
program.

Remember: just because you have got to this stage does {\it not}
guarantee that the program is "correct". It simply means that
the remaining problems are of such a kind that the program is
still "legal" - it is still executable - but it just doesn't do
what you intended. There almost certainly {\it will be} remaining
problems of this kind!

You can run the program by dropping down the \tty{Run}
menu and selecting the \tty{Run} menu item.

The IDE window should be automatically (though temporarily)
cleared so that it can be used and controlled by the program.
More technically, the window is being switched to display the
so-called \tty{User Screen}.

{\it If} the program is working correctly, it should display the
message prompting for input of the relevant data. Enter suitable
test numbers (separated by spaces). Press the \tty{Enter} key. The
program should then print out the results - and terminate!  There is a
slight problem here. As soon as the program exits or terminates, the IDE
will automatically switch away from the \tty{User Screen}, back to the
normal IDE display.  This happens {\it very} quickly - so that you will
not have time to see whether the program has printed any result at all
(never mind the correct result).

However, you can redisplay the \tty{User Screen}, even
when the program is no longer running. Simply drop down the
\tty{Window} menu. Select the \tty{User Screen}
menu item. The \tty{User Screen} will then be
temporarily redisplayed. This allows you to check the program
output. Pressing any key (or clicking the mouse button) will then
cause the display to revert to the normal IDE display.\footnote{A
  slightly more sophisticated, and convenient, alternative, is to display
  the \tty{Output} window (select the \tty{Output} menu item on the
  \tty{Window} menu). This is a normal Turbo-C++ IDE window which can be
  moved around and resized etc., but which "mirrors" whatever output
  appears on the \tty{User Screen}.  Thus, it can allow you to still see
  the output even while the \tty{User Screen} itself is not being
  displayed.}

\subparagraph{Test and Debug}

Test your program severely and thoroughly.  If possible,
co-operate on this with another person in the class, if that
person is at the same stage: temporarily swap machines, and each
test the other's program.\footnote{Most people have a natural
  disinclination to be severe in testing their own work - but
  relish the thought of demonstrating the flaws in the work of
  somebody else. Sad but true - and, in this case, rather
  useful.}
If this is not possible, just try to be as severe in your own
testing as you can.

More likely than not, this testing will reveal continuing
problems with the program. Try to understand what is causing
these problems, and fix them. If all else fails, ask the
demonstrator for help. Do not go past this stage unless the
program has behaved correctly under a wide variety of tests.

\paragraph{STOP!}

If you are satisfied that you have got the \tty{WOTCOST.C}
program working correctly and satisfactorily, then you can go on to
read the rest of the instructions below; but, if the program is still
misbehaving, then stick at it - and ask for help from the demonstrator.

\paragraph{Some Questions}

If you are completely satisfied that you have got the
\tty{WOTCOST.C} program working correctly and
satisfactorily, then you can go on to consider the following
questions.

\begin{itemize}

\item Are there any restrictions on the numbers that this program can
deal with?  Try to find out using very big and very small numbers -
and anything else you can think of.

\item What happens if you feed in {\it negative} numbers to this
program? What {\it should} happen (in your opinion)?

\item What happens if you feed in too many numbers? Too few? What {\it
should} happen?

\item What happens if you feed in non-numbers? What {\it should} happen?

\item If you change things in the program it will generally cause
compiler and/or linker errors.  Try to find what is the simplest, most
innocuous, change you can make which gives rise to the greatest number
of weird and incomprehensible error and warning messages
at compile time.

\end{itemize}

\paragraph{Variations}

If you succeed in getting the basic \tty{WOTCOST.C} program
working, and you have tested it thoroughly, then you can go on to try
the following:

\begin{itemize}
\item \tty{WOTCOST1.C}: Behaves exactly like the given program,
except that it first displays an additional message like "Welcome to
the WOTCOST program".

\item \tty{WOTCOST2.C}: Behaves like the given program, except
that it expects the interest rate to be entered already as an absolute
value such as 0.15,
rather than as a percentage.

\item \tty{WOTCOST3.C}: Behaves exactly like the given program
- but the variable names are changed to more meaningful ones (like
"principal", "years" etc.).

\item \tty{WOTCOST4.C}: Behaves exactly like the given program
except that it prompts {\it separately} for each of the input values to
be entered.

\item \tty{WOTTIME.C}: Similar in concept to the given program;
but it is given the principle, interest rate, and {\em monthly
repayment}; it has to calculate how long the loan will take to pay off.

\item \tty{WOTCOST5.C}: Behaves exactly like the given program,
except that it rejects any attempt to enter a {\it negative} value for
any of the inputs.

\end{itemize}

\paragraph{Conclusion}

That completes the exercise. As previously explained, the formal lab
report should be prepared electronically, and submitted (to {\it your\/}
demonstrator) by electronic mail.  The report should be concise, and not
repeat material in these on-line instructions.  It should focus on the
particular problems you experienced, and how you solved them. It should
make clear what you have learned from the exercise.

You will be allowed approximately 20 minutes at the end of the lab
session for preparing and submitting the formal report. If you cannot
complete it in this time, complete it on your own time afterwards.
However, you should {\it not} spend more that one hour, in total,
preparing and submitting the formal lab report. The report {\it must} be
submitted within one week of the day on which your lab session is
scheduled.

\subsubsection{Session 3: Week 5/6}

Carry out Exercise~1 {\it and} Exercise~2 of Chapter~2 of {\it
Illustrating C}.

For your convenience these exercises are reproduced in the following
sections of the on-line notes. Exercise~1 has also been slightly
modified to conform with some limitations of the Turbo-C++ application.

\paragraph{Exercise 1: Matrix Multiplication}

Program \tty{MATMUL} multiplies matrices of fixed size (3 rows, 4
columns; 4 rows, 2 columns). Make the program deal with any specified
sizes up to an arbitrary 50 by 50.\footnote{The maximum size stipulated
  in the textbook is 100 by 100; but with the Turbo-C++ application,
  as currently configured, this is too large for it to handle. Hence the
  reduction to 50 by 50.}

Read three sizes: the number of rows of \tty{A}, the number of columns
of \tty{A}
(implying also the number of rows of \tty{B}), the number of columns of
\tty{B}.
Read \tty{A} and \tty{B} by rows, then print \tty{C} by rows.
For this exercise you have
to change each simple reading loop to a nested pair of loops. Similarly
the printing loop.

\paragraph{Exercise 2: Bubble Sort}

Alter the Hooke's Law anagram program to read and sort a list of numbers
(type \tty{double}) into numerical order, then display the sorted list. Make
the program request the length of list, then ask for the numbers one by
one.

\paragraph{Preparation}

You {\it must} have completed all parts of the previous lab exercise in
advance of this lab session.  If you are having difficulty with some
parts of it, look for help! But do this before you arrive for this
session.

Prepare files (called \htmladdnormallink{\tty{MATMUL.C}}{matmul.c} and
\htmladdnormallink{\tty{BUBBLE.C}}{bubble.c} respectively) containing
the basic programs introduced on pages 17 and 19 of the textbook. Again,
this {\it must} be done in advance of the lab session.\footnote{You
  should have found that, if you click on the hot-linked file names, you
  can get a display of either of these files, within Mosaic.  You can,
  of course, retype each program from this display into the
  Turbo-C++ IDE.
  However, you may also save the files directly from Mosaic, using the
  \tty{Save As} menu item on the \tty{File} menu. Which saves a bit of
  typing.}

Note the comment on the listing of \tty{MATMUL} (page 17 of the text
book) that, when using Turbo-C, 1992, an extra "dummy" statement must
be added in to correct for a bug in the Turbo-C application itself. The
header file for the mathematical functions must also be included - i.e.
a \tty{\#include &lt;math.h&gt;} directive must be added at the top of the
file.  Both of these corrections are already included in the online
version of \htmladdnormallink{\tty{MATMUL.C}}{matmul.c}.

\paragraph{Instructions}

\begin{enumerate}

\item As in the previous exercise, ensure that a directory called
\tty{SWE1\_TC} exists on drive \tty{D:}. Create it if necessary. If it
already exists, and if there are any existing files or subdirectories in
this directory, delete them.  Then copy your files into this directory.
{\it Do all this before starting up Turbo-C++}.

\item Each exercise requires you to modify one of the given programs.
But first, ensure that the original programs behave as expected.  That
is, in each case, get the program to compile and link successfully (zero
error and warning messages), and then subject it to a range of tests.
Make the tests as difficult and severe as you can imagine.
You may find it useful to refer back to the information on using the
\htmlref{Turbo-C++ IDE}{tc_ide} from the previous lab session.

Do not proceed with trying to develop {\em either\/} of the modified
programs until {\it both\/} original programs pass such tests.  If in
doubt, consult the demonstrator for advice.

This should take no more than the first 50 minutes of the lab session,
i.e.\ you should be finished this by 9:50.

\item Now you can attempt to modify the programs. In each case, plan the
modifications first; then carry them out; then eliminate any compile
and/or link problems; and finally, carry out a range of tests, and
correct any run-time problems which are uncovered. Schedule at most 55
minutes for each of the two exercises: that is, even if you are not
finished with Exercise~1 after 55 minutes (10:45), put it aside and
start on Exercise~2; similarly, even if you are not finished with
Exercise~2 after a further 55 minutes (11:40), put it aside and proceed
to preparing your formal report.

\item You are allowed approximately 20 minutes at the end of the lab
session for preparing and submitting the formal report. If you cannot
complete it in this time, complete it on your own time afterwards.
However, you should {\it not} spend more that one hour, in total,
preparing and submitting the formal lab report. The report {\it must} be
submitted within one week of the day on which your lab session is
scheduled.

\item If you do not get the exercises completed during the lab session,
make sure that you come back and complete them on your own time, before
the next session. You should {\it not\/} include any description of this
further work in your formal report.

If you get stuck, look for help, either via the e-mail
\htmlref{feedback}{feedback} mechanism, or by coming to the
\htmlref{tutorial}{tutorial}!

\end{enumerate}

\paragraph{Hints}

The hints given below provide some further ideas on how to go about
completing the exercises.  But try to do the exercises under you own
steam first.  If and when you get stuck, you can come back and try here
for further inspiration.

\subparagraph{General}

\begin{itemize}

\item As you modify either of the given programs, keep testing them (and
saving them!). {\it Do this as you go along}.

That is, each time you have made some kind of single, self-contained,
modification, save the file, and try it out if possible. For example, if
you have added a new statement, or a declaration of a new variable, then
this should, as a minimum, not have introduced any new compile or link
time problems. So check that this is the case before going any further.
In many cases, you will be able to do even better than this. If you have
just introduced a new \tty{printf()} statement, for example, then you
should immediately be able to check that it actually works - that it
does print out what it should! And so on.

In this way the scale of the "current" problems with your program is
always kept small and manageable.  Whereas, if you make {\it all\/} your
modifications before trying {\it any\/} of them, then you are likely to
be overwhelmed by the problems, and not know where to even start in
trying to solve them.

\item Whenever your program is supposed to read data in
it is a good idea to have the program immediately print it back out
again, before reading anything further.  In this way you can separate
problems to do with {\it reading\/} the data from problems to do with
{\it processing\/} it.

\item Sometimes when you have a program running under the Turbo-C++
IDE you may
decide, for whatever reason, that you want to terminate it {\it
immediately\/} rather than going through whatever procedure is required
to get it to finish "naturally". For example, if the program needs to
read in 50 numbers, but it already clear that the first has been
mis-read, you don't want to bother typing in the remaining 49. Or (as
can easily happen) you program may get into an "infinite" loop, such
that it will {\it never\/} terminate "naturally".  In such
circumstances you can usually abort the program by typing
\tty{Ctrl-Break}.  That is, press down and hold the \tty{Ctrl} key
(located to the left of the space bar), and then press and release the
\tty{Break} key (also labelled \tty{Pause}: the \tty{Break} legend is on
the front face of the key; it is located at the right end of the very top
row of keys). You may have to do this twice before it will take effect.
The program should then be terminated, and control returns to the normal
Turbo-C++ IDE environment.\footnote{If this {\it still} doesn't kill the
  program, then you will probably have to use the \tty{Reset} button on
  the computer system unit, in order to reset the whole computer.  But
  the reset procedure is quite slow, and, of course, you will lose any
  modifications to files which have not been saved to disk again.
  So this is a very last resort!}

\end{itemize}

\subparagraph{Exercise 1: MATMUL}

\begin{itemize}

\item You are asked to modify the program to handle arbitrarily sized
matrices (up to some maximum). You might think therefore that the
arrays should not be declared until the program has read in the
appropriate sizes. However, this is not possible in \C. Arrays must have
their sizes fixed at {\em compile\/} time. You can get around this by
sizing the arrays big enough to accommodate the {\it maximum} you really
want to deal with. Then, at run time, when the "actual" sizes are read
in, you can arrange for the program to use only as much or as little of
the available array "space" as necessary - any left over can be simply
ignored.\footnote{This strategy might run into difficulty if we were
  concerned, for whatever reason, to only use as much memory as absolutely
  necessary.  Fortunately, this does not apply to the current exercise.}

\item The original program has four main parts: first the contents of
array \tty{A} are read in; then array \tty{B} is read in; then the
calculations are done (\tty{C} is calculated); and, finally, \tty{C} is
printed out.  The new program can reasonably retain this overall
structure, so you should try to identify for yourself, exactly how the
original program is broken down into these parts.

\item In the reading of array \tty{A} in the original program, a single
\tty{scanf()} call is used to read one entire row (four values).  This
is repeated three times to read the entire array.  In the new program
the width of the array is not fixed; so you cannot use a single
\tty{scanf()} call to read a whole row anymore.  Instead you will have
to use a single \tty{scanf()} call to read just {\it one} value.  This
can then be embedded in a (new) \tty{for} loop which iterates it for the
correct number of columns so that one complete row is read. This whole
loop can then be controlled by the "original" \tty{for} loop,
iterating over the rows (though with some further, minor, modification).

Of course, similar considerations apply also to reading in the \tty{B}
array, and printing the \tty{C} array.

\item Note that {\it multiple} statements can be controlled, or
iterated, by a single \tty{for} statement. The set of statements to be
iterated is simply enclosed in "curly brackets" or {\it
  braces}.\footnote{This is actually a very general point in \C:
  anywhere a single statement can be legally used, then a whole set of
  statements, enclosed in braces, can be used instead.}

\item The program \tty{MATMUL} introduces a new operator, written
\tty{+=}.  This is a combination of addition and assignment. The
statement:

\begin{verbatim}
   x += y;
\end{verbatim}

is exactly equivalent to:

\begin{verbatim}
   x = (x + y);
\end{verbatim}

There are corresponding composite operators for all four basic arithmetic
operations (addition, subtraction, multiplication, division). If you
ever in doubt as to their effect, just write out the long form
instead.

\end{itemize}

\subparagraph{Exercise 2: Bubble Sorting}

\begin{itemize}

\item You are asked to read in, and sort, a list of numbers which are
said to be of type \tty{double}.  \tty{double} is yet another \C\ data
type - like \tty{int}, \tty{float} and \tty{char}.  \tty{double} is most
similar to type \tty{float}: it is also used to approximately represent
"real" numbers. It differs from type \tty{float} is that it normally
has greater precision (more significant digits) and greater range (can
handle larger and smaller numbers - can have a bigger absolute value in
the "exponent" part in "scientific" notation). Type \tty{double} is
actually the most common "preferred" type for general purpose
calculations.  By that I mean that, if you need to represent numbers,
your first choice should normally be to use type \tty{double}; and you
should use something else only where there is some definite reason for
doing so.

Having said that, type \tty{double} does introduce a few new problems of
its own. Therefore I suggest that you initially {\it ignore\/} the
reference to type \tty{double}.  That is, first try to get the program
to read and sort a list of numbers of type \tty{float} (or even of type
\tty{int}).  When you have got this working successfully then go back
and try to modify it for type \tty{double}.\footnote{Be warned: when
  using \tty{scanf()} to read values into a variable of type
  \tty{double}, the correct format specification is \tty{\%lf} rather
  than \tty{\%f}; but, paradoxical as it seems, you should still use
  \tty{\%f} as the format specification for {\it printing\/} values of
  type \tty{double} with \tty{printf()}.}

\item The length of the list of numbers is not fixed in advance. But
just as with \tty{MATMUL}, you need to fix the size of array for holding
the list to some definite value, which will then be the {\it maximum}
length the program can deal with. The exercise does not explicitly state
a required maximum. I suggest that you get it to work for lists at least
up to 100 numbers long.

\item The original \tty{BUBBLE.C} program does not read in the array to
be sorted.  Instead the list is explicitly initialised in the program.
However, in the modified program, the list {\it must\/} be read in at
run time. You have already encountered code for doing that general sort
of job in program \tty{MATMUL.C}, so look at that for examples or
inspiration.

\end{itemize}


\subsubsection{Session 4: Week 7/8}

Enter, compile, and test the program \htmladdnormallink{WOTRATE.C}
{wotrate.c}, shown on pages 22--23 of {\it Illustrating C}. Then carry
out Exercise~3 of Chapter~2. For your convenience the exercise is
reproduced below.

\paragraph{Exercise 3: User Written Functions}

For the math library functions \tty{sin(x)} and \tty{cos(x)}, the value
of \tty{x} must be expressed in radians.  Write functions \tty{Sine(a)}
and \tty{Cosine(a)}, for which the argument, \tty{a}, must be expressed
in degrees of arc.  All types are \tty{double}.

\paragraph{Preparation}

Prepare a file (called \htmladdnormallink{\tty{WOTRATE.C}}{wotrate.c})
containing the program listed on pages 22--23 of the textbook. This {\it
must} be done in advance of the lab session.\footnote{You should have
  found that, if you click on the hot-linked file name, you can get a
  display of the file, within Mosaic.  You can, of course, retype the
  program from this display into the Turbo-C++ IDE.
  However, you may also save the
  file directly from Mosaic, using the \tty{Save As} menu item on the
  \tty{File} menu.}

\paragraph{Hints}

\begin{itemize}

\item In testing the \htmladdnormallink{\tty{WOTRATE.C}}{wotrate.c}
program, it is essential that you prepare a number of test cases for
which you know "with certainty" what the correct answers are - so that
you can decide whether the program is giving these correct answers or not.
"Certainty" is hard to come by, of course. But in this particular
case, you may be able to use some of the work you
have done in previous lab(s) to generate "reliable" test cases.

\item In Exercise~3 you are asked to write two new functions.
Implicitly, of course, you are also expected to check whether your
functions \tty{Sine()} and \tty{Cosine()} work correctly or not.  But
note that a function does not do anything unless and until it is called.
So to properly complete this exercise, there must be a \tty{main()}
function which allows you to exercise the \tty{Sine()} and
\tty{Cosine()} functions.

\item For Exercise~3, your essential problem is to convert from degrees
to radians - since, if you could do that, you could the use the {\it
existing} library functions \tty{sin(x)} and \tty{cos(x)} to complete
the required calculations.  So: as a first step, try to write a program
which just has a \tty{main()} function which does this conversion from
degrees to radians.  Then modify this program so as to encapsulate the
actual conversion proper in a function of its own. Then add the function
\tty{Sine()}, and finally the function \tty{Cosine}.  At each stage make
sure that everything is working correctly: do not try to do too much at
any one step.

\end{itemize}

\subsubsection{Session 5: Week 9/10: {\it Introducing Recursion}}

\label{lab5}

This exercise is divided into 4 parts. For each part
your report should have separate sections labelled \tty{Plan},
\tty{Coding} and \tty{Testing}. There should be a single overall
\tty{Conclusion} section.

The first two parts represent revision of material already encountered
in previous exercises: arrays, user defined functions, the \tty{for}
statement, the \tty{printf()} function etc. The third and fourth parts
introduce the notion of {\it recursion} - a function which calls or
invokes {\it itself}!

\begin{enumerate}

\item Develop (i.e., design, enter, compile, test and debug) a function
called \tty{print\_array(array, size)}. The parameter \tty{array} is an
array of integers (each of type \tty{int}) and \tty{size} is the number
of entries in \tty{array}. The function \tty{print\_array()} should have
the effect of displaying the contents of \tty{array}. Each element of
\tty{array} should be displayed on a separate line. Use a \tty{for}
statement to achieve the required repetition.

\item Develop a function called \tty{reverse\_print\_array(array,
size)}. The parameter \tty{array} is an array of integers (each of type
\tty{int}) and \tty{size} is the number of entries in \tty{array}. The
function \tty{reverse\_print\_array()} should have the effect of
displaying the contents of \tty{array}, but in {\it reverse} order (i.e. the
last element of \tty{array} should be displayed first etc.).
Each element of \tty{array} should be displayed on a
separate line. Use a \tty{for} statement to achieve the required
repetition.

\item Study the definition and discussion of the {\it factorial}
function, on page~25 of {\it Illustrating C}. Enter, compile, and test
the program \htmladdnormallink{FACTRIAL.C}{factrial.c}. Note that this
program {\it cannot} work correctly for indefinitely large integers.
Attempt to identify the biggest integer for which the function gives the
correct answer.

\item Develop a function called \tty{summer(n)}. The parameter \tty{n}
is an integer (type \tty{int}). \tty{summer(n)} should have the effect of
calculating the {\it sum} of all the integers up to \tty{n}, inclusive.
It should achieve the required repetition using {\it recursion}. Attempt
to identify the biggest integer for which the function gives the correct
answer.

\end{enumerate}

\subsection{Term 2: Weeks 11--20}

\subsubsection{Session 6: Week 11/12: {\it More Recursion}}

This exercise is divided into 2 parts. For each part
your report should have separate sections labelled \tty{Plan},
\tty{Coding} and \tty{Testing}. There should be a single overall
\tty{Conclusion} section.

\begin{enumerate}

\item Enter the file \htmladdnormallink{HCF.C}{hcf.c},
shown on page 24 of {\it
Illustrating C}. Add a definition of a suitable \tty{main()} function.
Then compile, test, and debug the completed program.

\item Modify the function \tty{reverse\_print\_array()}, developed in
step~2 of \htmlref{Laboratory Session~5}{lab5},
so that it uses {\it recursion} rather than a \tty{for}
statement to achieve the required repetition. Compile, test, and debug
the completed program.

\end{enumerate}

\paragraph{Hints}

\begin{itemize}

\item This exercise is concerned exclusively with the idea of {\it
recursive} functions.  It is essential that, before attempting
it, you are sure you understand the concept of a {\it function}.
So, before coming in for this session ensure that you have
thoroughly studied Chapter~2 of {\it Illustrating~C}, and the
accompanying sections of the on-line notes.

\item Before even bothering to test the \tty{HCF()} function, make sure
that you understand {\it what} it is trying to do (calculate the
"highest common factor" of two numbers) and {\it how} it is trying to do
it.  Please include in your report a short explanation (two or three
sentences), in your own words, of {\em why} Euclid's method of
calculating the highest common factor works.

\item Note carefully the introduction of a new operator in the \tty{HCF()}
function - the {\it remainder} operator, denoted in \C\ with the symbol
\tty{\%}. Thus, in dealing with {\it integer} arithmetic, we have
essentially two different kinds of division operator: the {\it quotient}
operator (denoted by \tty{/}) and the {\it remainder} operator denoted
by \tty{\%}.  This distinction does not arise in {\it floating point}
arithmetic, where only the {\it quotient} operator is required (why?).

\item To test the function \tty{HCF()} you must first provide a
\tty{main()} function in order to form a complete program (remember:
{\it every} complete C program file {\it must} contain the definition of
a function called \tty{main()}).  In this particular case, the
\tty{main()} function needs to do just whatever is required to allow you
to decide whether the \tty{HCF()} function is working correctly or not.
Minimally this means that it must {\it call} the \tty{HCF()} function
with some particular arguments, and should then print out the result
which is \tty{return}'ed by \tty{HCF()}.  But, of course, to properly
test \tty{HCF()} you will need to test it with a range of different
arguments.\footnote{Think carefully about the selection of test cases.
  For example do you expect there to be some biggest numbers for which
  the \tty{HCF()} function will work? Smallest numbers? Should it work
  if either of the arguments is zero? Should it work for negative
  arguments? Does it matter which argument is given first - the bigger
  or the smaller? And so on...}
One option is to simply edit the \tty{main()} function, and
rebuild (compile and link) the program before running each test.  This
is simple and perfectly satisfactory.  But if you have the time, and
wish to be a little more adventurous, you might try to write a
\tty{main()} function which would prompt the user to type in test
arguments, and then feed them into \tty{HCF()}: this would allow a whole
range of tests to be done simply by re-running the program (i.e.\
without having to rebuild each time).

\item In the second part of the exercise you are required to develop a
variant on a function you were originally supposed to have developed in
the previous lab session.  It is therefore {\it vital} that you actually
complete that previous exercise {\it before} coming in for this
lab session!

\item You are required to use {\it recursion} to implement the
repetition required in \tty{reverse\_print\_array()}. The essential idea
of recursion is that a function actually calls or invokes (a copy of)
itself.

The way that can be used in this particular exercise is as
follows: suppose that a single call to \tty{reverse\_print\_array()}
just prints the last element of the array it is given (assuming the
array is not of zero length), and then calls itself (i.e. another copy
of \tty{reverse\_print\_array()}) to print the rest of the array (i.e.
passing on the same array it was given, except "minus" the last
element).  And if \tty{reverse\_print\_array()} is called with a zero
array length argument, it should simply \tty{return} immediately - that
allows the recursion to "unwind" with all the copies of the function
then exiting in turn, until we finally get back to the \tty{main()}
function. Of course, the idea of passing on the array "minus" the last
element can be achieved simply by passing on a array length argument
which is one less that the argument which has been passed in - the array
"itself" does not actually have to be modified.

\end{itemize}


\subsubsection{Session 7: Week 13/14: {\it Lab Test \#1}}

The notes for this test are provided in a separate document entitled
\htmladdnormallink{Laboratory Test 1}
{../test1/test1.html}.

\subsubsection{Session 8: Week 15/16: {\it Encryption}}

"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 a called a substitution cipher, in which each letter of the
original message (the "plaintext") is replaced by a different letter to
generate the coded message (the "ciphertext").

To simplify matters further, we will restrict our plaintext to use only
the upper case letters \tty{A} to \tty{Z}, 
and 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 "wrapping
around" back to \tty{A} again after \tty{Z} as necessary). The number of
letters to count forward is called the {\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 "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
characters are read in with the \tty{getchar()} function, what you
receive (in \tty{int} form) is the ASCII numeric code.  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 - except that if the sum is
greater than 90 you must "wrap around" to the start of the alphabet
again by subtracting 26.

You are required to develop a program which will input a stream of
characters, using \tty{getchar()}, and encode them with a Caesar cipher;
the ciphertext should be output with \tty{putchar()}; the program should
terminate when \tty{getchar()} signals that the end of the input stream
has been reached.  The key for the encoding should be represented in
your program with a symbolic constant.\footnote{That is, using something
  like \tty{\#define KEY 5}, or \tty{const int key = 5}. See page~34 of
  {\it Illustrating C}.}

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.  There are various ways of doing this, but one
relatively simple method is described in the \htmlref{hints}{hints8} section
below.

Test your program carefully. Record in your report log book what tests
you carry out, what results you expect, and what results actually occur.

Now think about the problem of cryptanalysis: that is, suppose you {\it
are} "the enemy" and have intercepted a transmission 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.

\label{vigenere}
Finally, if you have time, try to develop a program to implement the
somewhat more sophisticated {\it Vigenere} cipher, invented in the 16th
century by Blaise de Vigenere. 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 Vigenere key is thus
not a single number but a sequence of some fixed length - 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.

\paragraph{Hints}

\label{hints8}

Perhaps the simplest way of arranging for your program to take its input
from a file, and/or route its output to a file, is to use
so-called {\it command line redirection}. 

To do this
your program must already have been compiled successfully, resulting in
the creation of an executable version of it.  If your source file were
called \tty{foobar.c}, the executable version would be in a file called
\tty{foobar.exe}.  The executable version must be run from the MS-DOS
command line interpreter application 
(and {\it not} from within the Turbo-C++ \tty{IDE}) in order to use
redirection.  So you should start up an MS-DOS
Window by double clicking on the relevant icon in Program Manager.

Within this window you will first need to set the "current" drive and
directory
to where you have stored the executable program. This will normally
be the directory \verb#\#\tty{swe1\_tc} on drive \tty{D:}, so issue the
following commands:

\begin{verbatim}
    C:\WINDOWS&gt; d:
    D:\&gt; cd \swe1_tc
    D:\SWE1_TC&gt;
\end{verbatim}

Now execute your program, with a command something like this:

\begin{verbatim}
    D:\SWE1_TC&gt; foobar &lt;in.txt &gt;out.txt
\end{verbatim}

The $&lt;$ serves as the "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 $&gt;$ 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 use input redirection only, or
output redirection only, or both together.

Note that if you change your program you must rebuild it it again, from
within the IDE, {\it before} trying to rerun it in the MS-DOS application.

To close down the MS-DOS application, give the command \tty{exit} thus:

\begin{verbatim}
    D:\SWE1_TC&gt; exit 
\end{verbatim}

\subsubsection{Session 9: Week 17/18: {\it Projectiles}}

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 "initial" information provided for a particular run of the program
(by assigning explicit values to suitable variables) 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 rebuild, 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 values
of $x$ and $y$ at successive, "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
(see the previous discussion of \htmlref{redirection}{hints8})
and a graph plotted of $y$ versus $x$ (one way of doing this
is described in detail in
the \htmlref{Hints}{hints9} 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 {\it
  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$ multipled by
$\Delta t$; and the new $y$ position is the old $y$ position plus this
movement. This calculation would be {\it exact} if $V_y$ were {\it
constant}; if $V_y$ is {\it changing} (as it will be in our case) then
the calculation will still be {\it approximately} correct, as long as as
$\Delta t$ is "small" - namely small enough that the percentage change
in $V_y$ in that time is "negligable".  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 {\it 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 {\it constant}, equal to
its initial value. There {\it 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 {\it negative} because our $y$ co-ordinate is positive in the upward
direction and gravity works {\it downward} (last time I checked anyway...).
This {\it 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, of course, 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.

In the first place, the repetition or iteration in your program should
be achieved using a \tty{while} statement.  However, if you succeed in
getting this working satisfactorily, you should then experiment with
using a \tty{for} statement instead.

\paragraph{Hints}

\label{hints9}
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 {\it 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}
D:\SWE1_TC\&gt; 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 "x" co-ordinate, and the
second as the "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.


\subsubsection{Session 10: Week 19/20: {\it Letter Frequencies}}

In a world where there are code {\it makers} there will, inevitably,
also be code {\it 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 "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 a 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, {\it 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.

\paragraph{Part 1: Counting}

Your first task in this exercise is to write a program which will read a
file (using \tty{getchar()} as usual), and count how many times each
alphabetic character occurs.  It should ignore distinctions between
upper and lower case, and should ignore all non-alphabetic
characters.\footnote{That is: both \tty{a} and \tty{A} should contribute
  to the count for the letter "a"; and non-alphabetics should not
  contribute to any count.}
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}.

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


\paragraph{Part 2: Statistics}

Next you are required to enhance the basic program (rename it at this
stage, to avoid overwriting your first program!). This enhanced program
should calculate the {\it total} number of all alphabetic characters read,
and output, for each character, both the actual number of times it
occurred, and the {\it percentage} this represents of the total number of
alphabetic characters encountered.

Again, test and document the program carefully.

\paragraph{Part 3: Graphing}

Finally: develop a further version of the program, which, instead of
outputing the relative frequencies as {\it numbers}, outputs a {\it
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 *'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}

 - and so on.

Note that histograms would normally be plotted with the independent
variable oriented vertically, whereas I have described an horizontal
orientation here.  If you have time, try to alter your program again, to
yield a histogram with a vertical orientation.


\section{Tutorials}

\label{tutorial}

A voluntary, "walk-in", tutorial will be offered
each Tuesday, from 10.00--11.00 pm, in the CAE lab. At least one of the
instructors and/or demonstrators will be present at this time.  This is
an excellent opportunity to look for help in completing any lab
exercises which you have outstanding, particularly if you are stuck with
some problem you simply can't seem to overcome.

You can, of course, submit queries by e-mail at any time (see
\htmlref{Feedback}{feedback}); but this may be impractical for various
reasons (e.g., if your problem is that you can't get the mail system to
work!). In such cases, the tutorial is your opportunity to get the
problem sorted.

\section{Assessment}

The course will be assessed by way
of two supervised {\it Laboratory Tests}. The first of these will take
place at the start of Term 2, the second at the end of Term 3. The
overall subject mark will be a weighted sum of the marks achieved in
these two tests: 25\% from the first, 75\% from the second.

The format of the tests will
be very similar to the format of the normal lab exercises. Each student
will work alone. The tests will be of three hours duration.
Instructions will be accessed via the \tty{World Wide Web}.
The work to be done will be derived from work done during the normal lab
sessions - though it will, of course, differ in detail. A report will
be required, submitted electronically. This report will form the basis for
marking the test.

Detailed information on the format of the report, and the marking
scheme to be used, are available in the
\htmladdnormallink{Laboratory Report Guidelines}
{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/rptfmt/rptfmt.html}.

Students who are {\em repeating\/} this course in 1994/95 will be
offered the option of being assessed on the previous model (three hour
written examination) instead. All students who intend to avail of this
alternative should confirm that {\em in writing\/} to me as soon as
possible.

\section{Feedback}

\label{feedback}

You can give me feedback on any aspect of the course, or ask questions
etc., by sending e-mail to \tty{mcmullin@ugmail.eeng.dcu.ie}. I normally
check this mailbox at least once every day, and will respond as quickly
as I can.  This is far and away the most reliable and effective way of
getting in touch with me.

\section{Other On-Line Resources}

This complete document is available in
\htmladdnormallink{LaTex}{swe1root.tex}\footnote{LaTeX is a typesetting
  mark-up language, particularly suitable for hierarchically organised
  documents, and documents using mathematical notation extensively.  It
  is a de-facto standard in academic publishing. A LaTeX source file is
  still a form of ASCII, but with typesetting commands interspersed with
  the "raw" text.  It can be read with any tool which can display ASCII
  files.}
and plain \htmladdnormallink{ASCII}{swe1root.txt} forms.  Thus, you can
download the document and browse it offline.  However, note that it is
rather large (c.~200KBytes) - you would not be able to load it with, for
example, the MS-Windows \tty{NotePad} application. But you could view it
with the built-in editor of the Turbo-C++ IDE.\footnote{Alternatively,
  you might want to install a copy of the
  \htmladdnormallink{Programmer's File
  Editor}{ftp://ftp.hea.ie:/pub/windows/programr/pfe0507.zip}. This is a
  powerful (and free!) professional text editor for Windows. It does the
  same job as NotePad, but much better!}

There is a separate detailed document dealing with the 
\htmladdnormallink{C Standard Library}
{http://www.eeng.dcu.ie/\%7Emcmullin/swe1/stdlib/stdlib.html}.
Again, it is also available for downloading, and offline browsing, in
\htmladdnormallink{LaTex}{stdlib.tex}
and plain \htmladdnormallink{ASCII}{stdlib.txt} forms.

There is also a very wide range of resources available elsewhere
on the Internet, on
the subjects of \C\ and {\bf C++} programming. Pointers to many of these
have been collected on the Web Page called
\htmladdnormallink{Learn C/C++ Today}{http://vinny.csd.mu.edu/learn.html}.
If you are looking out for further elaboration or alternative approaches
to the C language I strongly recommend that you have a browse through
the materials identified by this site.

\section{Copyright}

This Hypermedia Document is copyrighted, \copyright\ 1994, 1995, by
\htmladdnormallink{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.

\end{document}
</pre></body></html>