%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 1998 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.c}
{The first program converts a number of quarts to liters, from the keyboard
using the {\pf stdio.h} .  }

\ann

\i Comments in C 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 <stdio.h>} 
\hfil\break
instructs the machine how to use the stdio operations.

\i Each C program contains a driver function/program, called 
{\programfont main}.  Here, main uses no input parameters (hence the
parentheses with nothing between them following {\pf main}).  

\i Variables may be declared globally or at the start of a C
function.  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 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 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. 

\vfill\eject
\i {\pf scanf} and {\pf printf} are used for input and output,
respectively.  In each case, the first parameter is a string, which
indicates how input or output will be formatted.

\ii {When printing text only, as in the first output line in this program,
the text of the string is enclosed in double quotes {\pf "  "}, and the
characters are printed exactly as given.}

\ii {Within a format string, some symbols are used for special symbols.  For 
example, \hfil\break
{\pf '$\backslash$n'} stands for a new-line character, \hfil\break
{\pf '$\backslash$t'} stands for a tab character,  \hfil\break
{\pf '$\backslash$"'} stands for a double quote character, and  \hfil\break
{\pf '$\backslash\backslash$'} stands for the backslash character itself.}

\ii {When printing the value of a variable, the format string for {\pf
printf} gives the type of data to be read:  \hfil\break
{\pf "\%d"} stands for a (decimal) integer, \hfil\break
{\pf "\%f"} stands for a (floating point) real number, \hfil\break 
{\pf "\%lf"} stands for a double precision (long) real number, \hfil\break 
{\pf "\%c"} stands for a (single) character, \hfil\break
{\pf "\%s"} stands for a character string.}

\ii {When reading a value, the {\pf scanf} procedure uses the same
formatting conventions as {\pf printf}. } 

\ii {When using {\pf scanf}, one must pass the address of variables, rather
than their values.  That is, {\pf scanf} must know the address in memory into 
which a value is to be placed.  The ampersand \& before {\pf quarts} in the
{\pf scanf} statement specifies ``the address of {\pf quarts}''.}

\samplerun {quarts-1.out}

In this sample run (run on the machine {\ital babbage}), the program
(called {\pf quarts-1.c}) is compiled and run using the gcc 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.c}
{Another program to convert a number of quarts to liters.
}

\ann

\i In declaring the {\pf main} header, the addition of {\pf void} states
explicitly that {\pf main} is a procedure of no parameters.

\i {\pf main} may return an integer error code to the operating system by
declaring; thus, the declaration {\pf ing main} and the concluding
statement {\pf return 0} to indicate no errors.


\i Variables can be declared within a function at the start of a block
(i.e., immediately after a left brace {\pf $\{$}. Here, variables are
declared at the beginning of the function {\pf main}, 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.c}
{Program illustrating variable declaration and initialization, together
with simple error checking.}

\ann

\i C allows variables to be declared at the start of any block.
Thus, in this program, {\programfont liters} is declared in a new block,
after the value of {\pf quarts} has been entered successfully.

\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 at the
start of interior blocks.  
\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}

In this work, the steps for compiling and running this program were
combined on one line with the conjunction \&\&.  This conditional
conjunction \&\& states that the first command ({\pf gcc -o quarts-3
quarts-3.c}) should be done first.  However, the second command (running
{\pf quarts-3}) will occur only if the first step is successful.

