%font declarations
%
\font\normalfont=cmr12
\font\bold=cmbx12
\font\ital=cmsl12
\font\copyrightfont=cmfib8      %
\font\headfont=cmcsc10          %used for page headers
\font\headnumbfont=cmbx12       %used for numbers in page headers
\font\footfont=cmr8             %
\font\referencefont=cmti12      %used for book and journal titles in footnotes
\font\chaptitlefont=cmss17      %
\font\afont=cmr12               %
\font\bfont=cmbx12              %
\font\cfont=cmbx12              %
\font\programfont=cmtt12        %
\font\pf=cmtt12                 %
\font\problemfont=cmbx12        %
\font\mathfont=cmmi12
\global\textfont0=\normalfont
\global\textfont1=\mathfont

\def\uncatcodespecials{\def\do##1{\catcode`##1=12 }\dospecials}
\def\setupverbatim{\programfont
        \def\par{\leavevmode\endgraf} %\catcode`\`=\active
        \obeylines
        \uncatcodespecials
        \obeyspaces
}   
{\obeyspaces\global\let =\ }   

        
%\input /users/walker/setup.standard
\def\inputprogram#1{
        \bigskip
        \hrule width5.5truein
        \bigskip
        \hsize=7.0truein
        \leftskip=-0.5truein

        \begingroup\setupverbatim
        \input #1 
        \endgroup

        \leftskip=0.0truein
        \hsize = 6.5truein
        \bigskip
        \hrule width5.5truein
        \bigskip}

% This defines the date.
%
\def\today{\ifcase\month\or
  January\or February\or March\or April\or May\or June\or
  July\or August\or September\or October\or November\or December\fi
  \space\number\day, \number\year}
%\def\today{May 10, 1996}

% Program Macros
%
\newcount\programcounter
\programcounter=0

\newcount\firstprogrampage
\firstprogrampage=1     %0 = not first page of program
                        %1 = new sample program starts on current page
\def\programname {}

%  Definition of program
\def\newprogram#1#2{

%  #1 = program/file name
%  #2 = initial commentary

\global\firstprogrampage = 1

\vfill\eject

\advance \programcounter by 1
\noindent
{\bold Program \number\programcounter:  #1}
\gdef\programname{#1}
\global\firstprogrampage = 0

\noindent
#2

{\parskip = 0pt

\inputprogram{#1}

}
}

%  Definition of code segment
\def\newcode#1#2{

%  #1 = program/file name
%  #2 = initial commentary

\global\firstprogrampage = 1

\vfill\eject

\advance \programcounter by 1
\noindent
{\bold Code Segment \number\programcounter:  #1}
\gdef\programname{#1}
\global\firstprogrampage = 0

\noindent
#2

{\parskip = 0pt

\inputprogram{#1}

}
}

%  Annotation Header
\def\ann{

\noindent
{\ital Annotations for {\programfont \programname}:}

}

\def\i{\item{$\bullet$}}
\def\ii#1{{\parskip = 0pt
\itemitem{$\S$} #1

}}

%  Sample run
\def\samplerun#1{

\goodbreak
\noindent
{\ital Sample Run of {\programfont \programname}:}

{\parskip = 0pt

\inputprogram {#1}

}}


%Header Declaration
%
\headline = {\ifnum\programcounter>0 
      \ifnum\firstprogrampage=1
           \rm Sample Program \number\programcounter: 
                 \programname, continued \hfil
      \else\hfil\fi
\else\hfil\fi}

% Footer Declaration
%
\footline = {{\hsize=6.5truein \leftskip = 0pt \rightskip = 0pt
\footfont C++ through Examples \hfil
                \today \hfil
                Page \number\pageno}}

%----------------------------------------------------------------------------
\parindent = 20pt
\parskip = 6pt
\normalfont
%Define Page Parameters
%
\raggedbottom
\interlinepenalty=1000
\hsize=6.5truein        %use 7.0truein for fuller page
\vsize=9.5truein
\voffset = -0.4truein

\ 

\vfill
\centerline {\chaptitlefont An Introduction to C++}
\bigskip
\centerline {\chaptitlefont Through Annotated Examples}
\bigskip
\bigskip
\centerline {\bold by}
\medskip
\centerline {\bold Henry M. Walker}
\medskip
\centerline {\bold Grinnell College, Grinnell, IA}

\vfill
\centerline {\rm \copyright 1997 by Henry M. Walker}

\noindent
{\rm
Permission to make digital or hard copies of all or part of this work for
personal or classroom use is granted without fee provided that copies are
not made or distributed for profit or commercial advantage and that copies
bear this notice.

\noindent
Use of all or part of this work for other purposes is prohibited.

}
%-----------------------------------------------------------------------------
\newprogram {quarts-1.cc}
{The first program converts a number of quarts to liters, using stream IO
from the keyboard.
}

\ann

\i Comments in C$++$ may be denoted in either of two ways:
\ii {A comment begins with {\pf //} anywhere on a line and continues to the
end of the line.}
\ii {A comment may begin anywhere with the symbols {\programfont /*},
continuing until the symbols {\programfont */}, on the same or later lines.}

\i C$++$ makes use of libraries for many common operations.  The statement
\hfil\break
{\programfont ~~~~~\#include <iostream.h>} 
\hfil\break
instructs the machine how to use the iostream operations.

\i Variables may be declared almost anywhere within a C$++$ program.  Here,
{\programfont quarts} and {\programfont liters} are declared globally as
integer and real variables, respectively.  The term {\pf double} specifies
a real number, stored using double precision. (The term {\pf float} may be
used for single precision, real numbers.)

\i Each C$++$ program contains a driver function/program, called 
{\programfont main}.  Here, main uses no input parameters (hence the word
void in parentheses).  At termination, {\programfont main} returns an error
code (an integer), so the word {\pf int} appears before {\pf main}.  By
convention, code 0 indicates no errors were encountered in the program.

\i Braces $\{$ and $\}$ are used in C$++$ to mark the beginning and ending of
blocks.  In this case, the braces indicate the statements for the main
program.

\i  Semicolons (;) are used to terminate every statement in C$++$.

\i  The equal sign (=) is used for assignment.  (We will see later that == is
used for the Boolean comparison operator.)

\i  Arithmetic operations include +, $-$, *, and / for addition, subtraction,
multiplication, and division.  For integers, the division operation /
yields the integer quotient, while the modulus operation \% gives the
remainder. 

\i cin and cout are defined within iostream for simple input and output,
respectively.  endl is the symbol to move to a new line in output.

\samplerun {quarts-1.out}

In this sample run (run on the machine {\ital steenrod}), the program
(called {\pf quarts-1.cc}) is compiled and run using the g$++$ compiler.

Since the program reads quarts as an integer, the input 3.5 is read as the
integer 3 in the third run of the program.  If additional input were
requested within the program, the next characters read would be .5 .

%-----------------------------------------------------------------------------
\newprogram {quarts-2.cc}
{Another program to convert a number of quarts to liters.
}

\ann

\i Variables can be declared within a function any time before they are
used.  Thus, variables are commonly declared at the beginning of a
function, so they can be used any time within that function.  

\i The {\programfont assert} statement checks the validity of a Boolean
expression. If the statement is true, program execution continues without
interruption.  If the condition is false, however, the program is
terminated, with an appropriate error message printed.

\i The {\programfont assert} statement provides a simple mechanism to verify
pre-conditions and post-conditions, although more sophisticated approaches
are needed if the program is to resolve the problem and resume processing.
(This latter approach is accomplished by exception handlers, to be
discussed at a later time.)

\samplerun {quarts-2.out}

%-----------------------------------------------------------------------------
\newprogram {quarts-3.cc}
{Program illustrating variable declaration and initialization, together
with simple error checking.}

\ann

\i C$++$ allows variables to be declared at any point within a function
prior to the use of the function.  Thus, in this program, {\programfont
quarts} is declared after the {\programfont cout} line, and {\programfont
liters} is declared after either the {\programfont cout} or {\programfont
cin} lines.

\i C$++$ also allows a variable to be initialized when it is declared by
specifying the variable's initial value as part of the declaration.  If
this initial value were not given as part of the declaration, then the 
declaration line for {\programfont liters} would be replaced by the two
lines:
\hfil\break
{\programfont 
double liters;
\hfil\break
liters = quarts / 1.056710;}

\i Experienced C$++$ programmers disagree upon whether variable
declarations should normally be placed at the start of a function or
whether variables should be declared just before they are needed.  
\ii {Variables declared at the start of a function often are easier for a
programmer to find and check.}
\ii {When variables are declared as needed, memory allocation may not be 
needed if a section of code is skipped during specific runs of a program.}

\i For clarity in the following examples, variables normally are declared 
at the start of functions, unless there are special reasons to proceed
otherwise. 

\i The {\programfont while} loop continues as long as the condition
specified is maintained.  The general syntax is:
\hfil\break
{\programfont while (condition) statement ;}
where condition is any Boolean condition and the statement is any single
statement.  When several statements are to be executed in the body of a
loop, they are enclosed in braces $\{~~\}$, as shown in the example.

\samplerun {quarts-3.out}

%-----------------------------------------------------------------------------
\newprogram {smallest3-1.cc}
{Simplistic program to find the smallest of three integers.}

\ann

\i The simple {\pf if} statement has the form:
\hfil\break
{\pf if (condition) statement}
\hfil\break
Here, the ``condition'' is evaluated, and the ``statement'' is executed if
the ``condition'' is true.  Otherwise, the ``statement'' is skipped.  

\i Simple comparisons may use the relations:  {\pf <, <=, >, >=, ==} and
{\pf !=}.  Here {\pf !} means ``not'', so {\pf !=} means ``not equal''.

\i  Technically in C$++$ any zero value is considered as false, while any
nonzero value is considered true.

\i {\ital Caution:}  Programmers who may have programmed in other languages
sometimes mistakenly write {\pf =} for {\pf ==}.  In C$++$, the compiler
will interpret the {\pf =} as an assignment.  Thus, the statement
\hfil\break
{\pf if (i = j) cout << "Equal" ;}
\hfil\break
will assign the value of {\pf j} to {\pf i}.  If the value of {\pf j} was
0, then the result of the assignment is considered false, and nothing will
be printed.  On the other hand, if {\pf j} had a nonzero value, then the
assignment to {\pf i} returns a true (i.e., nonzero) value, and output is
generated.
\hfil\break
{\ital Be careful in writing comparisons to use  {\pf ==} rather than {\pf =}.}


\i Comparisons may be combined with {\pf \&\&} and {\pf ||} for ``and''
and ``or'', respectively.  The precedence of such operations follows the
familiar rules of Boolean algebra.  However, when in doubt, it is always
safer to use parentheses to clarify meaning.

\samplerun {smallest3-1.out}

%-----------------------------------------------------------------------------
\newprogram {smallest3-2.cc}
{Program to find the smallest of three integers, using two steps.}

\ann

\i The compound {\pf if} statement has the form:
\hfil\break
{\pf if (condition) statement1 
\hfil\break
else statement 2} 
\hfil\break
As with the simple {\pf if} statement, the ``condition'' is evaluated and
``statement1'' is executed if the ``condition'' is true.  In this compound
statement, however, ``statement2'' is executed if the ``condition'' is
false.

\i Note that both ``statement1'' and ``statement2'' end with semicolons (as
with all C$++$ statements.

\noindent
This program produces the same output as {\pf smallest3-1.cc}.

%-----------------------------------------------------------------------------
\newprogram {smallest3-3.cc}
{Program to find the smallest of three integers, using nested if statements.}

\ann

\i {\pf if} statements can be nested as desired.  Since each {\pf if}
statement is considered a single entity, such statements may be used
in either the ``then'' or ``else'' clauses of other {\pf if} statements.

\noindent
This program also produces the same output as {\pf smallest3-1.cc}.

%-----------------------------------------------------------------------------
\newprogram {smallest3-4.cc}
{Program to find the smallest of three integers, using nested if statements
with brackets for clarity.}

\ann

\i When several statements are to be used within ``then'' or ``else''
clauses, braces $\{~~\}$ are used to group the statements.  Such braces
also can be used around single statements for clarity.

\noindent
This program again produces the same output as {\pf smallest3-1.cc}.

%-----------------------------------------------------------------------------

\newprogram {quarts-for-1.cc}
{A program to compute the number of liters for several values of quarts.}

\ann

\i  The {\pf for} statement follows the syntax:
\hfil\break
{\pf for (initialization; condition; updates) statement;}
\hfil\break
Here, ``initialization'' (if any) is performed at the start, before any
Boolean expressions are evaluated.  The Boolean ``condition'' is evaluated
at the top of each loop iteration.  If the condition is true, the
``statement'' is executed. Otherwise, execution of the {\pf for} statement
terminates, and processing continues with the statement following the {\pf
for}.  The ``updates'' allow any variables or other work to be done after a
loop iteration, before the ``condition'' is evaluated again.

\i The $++$ operation associated with a variable increments the variable by
1.  Thus, {\pf i++} is the same as the statement {\pf i = i + 1}.
(Technically, {\pf i++} is a post-increment operation, while {\pf ++i} is a
pre-increment operation.  Here, the incrementing of {\pf i} takes place in
a statement by itself, and either operation has the same effect. Further
consideration of such subtleties is left to a later time.)

\i  Note that the {\pf for} statement is more general than in some other 
languages, as any initialization and updating are possible.  For example, the
{\pf while} loop is a special case of the {\pf for}, with empty
initialization and updating sections: 
%\hfil\break
{\pf for (;condition;) statement};
\hfil\break
That is, {\pf while (condition) statement;} is equivalent to 
\hfil\break
{\pf for (; condition; ) statement;}

\i In order to arrange the values approximately in columns, the program
prints a sequence of spaces, such as {\pf "~~~"} and {\pf "~~~~~~~~~~~"}.
The amount of space allocated for each number depends upon the size and
accuracy of the number.

\samplerun {quarts-for-1.out}

%-----------------------------------------------------------------------------

\newprogram {quarts-for-2.cc}
{A table of quart and liter values, using formatted output.}

\ann

\i Formatting of integers in C$++$ is relatively simple:  Only a width must
be given, and by default integers are right justified in the width given.
(If the integer requires more space than given by the width, then the width
in expanded as needed.)  The width must be specified for each number, as
shown in the program.   
\i Formatting of real numbers in C$++$ proceeds in several steps.
First, the program specifies that a ``fixed decimal'' representation is
needed, using the {\pf cout.setf(ios::fixed)} statement. (Alternatively,
the statement {\pf cout.setf(ios::scientific)} prescribes scientific
notation for output). Next, a number of digits to the right of the decimal
place may be prescribed with {\pf cout.precision(4)}.  Finally, the overall
width of the number, including the digits to the right of the decimal
point, is given following the same syntax as with integers.

\i If you want to switch between decimal representations, then you will
want to unset one format as you set the next.  For example, if a fixed
decimal format has already been given, then you would change to a
scientific format as follows:
\hfil\break
{\pf cout.unsetf(ios::fixed);
\hfil\break
cout.set(ios::scientific);}

\i The form of the output depends upon the machine if you omit {\pf
cout.setf(---)} or if you have set both the scientific and fixed modes at
the same time.

\samplerun {quarts-for-2.out}


%-----------------------------------------------------------------------------

\newprogram {quarts-for-3.cc}
{Another table of quart and liter equivalents -- this time including half
quarts as well.}

\ann

\i This program illustrates that the {\pf for} statement is quite general.
Here the control variable {\pf quarts} is real, rather than integer.  While
this seems reasonable in this context, note that roundoff error for real
numbers sometimes can provide unanticipated or incorrect results within
such loops.

\i In C$++$, the assignment {\pf quarts += 0.5} is shorthand for
{\pf quarts = quarts + 0.5}. More generally, the operator {\pf
+=} adds the value on the right-hand side of the operator to the variable
on the left-hand side.

\i Constants are declared within a program by specifying the type of the
variable, the initial value, and designating the variable as being a
constant, {\pf const}.  Thus, the declaration\break
{\pf const double conversion\underbar{~}factor = 1.056710;}
\hfil\break
indicates that the variable {\pf conversion\underbar{~}factor} will be a
double precision, real number with value 1.056710, and this value is not
allowed to change within the {\pf main} program where this constant is
defined.

\vfill\eject
\samplerun {quarts-for-3.out}


%-----------------------------------------------------------------------------

\newprogram {quarts-for-4.cc}
{This program illustrates the nesting of {\pf for} loops to produce a table
of liter equivalents.}

\samplerun {quarts-for-4.out}

%-----------------------------------------------------------------------------

\newprogram {darts.cc}
{A Monte Carlo simulation to approximate Pi.  More precisely, consider a
circle $C$ of radius 1 in the plane, centered at the origin.  Also,
consider the square $S$ of side 2, centered at the origin, so that the
corners of the square are at $(\pm 1, \pm 1)$.  If we pick a point
$P$ at random in $S$ or in the first quadrant of $S$.  Then the
probability that $P$ is also in $C$ is $\pi / 4$.}

\ann

\i This program illustrates the use of the random number generator {\pf
rand}, which is based upon a seed value kept internally.  {\pf rand}
returns pseudo-random positive integers.  {\pf srand} is used to set the
initial seed value, based upon the built-in {\pf time} function. The range
of the integer value returned by {\pf rand} depends upon the local machine
executing the code.  Some choices are noted in the program.

\i  The {\pf const} statements before the {\pf main} specify global
constants (and other expressions) for use throughout all functions.

\i The expression {\pf (double) MaxRandInt} performs type conversions.  In
the definitions from this program, {\pf MaxRandInt} represents an integer
value.  The prefix {\pf (double)} converts this to a real value for {\pf
MaxRandReal}. 

\i The function {\pf rand ()} returns a random integer value from the uniform
distribution from 0 to {\pf MaxRandInt}.  Since the program divides this by
a real value ({\pf MaxRandReal}), C$++$ converts the integer to a real
before the division takes place.  If we had not declared {\pf MaxRandReal}
as a real, but used {\pf MaxRandInt} instead, then we would need to convert
both {\pf rand ()} and {\pf MaxRandInt} to integers before performing the
division (otherwise we would obtain an integer result, in contrast to what
was intended).  This alternative conversion could be performed with the
revised statements
\hfil\break
{\pf 
x = (double) rand () / (double) MaxRandReal;
\hfil\break
y = (double) rand () / (double) MaxRandReal;
}

\samplerun {darts.out}

%-----------------------------------------------------------------------------

\newprogram {genfile.cc}
{This program illustrates the creation and printing of files.}

\ann

\i Stream I/O with files is analogous to stream I/O with the keyboard,
except for the initial steps of opening and closing the file.

\i Output streams are declared of class {\pf ofstream}.  

\i Once a stream {\pf f} is declared, it is opened or closed with the
statements \hfil\break
{\pf f.open (<file-name>)} and {\pf f.close ()}, respectively.

\i Output to a file uses the {\pf <<} operator, as with keyboard output to
{\pf cout}.

\samplerun {genfile.out}

%-----------------------------------------------------------------------------

\newprogram {printfile.cc}
{This program shows two simple ways to read from files.}

\ann

\i Input streams are declared of class {\pf ifstream}.  

\i As with files for output, input streams {\pf f} are opened and closed
with the statements {\pf f.open (<file-name>)} and {\pf f.close ()},
respectively.

\i Similarly, input from a file uses the {\pf >>} operator, as with
keyboard input from {\pf cin}.

\vfill\eject



\i The end of a file can be detected in either of two ways:
\ii {The function {\pf f.fail()} indicates whether the machine was
successful in its last operation on the file {\pf f}.  Thus, when {\pf
f.fail()} is used following an attempted read,  {\pf f.fail()} will return
false when a desired value was read and true otherwise (e.g., at the end of
the file).}
\ii {The expression {\pf (f >> r)} reads a value from {\pf f} to {\pf r},
as long as one exists, and it returns an updated file {\pf f} with the
value read extracted.  As long as this file is non-empty, it is 
considered non-zero or {\pf true}.  Thus, this updated file may serve as a
valid test within a {\pf while} loop.  When reading fails, {\pf (f >> r)}
returns 0 or {\pf false}, so the {\pf while} loop will terminate.}

\i {Another way to read a file uses the the end-of-file procedure as
demonstrated in the following code segment:}

{\parskip = 0pt
\parindent = 30pt
\pf

while (true)

~~~~$\{$ intfile $>>$ i;  /*  if $<$eof$>$ encountered, i is unchanged */

~~~~~~if (intfile.eof()) break;

~~~~~~cout $<<$ i $<<$ endl;

~~~~$\}$
}

\item {} The Boolean function {\pf f.eof()} returns {\pf true}
when the end of the file is encountered and {\pf f.eof()} returns false
otherwise.  Thus, {\pf f.eof()} indicates an attempt to read beyond the
last next character in the file.
\item {} While this approach often works, different systems may
handle {\pf <eof>} differently.  Thus, the use of {\pf f.eof()} may give
unpredictable results, and some authors advise against the use of this
procedure. 

\i As {\pf !} is the Boolean ``not'' operation, the program uses 
{\pf !f.fail()} to test when more data are present in the file for reading.

\samplerun {printfile.out}

%-----------------------------------------------------------------------------

\newprogram {max.min-1.cc}
{This following program computes the maximum, minimum, and average of n
real numbers.}

\ann

\i Arrays within C$++$ are declared by indicating the number of array
elements in square brackets [ ], as in the statement {\pf double a[n]}.
Also, since declarations may be made anywhere within a program, C$++$
allows an array size to be read first and then used within an array
declaration.

\i Individual array elements are accessed by placing a subscript in
brackets, such as {\pf a[0]} or {\pf a[j]}.

\samplerun {max.min-1.out}

\i C$++$ does not perform bounds checking when accessing array elements.
Thus, nonsense is printed for {\pf a[200]} when only {\pf a[0]} through
{\pf a[9]} are declared and given values.  Note especially that no {\ital
Subscript Out Of Range} error message is generated for the attempt to
access {\pf a[200]}.

\i The output $1.4013e-45$ may be interpreted as representing the number
$1.4013 \times 10^{-45}$, written in scientific notation.  Normally, {\pf
cout} will use this scientific notation for very large numbers and for
numbers very close to 0 in order to avoid printing numbers with many zeros.

%-----------------------------------------------------------------------------

\newprogram {max.min-2.cc}
{Use of vectors, defined by AP CS, behaves much like arrays in C$++$, but
includes the checking of subscript bounds.}

\ann

\i Vectors, as defined by AP CS, are declared by identifying the type of
data to be stored in the array together with the number of array elements.
For example, in the statement,
{\pf vector<double> a(n);}, an array of {\pf n} floating point numbers is
created, and these values are accessible through subscripts 0 through n-1.

\i When using vectors, the program must include information about the
appropriate AP CS material.  This is done with the beginning statement {\pf
\#include "vector.cc"}.  Here, the use of double quotes about {\pf
vector.cc} indicates that this material is located in the current user's
directory.  

\i Actually, vector information is included in two files, {\pf vector.h}
and {\pf vector.cc}, and the second file contains a statement to include
the first.  On many systems, the compiler is sophisticated enough, so that
{\pf vector.cc} can be compiled separately.  In such circumstances, a
user's program, such as {\pf max.min-2.cc}, includes only the header file,
with the statement {\pf \#include "vector.h"}.  The compiler then links in
the compiled material from a compiled version of {\pf vector.cc}.  Since
this alternative was unavailable on the author's machine, the entire {\pf
vector.cc} file is included here.

\i Use of these vectors is the same as for C$++$ arrays, although all
accesses to vectors includes an explicit test that a subscript is between 0
and n-1, inclusive.  If the subscript is not within range, an error message
is printed, and the program is terminated.

\i Details of AP CS vectors include the concepts of C$++$ classes and
objects and will be discussed later.

\samplerun {max.min-2.out}

\i The output for this program is the same as for {\pf max.min-1.out} when
all subscripts are within the declared range.  However, an error message is
generated and the program is terminated when any attempt is made to access
an element outside this range.

%-----------------------------------------------------------------------------

\newprogram {trap-1.cc}
{This program approximates Pi as the area of one-fourth of a
circle of radius 2.}

\ann

\i The main program uses the Trapezoidal Rule to approximate the area under
a function $y = f(x)$ on the interval $[a, b]$.

\i The function $f(x)$ is defined as a separate function.  Specifically,
{\pf double f} indicates that the function $f$ will return a floating point
number, and the header {\pf (double x)} specifies that $f$ will have a single,
floating point parameter.

\i The format of function $f$ is similar to that of main.  Both contain a
header (with possible parameters), followed by a function body in braces,
{\ital $\{$~~$\}$}.

\i Here, the entire function is declared first, before the main program.

\i A function computes and returns a value, and this value is designated
using a {\pf return} statement.  Here, the value returned is {\pf (sqrt(4.0
- x*x))}.  

\i The {\ital math.h} library of C$++$ contains many common mathematics
functions, including $\sin(x),~ \cos(x),~ \tan(x),~ exp(x),~ log(x),~
log10(x),~ pow(x, y),$ and $sqrt(x)$.  Here, $exp(x)$ computes $e^x$,
$log(x)$ computes the natural log, $log10(x)$ computes the common log, and
$pow(x,y)$ computes $x^y$.

\i In the computation of the Trapezoidal Rule, the constants $a$ and $b$
are specified as constants using {\pf \#define} statements in this program.

\samplerun {trap-1.out}

\i In compiling programs involving functions in {\ital math.h}, some
compilers require the use of the {\pf -lm} option, as shown.

%-----------------------------------------------------------------------------

\newprogram {trap-2.cc}
{This program uses a function for computations involving the Trapezoidal Rule.}

\ann

\i Functions either may be declared in full before a main program or a
header may be defined at the start with details given later.  This program
illustrates the second approach.  At the start, functions {\pf f} and {\pf
area} are identified with a header, which is terminated by a semicolon to
indicate that details are forthcoming later.  This header contains
information about the type of value returned by the function ({\pf double}
in each case here) and about the number and type of the function
parameters.

\i When function details are given later, the header information is
repeated, followed by the specific code elements.  

\i Within a function, variables may be declared and initialized, following
the same rules illustrated in previous examples for the main program.

\i This program produces the same output as the previous program.

%-----------------------------------------------------------------------------

\newprogram {trap-3.cc}
{This program computes the Trapezoidal Rule using a procedure.}

\ann

\i A function returning no value (a void result) is a procedure.

\i By default, C$++$ parameters are passed by value (at least for simple
variables).  Thus, in declaring {\pf double f(double x)} and calling {\pf
f(a)}, the value of $a$ is copied to $x$ before the computation of $f$
proceeds.

\i If a value is to be returned in a parameter (e.g., as an area), then
parameter passage by reference may be used, by adding an ampersand {\pf \&}
in the function header.

\i Once again, this program produces the same output as {\ital trap-1.cc}.
%-----------------------------------------------------------------------------

\newprogram {trap-4.cc}
{Another area computation, involving a home-grown square-root function
which tests that square roots are taken of non-negative numbers only.}

\ann

\i This program again produces the same output as {\ital trap-1.cc}.

%-----------------------------------------------------------------------------

\newprogram {trap-5.cc}
{Using the same area function for the computation of areas under two
functions.} 

\vfill\eject
\ann

\i This program represents a variation of program {\ital trap-2.cc}.  Here,
{\pf area} computes the area under $y = f(x)$ on $[a, b]$,
using $n$ trapezoids, and all of these elements ({\pf a, b, n, f}) are
passed as parameters.  

\i To declare a function parameter, the function is given a formal name
(e.g., {\pf f}), and information concerning its parameters and return type
are specified.  In the example, the header of {\pf area} contains the
information \hfil\break
{\pf double f (double)}
\hfil\break
which indicates that a function will be passed to {\pf area}.  This
function will take one double precision, real parameter and will return a
double precision, real number.  Further, when the details of {\pf area} are
defined, this function will be referred to as {\pf f} (just as the numbers
{\pf a, b} and {\pf n} will be used within {\pf area}).

\i When {\pf area} is called, an appropriate function name is specified for
{\pf f}, just as numbers are specified for {\pf a, b} and {\pf n}.  Thus,
in the call\hfil\break
{\pf area (0.0, 2.0, number, circle)}
\hfil\break
{\pf a} is given the value 0.0, {\pf b} is given the value 2.0, {\pf n} is
given the value {\ital number}, and {\pf f} will refer to the function
{\ital circle}.  Whenever {\pf f} is mentioned within {\pf area} during the
execution of this call, the function {\ital circle} will be used.
Similarly, for the call\hfil\break
{\pf area (1.0, 3.0, number, parabola)}
\hfil\break
the function {\ital parabola} will be used whenever {\pf f} appears.

\i In using function parameters, the actual functions  ({\pf circle} or
{\pf parabola}) must be of the type as the formal parameter ({\pf f}).  In
this case, the functions use one double parameter, and they returned a
double. 

\samplerun {trap-5.out}



%-----------------------------------------------------------------------------

\newcode {rational.h}
{The following code segment, called a {\ital header file}, defines some
simple elements of a new, rational-number data type.  In object-oriented
programming, such a data type is called a {\ital class}.  Subsequent code
segments show how a class is used and how implementation details are
specified.}

\ann

\i Conceptually, {\ital rational numbers} are fractions, with an integer
numerator and an integer denominator. {\ital rational.h} provides a simple,
user's view of such numbers, allowing a\break  programmer to create rational
numbers, use elementary I/O operations, and perform addition and
decimal division.

\i  In object-oriented programming generally and specifically in C$++$,
a data type combining both data and operations is called a {\ital class}.
This {\pf Rational} class contains 3 main elements.

\ii {An initial section (where the operator $+$ is defined) extends
familiar operations or references common operations using various details
of this class.}

\ii {A {\ital public} section defines operations for use by an
applications programmer.}

\ii {A {\ital private} section defines data types and operations involved
in the implementation of this class.  Such details may not be used directly
by applications; any explicit reference to these elements in a user's
program will yield a compiler-generated error.}

\item {} While all three of these elements may be specified in the
definition of a class, any of the above elements also may be omitted.

\i The definition of the operation $+$ given here allows the familiar
addition symbol to be used for rational numbers in addition to its
built-in capabilities for integers and real numbers.  This use of an
operator for several purposes (or data types) is called {\ital operator
overloading} or just {\ital overloading}.  The definition here is analogous
to any definition of a function, as shown in previous examples.  The use of
the modifier {\pf friend} grants the implementer of this operator
permission to access the internal fields {\pf numerator} and {\pf
denominator}. 

\i The first part of any public section usually includes operations which
indicate how initialization will take place.  In C$++$, these {\ital
constructor} operations always have the same name as the class itself.
Here, initialization may take any of three forms, depending upon how many
parameters are specified.  The following examples illustrate how these
constructors may be used.

\ii {A variable declaration \hfil\break
{\pf Rational a;} \hfil\break would declare {\pf a} to be a variable of
type {\pf Rational}.  (In the jargon of object-oriented programming, {\pf
a} is an object of class {\pf Rational}.)  Here, {\pf a} is declared
without any further information, so the first constructor is used.  The
comments for this constructor indicate that {\pf a} will be initialized to
zero, conceptually in the form $0/1$. }

\ii {A statement \hfil\break
{\pf Rational b(5);} \hfil\break
also would declare {\pf b} to be an object of class {\pf Rational}.  In this
declaration, the parameter {\pf 5} is given, so the second constructor will
be used.  The comments for that constructor indicate that {\pf b} will be
initialized to the number 5, in the form $5/1$.}

\ii {The declaration \hfil\break
{\pf Rational c(5, 8);} \hfil\break
would declare {\pf c} to be an object of class {\pf Rational}.  With two
parameters given, the third constructor will be used, yielding the value
$5/8$ according to the comments.}

\item {} These three variations of the constructor operation 
provide a second example of overloading -- this time for the name {\pf
Rational}.

\i Other public operations, defined here and available for general
programming, will include {\pf read}, {\pf print}, and {\pf eval}.

\i Details of all of these operations are not provided in the class
definition itself -- they must be given elsewhere.

\i As another part of object-oriented jargon, the operations defined within
a class are called {\ital methods}.  Thus, {\pf Rational}, {\pf read}, {\pf
print}, and {\pf eval} are all methods for objects of this new class.

\i The private section provides implementation information which may be
needed by a compiler (e.g., to allocate space or to provide linkage
addresses).  Here, the integer components of a rational number (i. e., the
{\pf numerator} and {\pf denominator}) are defined.

\i Note that the comments at the start of the file indicate that the
denominator of a rational number cannot be zero, and an error is reported
whenever any operation (e.g., {\pf read} or variable declaration) leads to
a zero denominator.  This restriction that denominator is non-zero is one
motivation for placing the fields, {\pf numerator} and {\pf denominator},
in the private section.  With this placement, a user cannot access the
denominator directly, possibly changing it to zero.  Thus, this class can
enforce the condition that the denominator of a rational number can never
be zero.

\i Since this header file only defines logical operations, it only
identifies what capabilities might be available for rational numbers.  It
does not produce any output by itself.

%-----------------------------------------------------------------------------

\newcode {rational.cc}
{An implementation file specifies the details of how class operations are
implemented.}

\ann

\i Each operation defined for class {\pf Rational} is defined, following
much the same syntax as other functions.

\i In providing the details of a specific operation or method, the function
header includes the prefix {\pf Rational::} to indicate that we are
providing code for the method for that class.  Thus, the header {\pf
Rational::print(void)} indicates that this code is defining the {\pf print}
method within class {\pf Rational}.

\i Since the methods {\pf Rational}, {\pf read}, {\pf print}, and {\pf
eval} are all associated with an object or variable of class {\pf
Rational}, every such object will have its own {\pf numerator} and {\pf
denominator}.  These fields are referenced as part of these methods.

\i This file only defines the details of various methods -- it does not use
the methods in an application.  Thus, this file does not produce any output.
On the other hand, this implementation file can be compiled for linking
into later programs as needed.


\samplerun {rational.out}

\i In using the specific compiler illustrated here, the {\pf -c} option
indicates that the file is to be compiled but not linked to other files.

\i The above compiler produces a file {\pf rational.o} which can be linked
with application programs, as they are developed.

%-----------------------------------------------------------------------------

\newprogram {rat-driver-1.cc}
{A program that demonstrates the use of the rational number class.}

\ann

\i C$++$ initializes variables when they are declared, following the
details specified within constructors.  Thus, {\pf z, i,} and {\pf r} are
all initialized, following the appropriate constructor, at the beginning of
the program when they are declared.

\i When using methods (operations) related to an object (variable),
a dot notation is used to associate the object with its method.  Thus, {\pf
z.print ()} invokes the {\pf print} method for the object {\pf z}, and {\pf
z.eval ()} invokes {\pf z}'s {\pf eval} method.

\i Since the operation $+$ was overloaded for rational numbers, it may be
used in the familiar context {\pf z + r}, as the compiler now knows how to
apply this operation to elements in this new data type.

\samplerun {rat-driver-1.out}


\i In compiling the program {\pf rat-driver-1.cc}, the machine is told to
link the details of rational numbers, as found in {\pf rational.o}.

\i The second and fourth runs illustrate that error checking is performed
as advertised. 

\i The third run illustrates that reading using the $>>$ operator strips
initial blanks, so that spaces may be placed before the {\pf /} character
or before either integer without generating errors.

%-----------------------------------------------------------------------------
\newcode {rational2.h}
{A simpler form for operations, using default parameters.}

\ann

\i This header file specifies the same constructors as the previous
version in a simpler form, using default parameters.  In particular, the
statement\hfil\break
{\pf Rational (int num = 0, int denom = 1);}\hfil\break
provides for two parameters, {\pf num} and {\pf denom}.  If no parameters
are supplied during initialization, however, this header specifies that the
values 0 and 1 should be used for these parameters.  Similarly, if only one
parameter is given, this header assumes the value should correspond to the
first parameter ({\pf num}), and the default value of 1 will be used for
{\pf denom}.

\i A similar use of default values for parameters may be used with any
C$++$ function.

%-----------------------------------------------------------------------------
\newcode {rational2.cc}
{A simpler and more efficient implementation of rational numbers.}

\ann

\i Since this implementation goes with the revised header file, default
values from the header are assumed in this implementation.  C$++$ allows
the default parameters to be repeated in the implementation header, with
the statement \hfil\break
{\pf Rational::Rational (int num = 0, int denom = 1)} \hfil\break
but the above code shows that there is no need to repeat the default values
again in the implementation.  (An error is generated, however, if new and
different default values are given in the implementation.)

\i This revised constructor {\pf Rational} also illustrates a more
efficient way to construct\break rational numbers.  In particular, the
first version contained the lines \hfil\break  
{\pf numerator = num; 
\hfil\break 
assert (denom != 0); \hfil\break 
denominator = denom; \hfil\break}
While this code correctly initializes a rational number and checks that the
denominator is nonzero, the execution actually proceeds in several steps.
First, space is allocated for the integer fields {\pf numerator} and {\pf
denominator}. Second, these fields are initialized with a default value for
integers (e.g., 0).  Third, new values ({\pf num} and {\pf denom}) are
copied to the respective fields.

\item {}  In this revised version, {\pf numerator} and {\pf denominator}
are given values before the brace $\{$.  In C$++$, this means that the
values specified are used to initialize the fields, before any default
value for integers is stored.  Thus, the second step of initialization from
the previous code is skipped in this revised code.

\i This revised code may be used with the previous program {\pf
rat-driver-1.cc} simply by including the new header file {\pf rational2.h}
and by linking with the new compiled code {\pf rational2.o}.  The output of
the user program remains unchanged.

%-----------------------------------------------------------------------------

\newcode {rational3.h}
{A variation of the rational number data type, allowing $<<$ and $>>$ for I/O
and automatically reducing rationals to lowest terms.}

\ann

\i In this version of the rational number data type, the I/O stream
operators $<<$ and $>>$ are overloaded for use with rational numbers.  This
eliminates the need for the separate operations {\pf read} and {\pf print},
which were defined in previous versions of the rational number data type.

\i In this revision, rational numbers will be kept as fractions reduced to
lowest terms.  To accomplish this, a greatest common division function,
gcd, is useful.  Since this function is intended for use within this class
only, not by any outside application, {\pf gcd} is declared as a private
operation.  Application programs may neither access nor redefine this {\pf
gcd} function.  (Of course, these programs may use their own $gcd$
function, but any such function will be considered distinct from the one
defined here.)

%-----------------------------------------------------------------------------

\newcode {rational3.cc}
{The implementation details for extending $<<$ and $>>$ and for reducing
fractions to lowest terms.}

\ann

\i The I/O operations $<<$ and $>>$ are defined for output and input streams,
respectively.  Within each operation, work is built upon similar operations
for numbers or integers.  In the case of input, error checking is added,
and the number entered is reduced to lowest terms.

\i The gcd function follows the standard Euclidean algorithm of finding
successive remainders to find the greatest common divisors.  For more
information on this algorithm, the reader is referred to a mathematics
textbook. 

\i In reducing a rational number to lowest terms, the greatest common
factor of the numerator and denominator is computed.  Then both the
numerator and the denominator are divided by this common factor.

%-----------------------------------------------------------------------------

\newprogram {rat-driver-3.cc}
{This program uses the new rational number data type.}

\ann

\i Since the operations, $<<$ and $>>$, have been extended to rational numbers,
I/O streams may be used for this new data type as for built-in types.

\samplerun {rat-driver-3.out}

\end

%-----------------------------------------------------------------------------

\newprogram {.cc}
{.}

\ann

\i 

\samplerun {.out}