%-----------------------------------------------------------------------------
\newprogram {smallest3-1.c}
{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, C has no separate Boolean type, and Boolean results are
considered integers.  Further, in C, a zero value is considered as false,
while any nonzero value is 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) printf ("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.

\vfill\eject
\i In reading multiple values with {\pf scanf}, the format string must
contain a specification for each variable to be read.  Thus, this program
contains 
\hfil\break
{\pf scanf ("\%d \%d \%d", \&i1, \&i2, \&i3);}
\hfil\break
In addition, {\pf scanf} interprets the characters between the variable
specifications as follows:

\ii {Blanks or tabs are ignored (as is the case here).}
\ii {Ordinary characers (not \%) are expected to match the next non-white
space characters of the input stream exactly.}
\ii {Conversion specifications begin with \%, as shown here for (decimal)
integers.}

\samplerun {smallest3-1.out}

%-----------------------------------------------------------------------------
\newprogram {smallest3-2.c}
{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.c}.

%-----------------------------------------------------------------------------
\newprogram {smallest3-3.c}
{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.c}.

%-----------------------------------------------------------------------------
\newprogram {smallest3-4.c}
{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.c}.

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

\newprogram {quarts-for-1.c}
{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 {\pf
printf} format string contains several spaces:  
{\pf "~~\%d~~~~~~~~~~\%f$\backslash$n"}.
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.c}
{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 in the output specification, 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 is
specified as part of the number format, as shown in the program.
\i Similarly, formatting of real numbers in C requires a specification of
both the overall width for the number and the number of decimal places to
be printed.  Both of these values are illustrated in the program; the 
specification {\pf \%16.4f} indicates that 16 characters will be allocated
to the overall number, and the number will be printed with four digits to
the right of the decimal point.
\i Note that space characters in a {\pf printf} format string are printed
as specified.  Thus, the following lines would yield the same results shown 
in this output: \hfil\break
{\pf
printf ("\%4d\%16.4f$\backslash$n", quarts, liters); \hfil\break
printf ("\%4d~\%15.4f$\backslash$n", quarts, liters); \hfil\break
printf ("\%4d~~\%14.4f$\backslash$n", quarts, liters); }

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


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

\newprogram {quarts-for-3.c}
{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.c}
{This program illustrates the nesting of {\pf for} loops to produce a table
of liter equivalents.}

\ann
\i This program also illustrates another common approach to defining
constants within C.  Historically, {\pf \#define} statements were used to
indicate constants well before the {\pf const} modifier was introduced.
Thus, most old programs and most experienced C programmers are likely to
use the {\pf \#define} construct.  (In contrast, experienced C$++$
programmers are more likely to use {\pf const}.)

\samplerun {quarts-for-4.out}

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

\newprogram {darts.c}
{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 {max-min.c}
{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]}.
The ANSI C Standard indicates that, unlike this example, the size of the
array must be an integer {\ital constant}.  However, this example also
shows that some compilers, such as the Gnu compilers from the Free Software
Foundation, allow variables to be used in specifying array size.  In such
cases, an array size could be read first and then used within a new block as
part of an array declaration.

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

\i Reading of individual array elements requires the ``address of''
operator \&, just as is used for reading other values.

\i As noted previously, reading of a double-precision real number is
accomplished using the {\pf scanf} format {\pf "\%lf"}.

\samplerun {max-min.out}

\i C does not perform bounds checking when accessing array elements.
Thus, nonsense is printed for {\pf a[-3]} when only {\pf a[0]} through
{\pf a[5]} 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[-3]}.

%-----------------------------------------------------------------------------
\newprogram {trap-1.c}
{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
double-precisions, floating-point number, and the header {\pf (double x)}
specifies that $f$ will have a single, double-precision, 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.c}
{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, called a {\ital
function prototype}, 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.c}
{This program computes the Trapezoidal Rule using a procedure.}

\ann

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

\i In C, all 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
the address of the actual parameter must be given in the function call.
As with the use of {\pf scanf}, this is accomplished by adding an
ampersand {\pf \&} before the actual parameter ({\pf new\underbar{~}area})
in the function call.

\item {} This use of an address as parameter is prescribed in the function
header by adding a star {\pf *} before the actual parameter.  Then, within
the function, the {\pf variable} itself refers to the address of the actual 
parameter, while  {\pf * variable} refers to the value at that address.
Thus, in this example, the assignment, {\pf *area = sum * width;},
indicates that the value of {\pf sum * width} will be stored in the memory
location whose address is given by the {\pf area} parameter.

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

\newprogram {trap-4.c}
{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.c}.

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

\newprogram {trap-5.c}
{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.c}.  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-precision parameter, and they
returned a double.

\samplerun {trap-5.out}

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

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

\ann

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

\i Output files are declared as pointer variables to elements of type {\pf
FILE}.   

\i Once a file {\pf f} is declared, it is opened or closed with the
statements \hfil\break 
{\pf <variable> = fopen (<file-name>, <mode>)} ~~~and~~~
{\pf fclose (<file-variable>)},\break
respectively. The {\pf <file-name>} is any string enclosed in double
quotes; the {\pf <mode>} is 
\ii {"w" for writing to a file,}
\ii {"a" for appending additional information to an existing file, and}
\ii {"r" for reading from a file (as in the next example).}

\i Output to a file uses {\pf fprintf} operator, which works the same as
{\pf printf} with a file variable added.

\samplerun {genfile.out}

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

\newprogram {readfiles.c}
{This program shows how to read numbers from files.}

\ann

\i Input files are declared of type {\pf FILE *}.  

\i As with files for output, input files {\pf f} are opened and closed
with the statements\break {\pf <variable> = fopen (<file-name>, "r")} and
{\pf fclose (<file-variable>)}, respectively.  (This format is exactly the
same as for output files, except that the mode used in the {\pf fopen}
statement is {\pf "r"}).

\i Similarly, input from a file may use the {\pf fscanf} procedure, which is
analogous to reading keyboard input with {\pf scanf}.

\vfill\eject



\i When using {\pf fscanf} for reading, the procedure returns an integer as
follows:


\ii {When values are read successfully according to the format string,
{\pf fscanf} returns the number of variables actually read.}
\ii {When {\pf fscanf} encounters the end of a file, {\pf fscanf} returns
the special value {\pf EOF}, which is defined in {\pf stdio}.}

\item {} Thus, testing {\pf (fscanf ( ... )~!=~EOF)} provides a natural way to
continue processing until the end of a file is encountered.

\samplerun {readfiles.out}

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

\newcode {fileletters-1.c}
{A program that reads a file name and counts the letters and other
characters in that file.}

\ann

\i Technically, a string is an array of characters, and the declaration of
any array requires a specification of a maximum length.  Within C, however,
strings are treated as a sequence of characters ending with a null
character {\pf '$\backslash 0$'}.  Thus, the string is considered to stop
with the first null, regardless of how large the array is declared.  To be
safe, one must be sure to declare the array to be sufficiently large.

\i Printing and reading of strings utilizes "\%s" format within 
{\pf scanf} and {\pf printf}.

\i Whereas all simple types (e.g., {\pf int}, {\pf double}, and {\pf char}) 
are passed by value in C, all structured types (e.g., arrays) are passed by
reference.  That is, the base address of the structure is passed as the
parameter. 

\ii {At a technical level, the passing of the base address requires little
copying, whereas passage by value would require the considerable overhead
of copying an entire structure.  For efficiency, C uses just the address
of the structure, so structured variables are passed by reference.}

\ii {At a practical level, use of the {\ital address operator \&} is rarely 
needed in passing structures as variables.  Thus, here {\pf
file\underbar{~}name} is used as parameter to {\pf scanf}, without the \&.}

\i While {\pf fscanf} could be used to read character data using "%c"
format, white space would be omitted.  With this option for this program,
processing would give correct results for letter frequencies, but counts of 
non-letters and control characters would not include spaces, tabs, returns, 
and other white space characters.  

\i The function {\pf getc} from {\ital stdio.h} returns the next character
in a file.  In this reading, the end-of-file character {\pf EOF} is
considered to be just another characer.  {\pf putc} is the corresponding
function to print a character to a file.

\i The condition for the {\pf while} statement combines reading,
assignment, and comparison within a single step.  First, {\pf
getc(file\underbar{~}var} returns a character, and that character is
assigned to variable {\pf ch}.  This value then is compared with {\pf EOF}
within the {\pf while} condition.

\i The library {\ital ctype.h} contains several functions that are useful
in working with characters in C.  In the following table, parameter {\pf c} 
is considered to be a character (type {\pf char}):
\halign {\hskip 20pt # \hfil & {\pf #} \hfil & # \hfil \cr
\multispan2 \hskip 40pt ``boolean'' functions \raise6pt\hbox{\strut}\hfil\cr
\qquad\qquad
  & isupper(c) & upper case letter\cr
  & islower(c) & lower case letter\cr
  & isalpha(c) & upper or lower case letter\cr
  & isdigit(c) & decimal digit\cr
  & isalnum(c) & upper or lower case letter or a digit\cr
 & isspace(c) & space, formfeed, newline, carriage return, tab, vertical tab\cr
  & ispunct(c) & printing character except space, letter, or digit\cr
\multispan2 \hskip 40pt ``conversion functions \hfil\cr
  & tolower(c) & convert upper case to lower case; no effect on other chars\cr
  & toupper(c) & convert lower case to upper case; no effect on other chars\cr
}

\i In C, characters are stored as coded integers.  Thus, characters may be
used within integer expressions, and the expression {\pf ch - 'a'}
subtracts the code for the letter {\pf 'a'} from the letter code read into
{\pf ch}.

\i When an integer appears with {\pf printf}or {\pf fprintf} using "%c"
format, the character with that code is printed.

\vfill\eject
\samplerun {fileletters-1.out}

\i Processing counts the letters in file {\pf character.file}.  This file
was created to make testing easy:  subsequent lines remove one line from
the alphabetic listing, both upper and lower case letters are included, the 
lower case listing contains 10 fewer lines than the upper case listing, and 
exactly 30 non-letters are included (plus $<$return$>$ characters at the
end of each of the 43 lines).

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

\newprogram {fileletters-2.c}
{A program, organized by procedures, to count letter frequencies in a file.}

\ann

\i This program organizes the file processing of {\ital fileletters-1.c}
into three stages, each coordinated by a separate procedure.  The steps
for each stage follows those in the earlier version.

\i As in previous examples using procedures, no global variables are used
here, parameters are used consistently to move values in and out of
procedures, and function prototypes appear at the program's start. 

\i The {\pf print\underbar{~}results} procedure takes values and prints
them, without changing any values.  Thus, the procedure uses default
parameter passing throughtout.  

\ii {For arrays {\pf name} and {\pf counts}, C
will pass the array's base address, while C will copy values of the
individual values for {\pf others} and {\pf control}.}

\ii {When declaring array parameters, the size of the array is omitted from 
the procedure header.  Since only the base address is passed, the procedure 
only knows the start of the array, not its size.  (Further, the same
procedure could be called for arrays of different size, although that
possibility is not needed in this application.)}


\i The {\pf initialize} procedure must place the correct first values into
the {\pf counts} array and the file pointer {\pf file\underbar{~}var}.
Since arrays are structures, C passes {\pf counts} by reference, so any
initialization made within the procedure will be stored directly within the 
array.  In contrast, {\pf file\underbar{~}var} is a pointer to a file, and
initialization must provide this pointer with the address of a newly created 
file buffer.  Thus, we must pass the pointer {\pf file\underbar{~}var} by
reference:

\ii {Since {\pf file\underbar{~}var} was declared as type {\pf FILE *},
passage by reference must give the address of this pointer.  Thus, the
header specifies type {\pf FILE **} as a pointer to the file pointer.}

\ii {The address of {\pf file\underbar{~}var} is needed as the actual
parameter, so an ampersand \& is used in the call:
{\pf initialize (counts, file\underbar{~}name, \&file\underbar{~}var);}.}

\ii {In opening the file, we store the buffer address in the pointer
variable {\pf (*filev)}.}

\i The {\pf process\underbar{~}file} procedure changes the status of
the file buffer ({\pf FILE *file\underbar{~}var}) as well as the frequency
array {\pf counts} and frequencies {\pf non\underbar{~}letters} and
{\pf control\underbar{~}chars}.  Thus, parameters are passed for {\pf
process\underbar{~}file} in the same way as for {\pf initialize}.


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

%-----------------------------------------------------------------------------
\newcode {fileletters-3.c}
{The following variation allows the file name to be included on the command 
line.  The program also utilizes C's {\ital string.h} library for strings.}

\ann

\i This program provides the user with the option of supplying the file
name on the command line, when first running the program (see the sample
output that follows).

\i Arguments on the command line are passed to the {\pf main} program from
the operating system as parameters.  When using parameters:

\ii {The first parameter is an integer which indicates how many parameters
are passed to the program.  Hence, the integer {\pf argc} will indicate how
many parameters are supplied on the command line.}

\ii {The second parameter {\pf argv} is a pointer to an array of command
line arguments.}

\ii {Since the program name is always the first command-line parameter,
{\pf argc} always is at least 1, and {\pf argv[0]} is the program name in
string form.}

\ii {Any arguments after the program name appear as strings in {\pf
argv[1]} and subsequent array elements.  Here, {\pf argv[1]} contains the
file name from the command line, if given by the user.}

\i Library {\ital string.h} provides many useful procedures for working
with strings.  This program uses {\pf strcpy} to copy the second string to
the first.

\i At declaration, arrays may be initialized by listing appropriate values
in braces $\{~~\}$, with individual values separated by commas.

\i In this program, procedure {\pf process\underbar{~}file} calls
{\pf process\underbar{~}char} to handle processing of a specific
character.  Here, {\pf ch} is supplied, and frequency counts are updated as 
needed.  

\ii {As frequency variables must be updated, all parameters must be passed
by reference: {\pf process\underbar{~}char}'s header shows that array {\pf
counts} is passed as a base address, while addresses are passed for both
{\pf otherss\underbar{~}var} and {\pf cntl\underbar{~}var}.}

\ii {In the header of {\pf process\underbar{~}file}, {\pf others} and {\pf
control} are already declared as addresses.  Thus, no additional address
operator is needed in the call to {\pf process\underbar{~}char}; {\pf
others} and {\pf control} may be passed directly.}

\samplerun {fileletters-3.out}

\i When the program is run as before (with no file name on the command
line), the program prompts for the file name as in past runs.

\i When a file name is provided on the command line, that file is opened
and processed.  The program does not ask for an additional file name.

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

\ann

\i 

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

\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 

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

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

\ann

\i 

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

\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}






