You are on page 1of 296

88 C Programs

by JT Kalnay
This book is dedicated to Dennis Ritchie and to Steve Jobs.
To Dennis for giving us the tools to rogram.
To Steve for giving us a reason to rogram.
Published by jt Kalnay
Copyright 2012, JT Kalnay
This book is licensed for your personal use.
This book ay not be re!sold.
"o#e$er, this book ay be freely gi$en a#ay to other people.
%f you #ould like to share this book #ith another person, please feel free to do so.
&isco$er other titles by jt Kalnay at'
!!!."tkalnay.com
#bout This $ook
This book is not organi(ed in a traditional chapter forat.
%nstead % ha$e chosen to include e)aple progras that e)hausti$ely illustrate the
iportant points of C in an e$olutionary anner. *y #orking through these progras
you can teach yourself C. % assue you already kno# ho# to progra and are failiar
#ith standard algoriths.
The progras that % present are not, by thesel$es, coplete applications. The
progras are +single!issue teaching progras,. -)perienced prograers #ho are
learning a ne# language ha$e told e tie and tie again that they ainly #ant to see
the functionality of the ne# syntactic and seantic eleents. The prograers tell
e that they #ill be able to think of the applicability of the feature to their project.
.hen necessary, % pro$ide a saple application to gi$e a feel for ho# the ne# eleent
ight be eployed.
The progras are presented in an order that presents the siplest, ost straightfor#ard
aspect of a ne# eleent first. /ubse0uent progras present the ore subtle or
confusing aspects of a ne# eleent. This is a pro$en pedagogical approach for
teaching C that % ha$e presented to o$er 1,000 professionals and college students.
This book assues that you are already a prograer and are able to learn #ell on
your o#n.
1ood luck in your study of C.
4
Table %f Contents
/iple.c siplest C progra, ain, progra entry point
hello#orld.c one printf
prog1.c ore printf
prog2.c coents, case sensiti$ity
prog2.c $ariable declaration and initiali(ation
prog3.c printf output
ops.c C operators
prog3a.c printf output
prog4.c C data types
pg23.c si(eof5$ar6
prog7.c operators and precedence
prog8.c i)ed ode arithetic
prog9.c odulus
ste$e.c relational operators
prog:a.c three types of loops
prog10.c for loop
prog11.c for loop, scanf
prog12.c nested for loops
prog12.c #hile loop
prog13.c #hile loop
5
prog14.c #hile loop, do loop
if.c if stateents
17.c ath.h
1:.c logical operators and e)pressions
20.c cople) decision structures
21.c s#itch stateent
errors.c coon synta) errors
22.c arrays
22.c array boundaries
24.c ore array boundaries
27.c bo#ling scores, arrays
28.c character arrays
2:.c function declaration and usage
20.c calling subroutines
21.c passing constants to subroutines
22.c passing $ariables to subroutines
22.c subroutine returning $alue
24.c ultiple files copiled together
$alref.c call by reference, call by $alue
27.c passing array to subroutines
28.c passing pointer to subroutine
29.c sorting array of integers
sortstep.c sorting e)aple
6
2:.c t#o diensional array
t#odi.c t#o diensional array to subroutine
testarrays.c ore arrays
testarrays1.c ore arrays
prog30.c static, autoatic, global
scope.c scope of $ariables
31.c recursion
testpop.c stack
32.c struct key#ord, structures
32.c structures
34.c ;<%= tie.h file
37.c >rrays of /tructures
38.c structures and arrays
39.c strlen string processing
3:.c strcat
40.c strcp
42.c getchar gets
42.c ctype.h, string functions
charlarge.c characters as large integers
44.c structures and strings
48.c pointers
49.c pointers
4:.c pointers to structures
7
70.c linked list pointers
alloc, eory allocation
$alref.c pointers and functions
87.c getchar, putchar
88.c file operations, fopen, fprintf, fclose, getc, putc
uitp.c file i?o and string processing
argtest.c arc, arg$, dealing #ith coand line arguents
en$test.c interface to ;<%= en$ironent
sol20.c argc, arg$
89.c register const storage 0ualifiers
speed1.c inefficiency
speed2.c efficiency
73.c copying strings using pointers
82.c printf in depth
83.c scanf in depth
84.c scanf in depth
78.c bit operations
bits.c int octal he) binary display
81.c @ifdef conditional copile
0uicksort.c 0uicksort pointer e)aple
ptrtofunc.c pointers to functions
8
Simle.c Simlest C rogram ossible
ain 5 6
A
B
ain is a C key#ord.
%t is the progra entry point.
%t does not need to be in colun one.
ain ay take arguents. .e #ill deal #ith the later.
The epty round brackets 5 6 indicate that #e arenCt going to #orry about the arguent
list at this point.
> C coent is enclosed by ?D EE. D?
ain 5 6 ?D progra entry point D?
A ?D start of block, start of scope D?
*lock body
*lock blody
E
*lock body
B ?D end of block D?
A is the start of scope character
B is the end of scope character
A and B are referred to as +curly brackets, in this te)t.
/ee also Fsiplest C progra possible' Part %% full ></%G copatabilityF on
page 20.2
9
hello&!orld.c Simle rogram !ith rintf outut
>ll C stateents end #ith a seicolon H
ain 5 6
A
?D printf is a c subroutine that you get access to through the standard io
library D?
?D #e #ill co$er @include Istdio.hJ later D?
?D in its siplest for printf takes a character string to display D?
?D it ay also take other arguents, #e #ill e)aine these
later D?
?D printf returns a count of the nuber of characters it
displayed D?
?D the count can be ignored D?
printf5Fhello #orld KnF6H
B
10
rog'.c (ore on Printf
?D stdio.h is the standard input library that pro$ides printf, scanf, and other i?o
routines D?
?D @include tells the copiler #here to look for input?output routines you call D?
?D @include I nae of .h file J #ill add that .h file to your copilation odule D?
@include Istdio.hJ
int ain 5 6
A
?D curly brackets ark the beginning and end of the scope of a copound
stateent.
> copound stateent ay be a function body, the body of a loop, the body
of a conditional,
se$eral stateents, E D ?
printf5FC PrograingKnF6H
printf5FC PrograingKnF6H
B
printf5Fstring to displayF6H ?D string to display is inside 0uotations, D?
?D can pro$ide forat specifiers that describe "L. to display things 5e.g., as integers, as
strings6 D?
?D if you put in a forat specifier you need to pro$ide a $ariable to satisfy the forat specifier
D?
printf5Fstring forat specifierF, $ariables to satisfy forat specifiers6H
11
rogl.c sulemental variable declaration) rintf outut) return value
?D to copile #ith ansi copiler #ith defaults
acc prog1.c #ill produce a.out
if 5opile is successful no Fsuccess indicatorF is generated
if errors, copiler essages #ill be generated
e)ecutable can be run by typing a.out D?

?D to copile #ith ansi copiler and specify e)ecutableCs
nae
acc !o progl prog1.c
#ill produce progl if 5opile is
successful D?
?D to pass source code through a $ery picky pre copiler
alint progr1.c
D?
?D curly brackets ark the beginning and end of the scope of a copound stateent.
> copound stateent ay be a function body, the body of
a loop, the body of a conditional, se$eral stateents D?
?D c is an e)pression language
e$ery stateent returns a $alue,
#hich ay be discarded or ignored if unneeded D?
?D the ne)t progra sho#s that printf returns the nuber of characters it printed. D?
12
C Prograing
$alue of )y( is 13
C Prograing
@include Istdio.hJ
int ain56
A
?D int declares )y( as a $ariable of type integer D?
int )y(H
?D )y( gets return $alue fro printf D?
)y( M printf5+C PrograingKn,6H
?D Ni forat specifier says print out the $alue of )y( as an integer D?
printf5+$alue of )y( is Ni Kn,,)y(6H
?D #e can ignore the return $alue of printf D?
?D Kn is the ne#line character D?
printf5+C PrograingKn,6H
B ?D progra e)it point D?
13
Comile) link) run se*uence
Oou can copile C odules to produce object files
Oou can asseble >ssebler odules to produce object files
Oou can also copile other 5e.g., Portran, Pascal6 progras to produce object files
Oou can then link all these together
>CC stands for ></% C copiler
>cc naeQofQcQfile produces e)ecutable a.out
.c file c file
.o file object file
.as file assebler file
.for file fortran file
.pas filepascal file
.cob file CL*LR file
14
ANSI C Compiler
Link Editor
Exect!"le
rog+.c comments case sensitivity
@include Istdio.hJ
int
a
in
5 6
A
?* coents start #ith slash asterisk
can span se$eral lines, and end #ith asterisk slash D?
int foobarH ?D $ariable naes are case sensiti$e D?
?D all C stateents e)cept coents are case sensiti$e
int is LK, %<T is not D?
/* #hite space is ignored D?
printf5+C PrograingKnF6H
printf5FPor fun and profitKnF6H ?D coents can be at the end of a line D?
printf 5F"ello ?D this is not a coent D? dolly KnF6H
print?Dcoent cannot be nestedD?f5F"1KnF6H
printf5FabcKnF6H ?D coents that span lines
printf5FdetKnF6H can cause une)pected resultsE D?
?D the printf5+det Kn,6H stateent #ould not be copiled b?c it is inside a
coentG D?
Printf5+$alue of foobar is NiKn,,Poobar6H
B
15
Compiler
Error
Compiler
Error
/torage Classes
Table %
Type "o#
&eclared
.here
/tored
%nitial Salue /cope Rifetie
>uto >uto
key#ord or
in function
or in block
/tack <one Punction or
block
Punction or
block
/tatic
internal
/tatic
key#ord in
function or
block
"eap Tero if not
e)plicitly
initiali(ed
Punction or
block
-ntire life of
progra
-)ternal Lutside all
functions
"eap Tero if not
e)plicitly
initiali(ed
-ntire
progra
-ntire life of
progra
Uegister Uegister
key#ord
> register, if
one is
a$ailable
<one /ae as auto /ae as auto
/tatic
e)ternal
/tatic
key#ord
outside all
functions
"eap Tero if not
e)plicitly
initiali(ed
/ae file
after
definition
-ntire life of
progra
C supports different storage classes that you can force by using e)plicit key#ords.
16
rog,.c variable declaration and initiali-ation
@include Istdio.hJ
int ain5 6
A
?D declare an integer D?
int )H
?D do not count on uninitiali(ed $ariables to ha$e a certain $alue D?
?D they could be (ero and probably #ill be (ero but, could be ??? D?
printf5F;nitiali(ed ) M NiKnF,)6H
) M 1 V 2H
printf5F) #ith 1 V 2 M NiKnF, )6H
B
17
&ifferent #ays to declare and initiali(e $ariables
TypeQofQ$ariable naeQofQ$ariable
%nt )H
Ploat yH
Char cH
typeQofQ $ariable nae1, nae2, E H
int ),y,(H
float f1 ,f2H
char c1, ?D first char D ?
c2H ?D another char D ?
typeQofQ $ariable naeQofQ $ariable M initialQ$alueH
int a M 8H
float f1 M 7.8fH
type nae M initial, nae M initial, ... H
int a M 7, b M 12, c M 12H
18
rog..c rintf outut of variables
@include Istdio.hJ
?D this progra adds t#o integer $alues and D?
?D displays the results D?
?D it also deonstrates t#o #ays to initiali(e a $ariable D?
int ain5 6
A
?D declare $ariables D?
int $ lH int $2H int $suH
?D declare and initiali(e $ariable D?
int allQinQone M 4H
/* initiali(e $alues D?
$ l M 1H
$2 M 2H
?D copute D?
$su M $ l V $2H
?D print result D?
printf5FThe su of Ni and Ni is NiKnF,$%,$2,$su6H
?D display all in one D?
printf5FallQinQone MJ Ni KnF,allQinQone6H
?D case sensiti$ity error, #ould not copile D?
?D printf5FallQinQone MJ Ni KnF,>RRQinQone6H D?
?D printf error D ?
print5FallQinQone MJ Ni KnF,allQinQone6H
B
19
%P/R#T%RS0 R/T1R2 3#41/ #2D S5D/ /66/CTS
%n C, all operators ha$e a return $alue and soe ha$e
Fside effectsF
> return $alue isa $alue gi$en back. Por e)aple in the
code'
int aH
9M 2 V 3H
The addition operator 5V6 returns the result of adding the $alues 2 and 3.
> side effect is a change in a eory location.
Por e)aple'
int aH
aM 8H
The assignent operator 5M6 changes the eory location #e call CaC to contain the
$alue 8.
The assignent operator also has a return $alue, naely the ne# $alue of a 5in our
case 86. %n this #ay #e can say'
int a,b,cH
aMbMcM8H
8 is assigned into c, cCs ne# $alue 586 is assigned into b, etc.
<LT-' any stateent that has no side effec$t and #hoCs return $alue is not used adds
(ero $alue
to a progra.
2 V 3H
the 2 and 3 are added returning 8 #hich is discarded 5like all interediate results #hen
no longer
needed6. Wost copilers #ould flag a line like 2 V 3H #ith the #arning'
F/tateent has no effectF
20
mathematics oerators
addition V
subtraction !
ultiplication D
di$ision ?
assignent M
increenting VV
decreenting !!
os.c rogram to demonstrate c oerators
ain 5 6
A
int i.)'
i M LH
) M iVVH ?D post increent, return $aule is LR& $alue, side effect is
increentD?
printf5Fi M Ni ) M Ni KnF,i ,)6H
i M0H
) M VViH ?D pre increent, return $aule is <-. $alue, side effect is
increentD?
printf5Fi M Ni ) M Ni KnF, i, )6H
i M 0H
) M i!!H ?D post decreent, return $aule is LR& $alue, side effect is
decreentD?
printf5Fi M Ni ) M Ni KnF, i, )6H
i M 0H
) M !!iH ?D pre decreent, return $aule is <-. $alue, side effect is
decreent D?
printf5Fi M Ni ) M Ni KnF, i, )6H
/* copound assignents' $ar op= $alue is the sae as $ar M $al op
$alue D?
21
i M 4H
i VM 2H ?D plus e0uals, add and assign, sae as i M i V 2 D?
printf5Fi M Ni KnF,i6H
i M 4H
i !M 2H ?D inus e0uals sae as i M i ! 2D?
printf5Fi M Ni KnF,i6H
i M 4H
i DM 3H ?D ties e0uals sae as i M i D 3 D?
printf5Fi M Ni KnF,i6H
i M 20H
i ?M 2H ?D di$ides e0uals sae as i M i ?2 D?
printf5Fi M Ni KnF,i6H
i M 24H
i NM 8H ?D od e0uals sae as i M
i N 8D?
printf5Fi M Ni KnF,i6H
B
Samle %utut 6rom os.c
iM 1 ) M L
iM1 ) M 1
iM !1 )M L
iM !1 )M !1
i M 8
i M 2
i M 20
i M 10
i M 3
22
/7ercise '
?D ake a file naed )one.c D?
?D #rite a C progra to copute the follo#ing D?
?D the result of b s0uared ! 3 ties a ties c D?
?D #here a is 4, b is 3, c is 2 D?
?D print out the ans#er D ?
?D use $ariables naed a, band c and a $ariable to hold the result D?
?D C does not ha$e a built in s0uare function
nor does it ha$e a Fto the po#er of, operatorD?
23
Solution for /7ercise '
@include Istdio.hJ
int ain 5 6
A
int a, b, c, resultH
a M 4H
b M 3H
c M 2H
result M 5 b D b6 X 53 D a D c6H
?D using the 5 6 reo$es doubts about the order of operations... D?
printf5FNi s0uared ! 5 3 D Ni D Ni 6 MJ Ni KnF, b,a,c,result6H

B
24
/7ercise +
/* fi) this progra by typing it in fro scratch
find the synta) errors and fi) the as you go 5let the copiler find the errors6
until it copiles cleanly and runs cleanly and produces the ans#er 12 D?
@include stdio.h
ain
integer iH
do soe ath D ?
iM1V2V2
/* do soe ore
ath
i M i V iH
print5i M N Kn,
i6H
B
/* desired
output D?
?D
i M 7 inaccurate
docuentation GG
D?
25
@include Istdio.hJ
ain5 6
A
int iH
?D do soe ath D ?
i M 1 V 2 V 2H
?D do soe ore ath D ?
i M i V iH
printf5Fi M Ni KnF, i6H
B
?D desired output D ?
?D
i M 12
D?

26
Precomiler0
The precopiler 5soeties called Preprocessor6 is the first step in the copilation
process. %ts purpose is to'
16 reo$e coents before CrealC copilation
26 perfor precopiler stateents 5 a!k!a Preprocessor directi$es6
Precopiler stateents start #ith a @ as the first non #hite space character on the line.
.e ha$e already seen one'
@include Istdio.hJ
This stateent asks the precopiler to ebed the file stdio.h into our C file at the
place #here the directi$e appears.
There are se$eral ore that #e #ill e)aine'
@ define perfor te)t subtitution
@if IsttJ conditional include of code
@ifdef IsttJ perfor te)t substitution
@ifndef IsttJ if not defined, include the follo#ing code
@else else for any @if
@elseif IsttJ else if for any @if
@endif end of @if block
27
rog.a.c 8ifdef recomiler
ain 5 6
A
@ifdef >>>
printf5Fhello fro aaaKnF6H
@endif
@ifdef ***
printf5Fhello fro bbbKnF6H
@else
printf5F.hat you donCt like bbbYKnF6H
@endif
@ifndef CCC
printf5FdefineCCC to stop e before % print againGG KnF6H
@endif
B
%f you copile like this' acc prog3a.c
and run a.out, you see'
.hat you donCt like bbbY
define CCC to stop e before % print againGGG
%f you copile like this' acc !&>>> prog3a.c
and run a.out, you see'
hello fro aaa
.hat you donCt like bbbY
define CCC to stop e before % print againGGG
%f you copile like this' acc !&>>> !&*** prog3a.c
and run a.out, you #ill see
hello fro aaa
hello fro bbb
define CCC to stop e before % print againGGG
%f you copile like this' acc !&CCC prog3a.c
28
and run a.out, you #ill see
.hat you donCt like bbbY
29
rog9.c C basic data tyes
/* acc prog4.c !&C>/-1 !o prog4 D?
/* acc prog4.c !&C>/-2 !o prog4 D?
ain 5 6
A ?* all scalar!$ariables ay be initiali(ed #hen defined D?
/* progra to sho# declaring $ariables D?
/* and initiali(ing $ariables D?
@ifdef C>/- 1
char c M CaCH
double d M 1.22eV34
H
float f M 122.34H
int i M 221H
@endif
/* -=-UC%/-, change these to $alid $alues D?
@ifdef C>/-2
double d M CdCH
float f M 2H
int i M 1.22H
char c M dH
@endif
/* display character as character D?
printf5Fc M Nc KnF,c6H
/* display character as integer D?
printf5Fc M Nd KnKnF,c6H
/* display double in scientific D?
printf5Fd M Ne KnF,d6H
?D display double in float or scientific D?
/* lets coputer decide D?
printf5Fd M Ng KnKnF,d6H
/* display float as floating point D?
printf5Ff M NfKnKnF,f6H
/* display integer as base ten integer D?
printf5Fi M Ni KnF,i6H
/* display integer as base 17 integer D?
30
printf5Fi M N) KnKnF,i6H
B
31
6undamental Data Tyes
To Store # Character
%n C a char is just a subtype 5skinny6 integer. .hat #e norally think of as a
character 5displayable6 is siply the output to the screen fro soe display function.
/oething like C>C is an integer in C #hose $alue is 74 5>/C%% code for >6. >
stateent like' printf5FNcF, C>C6H
asks C to display the character #hose code is 74.
To Store 5ntegers
char 5usualy 1
byte, 9 bits6
short int 5at
least 2 bytes6
int 5usualy the sae si(e as a
achine #ord6
long int 5usualy at least 3 bytes
perhaps bigger6
To Store 6loating Point
2umbers
float 5at least 3 bytes, 8
significant digits6
double 5at least 9 bytes, 14 significant digits, ay
be larger6
long double 5at least 9 bytes, soe copilers
support 17 bytes6
To Store 1nsigned 5ntegers) 4ogical 3alues and $it
#rrays
unsigned char
unsigned short int
unsigned int
unsigned long int
To Store /7licitly Signed 5nts
signed char
signed short int
signed int
signed long int
%f the key#ord int is reo$ed, say fro signed int, the default data type is int so the
stateents
signed int and signed are syntactally e0ui$alent
built in oerator si-eof:7;
si(eof5 type6 returns @ of bytes in that type
si(eof5$ariable6 returns nuber of bytes in
that $ariable
32
Relationshis $et!een Si-es of 3ariables
1 M si(eof5char6 IM si(eof5short6 IM si(eof5int6 IM
si(eof5long6
si(eof5float6 IM si(eof5double6 IM si(eof5long
double6
si(eof5char,short,int,long6 M si(eof5rsigned6 char,short,int,long6 M si(eof5%unsigned6
c,s,i,l6
33
2%T/0 The follo!ing items !ere intentionally left to the discretion of the
comiler !riter0
16 #hether the default is signed or unsigned if the prograer does not specify it for
5har, short, int or long
26 the e)act nuber of bytes in any data type although iniu ranges ha$e been
specified
g,..c) illustrates si-eof:var;
<LT-' si(es of different types ay $ary fro syste
to syste
ain 5 6
A
char clH int ilH short slH unsigned ulH
long int 11H
printf5F/i(e of character is Nd
KnF,si(eof5cl6 6H
printf5F/i(e of short int is Nd
KnF,si(eof5sl6 6H
printf5F/i(e of unsigned int is Nd
KnF,si(eof5ul6 6H
printf5F/i(e of int is Nd KnF,si(eof5il6 6H
printf5F/i(e of long int is Nd
KnF,si(eof5ll6 6H
B
?D
saple
output
D?
?D
/i(e of
character is
1
/i(e of short
34
int is 2
/i(e of
unsigned int
is 3
/i(e of int is 3
/i(e of
long int is
3
D?
?D e)ercise'
odify this progra to find out ho# any bytes a float and a double
consue
D
?
35
PLUT>*%R%TO CL<C-U</
This is not a bad tie to say a fe# introductory #ords on the issue of portability.
Lne of the strongest arguents for aking the change to the C language is that of
portability. %f a progra is coded to the ></% standard, it should be !100N portable if
the target platfor has
an ></% copliant C copiler a$ailable. "o#e$er, there ha$e been any groups
that ha$e learned the hard #ay that they need to understand, the ></% standard in
order for their progras to #ork correctly cross!platfor.
%t is e)treely iportant to note the follo#ing in light of our discussion of
data types'
a short integer #ill be at least 2 bytes, but ay or ay not be 3
an int #ill typically be the sae si(e as a achine #ord, but #ill be at least 2
bytes
a long int #ill be at least 3 bytes, but could be longer
>ny progra that needs to be portable 5and still function correctly6 should be careful
to use these data types correctly. *ack in C:2 a client?ser$er soft#are group learned
this the hard #ay. Their progra, #hich ran fine on an %*W ainfrae, hung their
PC 5&L/ achines6 e$en though it had copiled #ithout error or #arning. Their
progra #as riddled #ith counters of type int 5keeping track of the nuber of
records read etc.6, #hich #ould keep track of counts soeties reaching 1 illion or
ore. Their ainfrae copiler had 3 byte ints, their PC copiler had 2 byte ints.
5U><1-' 2 bytes M 0 to 74424 3 bytes M 0 to 3,2:3,:78,8736
/uggestion' analy(e your data first and ...
!if you ean to store 2 byte 0uantities use a short
!if you ean to store 3 byte 0uantities use a long
!if you need a data $alue the si(e of a achine #ord 5and adjusts cross!
platfor6
use an int 5handy #hen #riting operating syste code or
interrupt handlers6
!analysis of the data #ill also help you decide #hether you need
specify signed or
36
unsigned, if there is a need to specify it please do so.
Lne last #ord for no# ...
Wany C copilers coe #ith e)tra libraries supporting sound, fancy graphics, lo#!
le$el hard!
#are %?L, etc. Please note that these Cadd!inC libraries are generally not ></% standard
and are not supplied #ith any copilers. 5does ouse control ean anything on a
2289 attached to a WS/ syste6 %t does you little good to ha$e a progra that does
fancy screen %?L if it cannot be ported to another platfor 5unless, of course, it is
strictly intended for only one platfor6
Simlest C rogram ossible0 Part 55
full #2S55 comatability !ith no comiler !arnings or errors
$oid ain 5$oid6' ?D prototype for ain, usually not re0uired, but
guaranteed
to #ork #ith all ></% copilers D?
$oid ain5 6
A
B
LU
?D ></% header stating return type D ?
int ain5$oid6H ?D prototype for ain, usually not re0uired, but guaranteed
to #ork #ith all ></% copilers D?
int ain 5 6
A
return 0H
B

37
rog<.c mathematics oerators) recedence
ain 5 6
A
/* declare four integers and space for ans#ers D?
int a M 1H int b M 2H int c M 2H int d M 3H int ansH
?D precedence of ! V D
5 6 parentheses
! unary inus V unary plus
VV increent !! decreent
D ultiplication
? di$ision
N odulo
V addition ! subtraction
MM e0uality M e0uals D?
?D print initial $alues D?
printf5Fa MJ Ni Kt b MJ Ni Kt c MJ Ni Kt d MJ Ni KnKnF,a,b,c,d6H
?D subtraction e)aple D?
ans M a ! bH
printf5Fa ! b M Ni KnF,ans6H
?D precedence proble, #ant addition then ultiplication D?
ans M a V b D cH
printf5Fa V b D c M Ni KnF,ans6H
?D precedence e)aple D?
ans M 5 a V b 6 D cH
printf5F5 a V b 6 D c M Ni KnF,ans6H
B
=> samle outut >=
a ?@ ' b?@ + c?@, d?@.
a A b ? B'
a C b > c ? D
: a C b; > c ? E
38
rogD.c mi7ed mode arithmetic
?D progra deonstrates atheatics, precedence and the difference bet#een integer
di$ision D?
?D ho# $alue is stored is deterined by destination data type D?
?D and floating di$ision DB
ain 5 6
A
/* declare and initiali(e
integers D? int a M 8H int b
M 2H int intQansH
?D declare and initiali(e floats D?
float c M 8.0H float d M 2.0H float float ansH
?D print initial $alues D?
printf5Fa MJ Ni Kt b MJ Ni Kt c MJ NfKt d MJ
NfKnKnF,a,b,c,d6H
printf5Finteger di$ided by
integer KnF6H
intans M a ? bH
printf5FNi ? Ni M Ni KnKnF,a,b,intQans6H
printf5Ffloat di$ided by
float KnF6H
float ans M c ? dH
printf5FNf ? Nf M NfKnKnF,c,d,floatQans6H
intans
M c ? bH
floatan
s M c ?
bH
printf5+float di$ided by integer KnF6H
printf5F stored in integer Nf ? Ni M Ni
KnF,c,b,intQans6H
printf5F stored in float Nf ? Ni M
NfKnKnF,c,b,floatQans6H
39
printf5Finteger di$ided by a
float KnF6H
intQans M a ? dH
floatQans M a ? dH
printf5F stored in integer Ni ? Nf M Ni
KnF,a,d,ineans6H
printf5F stored in float Ni ? Nf M
NfKnKnF,a,d,floaeans6H
printf55F!a M Ni KnF,!a6H
printf5F!c M NfKnF,!c6H
B
40
samle outut
a MJ 8 b MJ 2 C MJ 8.000000 d MJ 2.000000
integer di$ided by integer
8?2 M 2 .H
float di$ided by float
8.000000 ? 2.000000 M 2.400000
float di$ided by integer
stored in integer 8.000000 ? 2 M 2
stored in float 8.000000 ?2 M 2.400000
integer di$ided by a float
stored in integer 8 ?2.000000 M 2
stored in float 8 ?2.000000 M 2.400000
!a M!8
!c M !8.000000
41
rog8.c the modulus :remainder) residue; oerator
/* the odulus operator only #orks on #hole nubersD?
ain 5 6
A
int gu(intaH
int reH
gu(inta M 24 ?4H
re M 24 N 4H
printf5F4 goes into 24 Ni ties #ith reainder Ni KnF,gu(inta, re6H
gu(inta M 24 ? 8H
re M 24 N 8H
printf5F8 goes into 24 Ni ties #ith reainder Ni KnF,gu(inta.re6H
B
output youCll see
4 goes into 24 4 ties #ith reainder 0
8 goes into 24 2 ties #ith reainder 3
42
/7ercise ,
?D Part 1 D?
?D #rite a progra that e$aluates the follo#ing e)pression D?
?D display the result in integer forat D?
?D
ans M 8 ties : plus 1: di$ided by 4 odulo 2

do the ultiplication first
the di$ision second
the odulo third
and the addition last
D?
?D Part 2 D?
?D #rite a progra that e$aluates the follo#ing e)pression D?
?D use e)ponential forats for the nubers D?
?D display the result in e)ponential forat D?
?D 5.0000000:8 V 2010 6 ? 5 9:000 D 226 D?

43
Solution for /7ercise ,
ain 5 6
A
int ansH
float a,b,c,dH
float nueratorH
float denoinatorH
float resultH
a M :.8e!9H
b M 2.01e2H
c M 9.:e3H
d M 22.0H
ans M 5 8 D : 6 V 5 5 1:?4 6 N 26H
printf5Fans M Ni KnF,ans 6H
nuerator M a V bH
denoinator M c D dH
printf5Fnuerator M Ne KnF,nuerator6H
printf5Fdenoinator M Ne KnF,denoinator6H
result M nuerator ? denoinatorH
printf5FUesult M Ne KnF,result6H
B
44
Relational :Comarison;
%erators
I less than
J greater than
M e0ui$alent to
IM less than or e0ui$alent to
JM greater than or e0ui$alent to
GM not e0ui$alent to
Uelational operators are used in relational e)pressions. > relational e)pression is
defined as anything that can produce a True or Palse ans#er. Palsity is defined as (ero.
Truth is defined as non!(ero. > $ariable by itself can be a relational e)pression
because its $alue #ill be e)ained to see if it is (ero or non (ero. > relational
e)pression can e)ist by itself, it does not ha$e to be e)ained #ithin the conte)t of a
decision.
The relational operators return a 1 if true,
0 if false.
45
?D ste$e.c >ugust 10, 1::2 D?
ain 5 6
A
int ), y, (H
y M 2H
?D y M 2 is a relational e)pression D ?
?D its truth or falsity is assigned to ) D?
) M y MM 2H ?D assign to ) the result of the coparison D?
printf5F>>> ) M Ni y M NiKnF,),y6H
y M 2H
?D y MM 2 is a relational e)pression D ?
?D its truth or falsity is assigned to ) D?
) M y MM 2H
printf5F*** ) M Ni O M NiKnF,),y6H
) MM yH ?D no side effect, return $alue not used, this does nothing D?
printf5FCCC ) M Ni y M NiKnF,),y6H
) I yH
printf5F&&& ) M Ni y M NiKnF,),y6H
( M ) I yH
printf5F--- ( M Ni ) M Ni O M NiKnF,(,),y6H
?D saple output D?
>>> )M L y M 2
*** ) M 1 y M 2
CCC ) M 1 y M 2
&&& ) M 1 y M 2
--- ( M 1 ) M 1 O M 2
Uun this progra through alint and see that it tells you that there are se$eral bugs.

46
rogEa.c three tyes of loos
ain 5 6
A
int suH
int nH
?D su and loop counter need to be initiali(ed D?
su M 0H n M !4H
?D #hile 5relational e)pression6 D?
?D #hile loop, check condition at top D?
#hile 5 n IM 4 6
A
su M su V nH
n M n V 1H
printf5Fn is Ni su is Ni KnF,n,su6H
B
printf5F."%R- RLLP'su is Ni KnKnKnF,su6H
?D do loop, check condition at botto D?
su M 0H n M !4H
do
A
su M su V nH
n M n V 1H
printf5Fn is Ni su is Ni KnF,n,su6H
B #hile 5 n, IM 4 6H
printf5F&L RLLP'su is Ni KnKnKnF,su6H
?D for loop, C shorthand to get all loop things on one line D?
for 5 su M 0, n M !4H n IM 4H nVV 6
A
su M su V nH
B
?D print out the results D?
printf5FPLU RLLP'su is Ni KnKnF,su6H
B
47
roglF.c for loo
/* progra to calculate s0uares
D ?
a
in
5 6
A
int s0uareH
int nH
printf5FT>*R- LP /Z;>U-/ <;W*-U/ KnKnF6H
printf5CCKt n Kt n s0uaredKnF6H
printf5CCKt!!!Kt!!!!!!!!!!KnCC6H
for 5 n M 1H n IM 20H
nVV 6
A
s0uare M n D nH
printf5CCKt Ni Kt Ni
KnF,n,s0uare6H
B Kt is the tab character
B
48
T>*R- LP /Z;>U-/ <;W*-U/
n n s0uared
!!! !!!!!!!!!!!!
1 1
2 3
2 :
3 17
4 24
7 27
8 3:
9 73
: 91
10 100
11 121
12 133
12 17:
13 1:7
14 224
17 247
18 29:
19 223
1: 271
20 300
49
Coparison of Roop /ynta)
Por a M 1 to 28 by 2
Por 5 n M 1H n IM 20H nVV6
n is initiali(ed to 1 ?? n M 1
perfor test, ?? if n IM 20
if true, do body
if false, skip body
after body perfored, do increent
??nVV
50
St!rtin#
Condition
Condition $o
Contine
increment done !%ter
"od&'
"e%ore te(tin# condition
-)ercise' Ue#rite the pre$ious e)aple 5progl0.c6 and replace the for loop
#ith
a #hile loop, and then a do!#hile loop.
-)ercise' Wake the pre$ious progra do the table of s0uares fro 10 to
40
by 2Cs. i.e, 10 12 13 17 ...
-)ercise' Wake the pre$ious progra do the table of s0uares fro 22 to
!8
by !2Cs i.e. 22, 20,28,23 ...
51
rog''.c for loo scanf inut
?D progra to calculate s0uares D ?
?D introduces scanf for
user input D?
ain 5 6
A
int s0uareH
int cubeH
int nH
int user nuberH
printf5F"o# far do you #ant to go toY KnF6H
scanf5FNiF,[userQnuber6H
printf5CCKnOou entered Ni KnKnF,userQnuber6H
printf5FT>*R- LP /Z;>U-/ [ C;*-/KnKnF6H
printf5FKt n Kt n s0uared Kt n cubedKnF6H
printf5CCKt!!!Kt!!!!!!!!!!!Kt !!!!!!!!!KnF6H
for 5n M 1H n IM userQnuberH nVV6
A
s0uare M n D nH
cube M s0uare D nH
printf5CCKt Ni Kt Ni KtKt NiKnF,n,s0uare,cube6H
B
B
?D -=-UC%/-' reo$e the [ fro [userQnuber, you #ill e)perience a core
dup. This is because scanf re0uires the [ on the $ariable to read the data into. %t
needs to be passed the address of #here to #rite to D?
?D ;<%= PUL1U>WW-UC/ "%<T' #hen you ha$e a progra #ith a
scanf in it,
do a grep on the file #ith the scanf as the string to search for.
&ouble check that e$ery scanf has an [ associated #ith it. %f
you kno# C shell prograing, ake a shell script to do the
grep and print only the lines that ha$e scanfs and not [ D?
%f the [ is left off, and if you use the highest #arning le$el, the copiler should
52
#arn you that
you are trying to use the $alue of the $ariable userQnuber before it has been set.
TUO TL 1-T %<TL T"- ">*%T LP U->&%<1 >RR .>U<%<1/ PULW T"-
CLWP%R-UG %T %/ CL</%&-U-& 1LL& PU>CT%C- T">T OL;U PUL1U>W
."-< C&L<-C /"L;R& C>;/- <L .>U<%<1/.
53
-=-UC%/-' see ho# large a nuber you can input and still get the s0uare and cube
of. Try to ake the integer result go out of range
/C><P FPeatureF or F*ugF
scanf al#ays lea$es a carriage return in the input strea. %f you are i)ing
line input $ia scanf and character input $ia getchar, you #ill ha$e to eat the
carriage return left behind by the scanf or you #ill ha$e to flush the input
strea
9: cr 22 cr CpC cr
1sing scanf for 5nut
scanf:G format&secifierG ) address of variable to satisfy format&secifier;H
54
rog'+.c nested for loos
II1kranian doll for loosG II(atreshkaII
/* progra to calculate s0uares D ?
?D introduces nested for loop D?
ain 5 6
A
int s0uare, n, userQnuber, counter, iH
?D this loop #ill be done four ties D?
?D counter #ill take on the $alues, 1 223 D?
for 5counter M 1H counter I 4H counterVV 6
A
printf5F"o# far do you #ant to go toY KnF6H
scanf5FNiF,[userQnuber6H
printf5CCKtOou entered Ni KnKnF,userQnuber6H ?D Kf for feed D?
printf5FT>*R- LP /Z;>U-/ KnKnF6H
printf5CCKt n Kt n s0uaredKnF6H
printf5CCKt!!!Kt!!!!!!!!!!KnCC6H
?D this loop #ill be done userQnuber ties D?
?D n #ill take on $alues 1 through userQnuber D?
for 5n M 1H n IM userQnuberH nVV 6
A
s0uare M n D nH
printf5CCKt Ni Kt Ni KnF,n,s0uare6H
B /* end of n loop D?
B ?D end of counter loop D ?
printf5CCKnKnCC6H
?DCLWWL< PUL1U>WW%<1 W%/T>K-/ D?
for 5 i M 0H i I 4H iVV 6
A
printf5Fouter i M Ni KnF,i6H
55
?D using sae loop counter in a nested loop D?
for 5 i M 7H i I :H iVV 6
A
printf5Finner i M Ni KnF,i6H
B
printf5+KnKn,6H
for 5 i M 0H i I 4H iVV 6
A
printf5Fouter i M Ni KnF,i6H
?D changing $alue of loop $ariable D?
i VM 8H
B
B /* end ain D?
56
>ssue i and j are ints
.hat .ould be PrintedY
for 5 i M 0H i I 4H i VV 6
A for 5j M 4H j J 2H j!! 6
A
printf5FNi NiKnF .i.j6H
B
B
>ssue ) and are ints
) M 4H
#hile 5 ) I 106 A
M ) D 10H
do A
printf5FNi Ni KnF .).6H
MV 5?26H
B #hile 5 I 200 6H
) M ) V 2H
B
57
rog',.c !hile loo
?D #hile loop D ?
?D introduces Ka, ansi alert characterD ?
ain 5 6
A
int iH
int su M 0H
i M !4H
#hile 5 i IM 4 6
A
printf5+Ka i M Ni KnF,i6H
su VM iH
iVVH
B
printf5F/u fro !4 to 4 is Ni KnF,su6H
?D CLWWL< PUL1U>WW%<1 W%/T>K- D?
/* %nfinite RLLP D?
i M 1H
-S-UO C stateent returns a $alue that ay be used or ignored
T"- U-T;U< $alue of an assignent stateent is the $alue assigned
#hile 5 i M 1 6
A
printf5F i M Ni KnF,i6H
iVVH
printf5F i M Ni KnF,i6H
B
/* ;<%= PUL1U>WW-U "%<T D?
?D *-PLU- CLWP%R%<1, ><& -/P-C%>RRO *-PLU- U;<<%<1 D?
?D
grep your file for all lines that ha$e if, #hile, for in the
double check that you ha$e M #here M is needed, and not M
any prograers replace MM #ith soe other defined $alue
58
see @define stateent later
D?
/* add this line to top of progra
@define WO-Z MM
then change the M in the #hile 5 i M 1 6 to #hile 5 i WO-Z 1 6 D?

59
rog'..c !hile loo for secret number guessing
?D #hile loops D?
?D progra to ask for guesses until they get it right D?
ain 5 6
A
int guess M !1H
int secret M 8H
int count ofCguesses M 0H
printf5FTry to pick a nuber fro 1 to 10 KnF6H
?D possible infinite loop if user is real idiot D?
#hile 5 guess GM secret6
A
count ofCguessesVV'
printf5F-nter a guess KnF6H
scanf 5FNiF,[guess6H
printf5CCKn Oou entered Ni KnF ,guess6H
B ?D end #hile D?
printf5+Oou got it after Ni tries KnF,countQofQguesses6H
B
60
prog'9.c !hile loo vs. do loo
/* progra to let user guess secret nuber */
/* sho#s difference bet#een #hile loop and do
loop */
ain 5 6
A
int guessH
int secret M 8H
int countQofQguesses M 1H
printf5FTry to pick a nuber fro 1 to 10 KnF6H
/* possible infinite loop if user is real idiot */
/* need to preinitiali(e $alue for #hile loop */
printf5F-nter guess @NiKnF,countQoCguesses6H
scanf 5FNiF,[guess6H
printf5CCKn Oou entered Ni KnF ,guess6H
#hile 5 guess G M secret6
A
printf5F.UL<1KnF6H
CL<TULR #ill return fro the syste stateent #hen the entire
coand has been copleted. %P T"- coand #as placed in the
background
control #ill return as soon as the placeent has occurred
syste ("usr/demo/SOUND/play
lusr?deo?/L;<&?sounds?laugh.auF6H
countQ ofQguessesVV'
printf5F-nter guess @
NiKnF,countQofQguesses6H
scanf 5FNiF,[guess6H
printf5CCKnOou entered Ni KnF,guess6H
B /* end #hile */
printf5FOou got it after Ni tries KnF,countQoCguesses6H
61
printf5FTry to pick a nuber fro 1 to 10 KnF6H
countQofQguesses M 0H
secret M 2H
/* do not need to preinitiali(e $alue for do loop D?
do
A
countQofQguessesVVH
printf5F-nter guess @
NiKnF,countQofQguesses6H
scanf 5FNiF,[guess6H
printf5+Kn Oou entered Ni KnF
,guess6H
if 5 guess
GM
secret6
A
printf5F.UL<1KnF6H
syste 5+?usr?deo?/L;<&?play
?usr?deo?/L;<&?sounds?laugh.auF6H
B #hile 5 guess GM secret 6H
printf5FOou got it after Ni tries
KnF,countQofQguesses6H
B
62
/7ercise .
?D #rite a progra to copute and print the first
ten D ?
/* factorial nubers D?
?D desired output is a table D?
?D 1G 1 D?
?D2G 2 D?
?D2G 7 D?
?D ... D?
?D 10G 2729900 D ?
%f your progra is ore than 14 lines5of code, not counting coents6 it is going the
#rong
direction.
"%<T' atheatical identity <G M 5<!%6G D <
63
Solution for /7ercise .
main : ;
A
int i, factorialH
factorial M 1H
for 5 i M 1H i IM 10H iVV6
A
factorial M factorial D iH
printf5+NiG?tNiKn,,i, factorial6H
B
B
64
/7ercise 9
/* #rite a c progra to input an integer as an integerD ?
?D print out the nuber, one digit per line D?
?D i.e. input 1223 D?
?D output 3 D?
?D 2 D?
?D 2 D?
?D 1 D?
Solution for /7ercise 9
main: ;
A
int iH
int outnuH
rintf:G5nut number lease JnG;H
scanf:GKiG )Li;H
!hile :i @ F;
A
outnum ? i K 'FH
rintf:GKiJnG )outnum;H
i M i = 'FH
B
B
65
C if if else
if .c
ain 5 6
A
int iH
printf5Fenter a nuber KnF6H
scanf5FNiF,[i6H
if :i M 'FF;
A
printf5FNi is less than one hundred KnF,i6H
B
printf5F>fter the first if stateentKnF6H
if 5i I l06
A
printf5FNi is less than ten KnF,i6H
B
else
A
printf5FNi is greater than or e0ual to tenKnF,i6H
B
B
if : relationale)pression ;
A
e7ecute if re TR1/
\\\
B
else => must follo! immediately >=
A
e7ecute if re 6#4S/
B
66
rog'<.c math.h include file
/* if stateent D?
?D ath.h contains atheatical functions like s0rtL D?
8include Mmath.h@
ain 5 6
A
float nuberH
float s0uareQrootH
printf5CCKnKnType in a nuber KnF6H
scanf5FNf,,[nuber6H
printf5CCKnOou entered NfKnF,nuber6H
if 5 nuber I 0 6
A
printf5FCanCt get s0uare root of negati$e nuber KnF6H
B
else
A
s0uareQroot M s0rt5nuber6H
printf5FThe s0uare root of Nf is NfKnF,nuber,s0uareQroot6H
B
printfC5+Progra copleted KnF6H
B
?D -=-UC%/- reo$e the @include Iath.hJ line and see #hat you get D?
/* soe 5but not all6 of the ath functions a$ailable
for a coplete list, consult your copilerCs docuentation
ceil5)6 floor5)6
sin5)6 cos5)6 tan5)6 asin5)6 acos5)6 atan5)6
sinh5)6 cosh5)6 tanh5)6
e)p5)6 log 5)6 loglL5)6 po#5),y6
D?
67
rog'E.c logical oerators and relational e7ressions
?D precedence of logical operators and
brackets D ?
?D
I less than
IM less than or e0ual to
J greater than
JM greater than or e0ual to
MM e0uality
GV ine0uality
[[ logical and
]] logical or
ain 5 6
A
int scoreH
printf5F-nter the scoreKnF6H
scanf5FNiF,[score6H
printf5FOou entered NiKnF,score6H
if 5 score I 0 ]] scoreJ 100 6
printf5+%possible scoreKn,6H
else
A
if 5 score JM 0 [[ score I 40 6
printf5FPKnF6H
else
A
if 5 score JM 40 [[ score I 806
printf5+&Kn,6H
else
A
if 5 score JM 80 [[ score I 906
68
printf5+CKn,6H
else if 5 score JM 90 [[ score I :06
printf5+*Kn,6H
else if 5score JM :0 [[ score IM 1006
printf5,>Kn,6H
else
printf5+no #ay to get here Kn,6H
B
B
B
B
69
if : relational e7ression;
relational e7ression evaluates to TR1/ or 6#4S/
if : : r e l6 ]] : r e +; ;
NN is the logical or oerator
re1 re2 result
t t t
t f t
f t t
f f f
70
if : relational e7ression;
relational e)pression evaluates to TR1/ or 6#4S/
if : : re'; LL : re+; ;
LL is the logical and oerator
rel re2 result
t t t
t f f
f t f
f f f

71
rog+F.c comle7 decision structures
@define %*W 1
@define W-U 2
@define WW& 2
@define Z;%T 3
ain 5 6
A
int stock sybolH
char pQorQcH
char crH
printf5CCKn-nter stock sybo%KnF6H
printf5F 1 %*WKnF6H printf5F2 W-U Kn,6H
printf5F2 WW&KnF6H printf5F3 Z;%T Kn,6H
scanf5FNiF,[stockQsybol 6H
scanf5FNcF,[cr6H
printf5FOou entered NiKnF,stockQsybol6H
if 5 stock sybol MM %*W 6
printf5FN.2fKnF,42.246H
else if 5 stockQsybol MM W-U6
printf5FN.2fKnF,81.846H
else if 5 stockQsybol MM Z;%T 6
printf5FOL; /-R-CT-& Z;%TKnF6H
else if 5 stocksybol MM WW& 6
A
printf5F5P6referred or 5C6oonYKnF6H
scanf5FNcF,[pQorQc 6H
scanf5FNcF,[cr6H
if 5pQorQc MM CPC 6
A
printf5FPreffered 22.4K11F6H
B
72
else if 5pQorQc MM CcC 6
A
printf5+Coon 21.24K11F6H
else
printf5F;nkno#n character KnF6H
B
else
printf5F;nkno#n sybo%KnF6H
B

73
s!itch :discreet valued variable;
A
case discreet value0
OOO
OOO
breakH
case discreet value0
OOO
OOO
breakH
OOO
OOO
default0
OOO
OOO
breakH
B

74
rog+'.c s!itch statement
@include Istring.hJ
@include Ictype.hJ
@define %*W 1
@define W-U 2
@define WW& 2
@define Z;%T 3
int stockQsybolH
char pQorQcH
char crH
printf5+Kn-nter stock sybolKnF6H
printf5F 1 %*WKnF6H
printf5F2 W-UKnF6H
printf5F2 WW&KnF6H
printf5F3 Z;T%KnF6H
scanf5FNiF,[stockQsybol 6H
scanf5FNcF,[cr6H
printf5+Oou entered NiKnF,stockQsybol6H
s#itch 5 stockQsybol 6
A
case %*W'
printf5FN.2fKnF,42.246H
breakH
case W-U'
printf5FN.2fKnF ,81.846H
breakH
case Z;%T'
printf5FOL; /-R-CT-& Z;%1KnF6H
breakH
caseWW&'
75
printf5F5P6referred or 5C6oonYKnF6H
scanf5FNcF,[pQocc6H
scanf5FNcF,[cr6H
if 5toupper5pQorQc6 MM CPC 6 ?D this is an atrocious line of code
D?
?D can you figure out #hyY D?
A
printf5FPreffered 22.4K11F6H
B
else if 5toupper5pQorQc6 MM CCC 6 ?D >TULC%L;/ D?
A
printf5FCoon 21.24KnF6H
B
else
printf5+;nkno#n characterKn,6H
breakH
default'
printf5F;nkno#n sybo%KnF6H
B ?D end s#itch D?
?D -)ercise, reo$e the break in case %*W, #hat happensY .hyY D?
T"-/- T.L R%<-/ >U- >TULC%L;/, yet coon.
.hyY
5toupper is a acro that con$erts a character to its upper case e0ui$alent6

76
/7ercise <
/* #rite a progra to ha$e a person guess a secret nuber.
Ret the range of $alid nubers be (ero to 100.
Ret the ha$e a a)iu of 8 tries.
Tell the if they #ere too high or too lo#.
Ueport the reaining range of possiblities for the D?

77
Solution for /7ercise <
ain 5 6
A
int secretH
int guessH
int
nuQgu
esses M 0H
int hi M
100H
int lo M0H
int seedH
printf5F.hat tie is it hh''ssKnF6H
scanf5FNi'Ni'NiF,[seed,[seed,[seed6H
srand5 seed6H ?D rando nuber function D?
secret M 5int6 rand56 ? 220H
if 5 secret I 0 6
secret M 0H
if 5secretJ 100 6
secret M 100H
?D ake sure that guess is incorrect to begin
#ith D?
guess M secret ! 1H
#hile 5 5secret GM guess6 [[ 5nu
guesses I 86 6
A
nuQguessesVVH
prfntf5F-nter a guess bet#een Ni and NiKnF,hi,lo6H
scanf5FNiF, [guess6H
printf5CCKnOou entered NiKnF,guess6H
78
if
5 guess
I
secret6
A
syste 5F?usr?deo?/L;<&?play
?usr?deo?/L;<&?sounds?laugh.auF6H
printf5FTLL RL.KnF6H
if 5 guess J lo 6
lo M guessH
else if 5 guess J secret6
A
syste 5F?usr?deo?/L;<&?play ?usr?deo?/L;<&?sounds?
laugh.auF6H
printf5FTLL "%1"KnF6H
if 5 guess I hi 6
hi M guessH
B
B
B
B
79
/7ercise D
?D 6%R TP/ (#TP/(#T5C#44Q 52C452/D >=
?D #rite a progra to sol$e for the real roots of D ?
?D the 0uadratic e0uation a)^2 V b) V c D?
?D input a , b , c D ?
?D check for real or iaginary roots D ?
?D ake sure not to di$ide by (ero D?
?D test data 1 2 1 MJ single real root )1 M !1 D?
?D 1 !1 !7 MJ t#o real roots )1 M !2, )2 M 2 D?
?D 0 0 0 MJ one real root )1 M 0 D?
?D 0 3 !2 MJ one real root )1 M .4 D?

)l M !1
)l M !2, )2 M 2
)l M0
)l M.4
80
Solution for /7ercise D
@include Iath.hJ
ain 5 6
A
float a, b, cH
float discriinantH
float )l, )2H
printf5FKnKninput a b and c separated by spaces KnF6H
scanf5FNf Nf NfC,[a,[b,[c6H
printf5Fyou entered Nf Nf NfKnKnKnF,a,b,c6H
discriinant M 5 b D b6 ! 5 3 D a D c6H
if 5 discriinantJ 0 6
A
if 5a MM 06
A
if 5 b MM 0 6
A
printf5F) M 0 KnF6H
else
A
)l M 5!c6?bH
printf5F/ingle real root is NfKnF,)l6H
B
B
else
A
)l M 5 !b V s0rt5bDb ! 3DaDc66 ? 52 D a6H
)2 M 5 !b ! s0rt5bDb ! 3DaD66 ? 5 2 D a6H
printf5FT#o real roots are KnF6H
printf5FNf NfKnF,)l,)26H
B
81
else if 5 discriinant ??
0 6
A
printf5Fone real root K
nF6H
if 5a MM 0 6
A
)l M 0H
printf5F)l M
NfKnF,)l6H
B
else
A
)l M !b ? 52Da6H
printf5F)l M
NfKnF,)l6H
Belse
A
printf5+%aginary UootsKn,6H
B
printf5+KnKn,6H
B?D end progra D?
82
/7ercise 8
?D e)ercise for those #ho donCt #ant to do 0uadratic e0uations D?
?D #rite a C progra that'
inputs an integer nuber fro the keyboard
displays it for#ards
displays it back#ards D?
?D big, brain buster
as you re$erse the nuber, print out each digit on a
seperate line, #ith the english language #ord beside the digit D?

?D huungous brain destroyer
print out the english #ord for the nuber as a #hole
i.e. 742 MJ si) hundred fifty three
D?

83
Solution for /7ercise 8
?D #rite a c progra to input an integer
D?
/* print out the nuber, one digit per
line D?
?D i.e. input 1223 D?
?D output 3
2
2
1 D? .
?D then print it out in re$erse order D?
?D then print the english #ord beside each digit D?
char D #ords_` M A FTeroF, F;nF, F&eu)F, FTroisF, FZuatreF, FCin0F, F/i)F,
F/eptF, F"uitF, F<euf,BH
?D
solution
D?
ain 5 6
A
int
i,safe,outnu
H
int re$nu
M 0H
printf5F%nput nuber
KnF6H
scanf5FNiF,[i6H
#hile 5i
J 06
A
outnu M i N 10H ?D strip off last digit D?
re$nu M re$nu D 10 V outnuH
84
printf5FNi KnF,outnu6H ?D print it D?
i M i ?10H ?D di$ide current nuber by 10
effecti$ely dropping last
digit D?
safe M
re$nuH
printf5CCKnK
nCC6H
85
#hile 5 re$nu J 0 6
A
outnu M re$nu N 10H ?D strip off last digit D?
printf5FNi KnF,outnu6H ?D print it D?
re$nu ?M 10H
B
printf5CCKnKnCC6H

?D no# print digit by digit #ith english #ords D?
#hile 5safe J 0 6
A
outnu M safe N 10H ?D strip off last digit D?
printf5FNiKtF,outnu6H ?D print itD?
printf5F N sKtF,#ords _outnu`6H
s#itch5 outnu6
A
case 0'
printf5FTeroK
nF6H
breakH
case 1'
printf5FLneK
nF6H
breakH
case 2'
printf5FT#oK
nF6H
breakH
case 2'
printf5FThreeK
nF6H
breakH
86
case 3'
printf 5FPourF6H
breakH
case 4'
printf5FPi$eK
nF6H
breakH
case 7'
printf5F/i)K
nF6H
breakH
case 8'
printf5F/e$enKn6H
breakH
case 9'
printf5F-ightK
nF6H
breakH
case :'
printf5F<ineKnF6H breakH
B
safe ?M 10H ?D di$ide current nuber by 10 D?
B
B
87
errors.c
?D putting a sei colon after a definition D?
@define W>=QS>R;- 100H
?D forgetting that upper and lo#er case atter D?
@define L<- 0H
ain 5 6 A
int j M 200H int k M 0H
?D adding a sei!colon #here there shouldnCt be one D?
if5 j M 1006H
printf5FJ M 100KnF6H
?D lea$ing off a sei!colon #here there should be one D?
?D #onCt copile because of @if 0 D?
@if 0
if5 j M 1006
?D issing a sei!colon #here you need one D?
printf5Fl M 100KnF6
else
printf5FJ not e0ual to 100 KnF6H
?D using one M #here you need t#o MM D?
if 5j M W>=QS>R;- 6
printf5FJ #as e0ual to W>=Q S>R;-KnF6H
@endif
?D putting M instead of MM in a conditional D?
if5j M 16
printf5FJ #as e0ual to 1 KnF6H
?D not using parantheses on ath and forgetting D?
?D the precedence of operations D?
j M 1 V 2 ! 2 D 3? 4 ? 7 D 8 ! 9 V :H
prif5FJ M Nd KnF,j6H
88
@if 0
j M LneH
printf5Fj M Nd KnF,j6H
@endif
?D forgetting the [ character in scanf calls #ill cause core dup D ?
printf5F-nter $alue for j KnF6H
scanf5FNiF, j6H
printf5+Oou entered NiKnF,j6H
"ere is a line of code actually found in a CrealC deli$ered
product'
if 5length M 96 length MM 8H /* if length is 9 reset it to 8 */
it #as 0uite interesting to deterine #hat if anything to do #ith or about this ..
.hat #ould you ha$e doneYY
89
rog++.c simle array
/* introduces siple array */
?D note that inde)ing goes fro 0 to 3 */
/* declaration synta) indicates 4 cells */
/* starting at inde) 0 */
ain5 6
A
int array'R9SH
int iH
arrayl_0` M 22H
array1_1` M 18H
array1_2` M 2:H
array1_2` M 2H
array1_3` M !8H
for 5 i M 0H i IM 3H iVV 6
A
printf5Farray1_Ni` M Ni KnF,i,array1_i`6H
B
?D
arrayl_0` M 22
array 1 _1` M 18
array1_2` M 2:
array 1 _2` M 2
array 1 _3` M!8
D?
90
#rrays0 Discussion
To declare an array #e state the type of its eleents, the nae of the array, and the
nuber of eleents in it'
int arl_l0`H
defines storage for an array of 10 integers called arl.
/ince all calls in C are call by $alue, #hat is the $alue of arl if #e #ere to pass it to a
functionY
Wentioning arl #ith no subscript is to ention its address. This eans the address of
the first eleent in the array. .hen an array is subscripted, like' ar_1` M 32H
#hat actually happens is this, the copiler generates the code to take the starting
address of the
array 5the address of the (ero!th eleent, arl6, adds the si(e of 1 integer to it 5to get the
address of the eleent at location 1 in the array6 and Cgoes toC that address. %n this case
#e are doing an
assignent operation, so the correct code is generated to perfor a eory store at
that address.
/ince the copiler generates the address in this #ay, it assues the prograer has
$erified that
the resulting address #ill be correct. There are no array bounds checking in C) neither
at comB
ile nor at run timeT Part of the reason for this is to a)ii(e e)ecution speed, the
other is that
the authors #ish to place the responsibility for 5orrectness upon the prograer at
design tie.
Lther languages 5like Pascal6 enforce tight run!tie checking.
>rrays ay ha$e ore than 1 diension'
int t#oQdi _2` _2lMA A 1,2,2 B, A 3,4,7B BH
t#oQdi is a 2 by 2 array of integers. There are 2 ro#s of three coluns.
Lr #e ight say t#oQdi is an array of 2 2 integer arrays. %n fact this is a better
description as that is ho# it is stored reeber, a 2 integer array is represented by its
address. /o t#oQdi has 2 entries in it each of #hich is the address #here a 2 integer
array begins in eory.
91
t#oQdi 1000
1012
The stateent t#oQdi_1`_2` M 32H is copiled as'
Take the address in t#oQdi_1`, add 2 integer si(es to it and go to that address and
assign the
$alue 32 51012 V 52 D 36 M 1020 the address of the third ite in the second ro#6
92
rog+,.c array boundaries
ain5 6
A
int array1_4` M A 22, 18, 2:, 2,
!8 BH
?D print out $alues in
array D?
for 5i M 0! i IM 3! iVV6
printf5Farrayl_Ni` M Ni
KnF,i,arrayl_i`6H
?D print out $alues in array and beyond boundaries of
array D?
for 5 i M !3H i I 10H iVV 6
printf5Farrayl_Ni` M Ni KnF,i,arrayl_i`6H
B
?D saple output D?
array 1 _0` M 22
array1_1` M 18
array1_2` M 2:
array1_2` M 2
array 1 _3` M!8
array 1 _!3` M 2
array1_!2` M 17
array1_!2` M !212040:448
array1_!1` M !1
arrayl_0` M 22
array 1 _1` M 18
array1_2` M 2:
array1_2` M 2
array 1 _3` M!8
array1_4` M 0
array 1 _7` M 0
array 1 _8` M 0
arrayl_9` M 0
array 1 _:` M 0
93
rog+9.c more array boundaries
?D note that $alues are assigned beyond declared
space D?
ain 5 6
A
int array 1_4`H
int iH
/* $alid initiali(ation D ?
arrayl_0` M 22H
arrayl_1`Ml8H
array1_2` M 2:H
arrayl_2` M 2H
arrayl_3` M !8H
?D these $alues are stored but canCt be
addressed D?
?D you can read fro the but you canCt
#rite to the D?
?D because they are not part of your data
space D ?
) M array 1 _4` M 23H
array1_7` M :939H
array'RDS ? B,8.E9H
for 5 i M 0H i IM 8H iVV 6
printf5Farrayl_Ni` M Ni
KnF,i,arrayl_i`6H
/
*sa
ple
output
array
1 _0`
M 22
arrayl
_l` M
18
array
1 _2`
M 2:
array
1 _2`
M 2
array1
_3` M!
8
arrayl
_4` M
94
0
arrayl
_7` M
0
array1
_8` M
0
D?
Z;-/T%L<Y .ill ) be set to 23 or 0Y
>ns#erG 23, e$en though array 1 _4` is not setG
<LT-' on soe systes 5&L/ for e)aple6 arrayl_4` ay ha$e been set to 23.
*-.>U-' inde)ing outside array bounds can be $ery dangerous and causes any
headaches for both ne# and seasoned C prograers. /oeties this is refered to
as ha$ing a F#ay#ard pointerF eaning storing or retrie$ing data fro #ho!kno#s!
#here. These can be particularly nasty bugs to debug. %n this e)aple storing at
arrayl_4` #ill 0uite possibly o$er#rite the $ariable i. Ln any systes storing a
$alue at arrayl_!l` #ill cause an addressing e)ception 5ainfrae6.
95
rog+<.c bo!ling scores) array rocessing
?D progra to calculate the a$erage of a set of bo#ling
scores D?
?D only count scores o$er 100 for personCs a$erage D?
?D print out the high and lo# scores, all scores, scores used in
a$erageD?
?D print out a$erage D?
@define W>=Q/CLU-/ 100
@define W>=Q/CLU- 200
@define W%<Q/CLU- 0
@define W%<QR->1;-Q/CLU- 100
ain 5 6
A
/* scores #ill be the array of scores entered D ?
int scores_W>=Q/CLU-/`H
?D nuscores is the count of ho# any scores they #ant to enter D?
int nuscores, i, scoreH
/* scoresQtoQcount are used to keep track of ho# any $alid scores there
#ere D?
int ra# QscoresQtoQcount M 0H
int leagueQscoresQtoQcount M 0H
int scoreQtotal M 0H
?D the a$erages are floats because % #ant floating point
accuracy */
float ra#Qa$erageH
float leagueQa$erageH
?D initiali(e current high and lo#
score D?
int high M 0H
int lo# M W>=Q/CLU-H
96
?D find out ho# any scores the person #ill be
entering D?
printf5F"o# any scores #ill you be enteringYF6H
scanf5FNiF, [nuscores6H
printf5CCKnOou entered Nd scores KnF,nuscores6H
if 5 nuscores J
W>=Q/CLU-/6
A
printf5FC><<LT T>K- T">T W><O, Ni is
a)KnF,W<C/CLU-/6H
e)it5!16H
B
B
?D for each of the scores re0uested, get the score D?
for 5i M 1H i IM nuscoresH iVV 6
A
printf5,CKn-nter score @Ni' F,i6H
sc anf5F N iF ,[score 6H
printf5FOou entered NiKnF,score6H
?D if scores #as less than 100 D ?
?D donCt count in a$erage D?
if 5 5 score I W%<Q/CLU- 6 ]] 5 scoreJ W>=Q/CLU-66
printf5F%possible score KnF6H
else
A
?D insert score into array D?
scores _ra# QscoresQtoQcount` M scoreH
?D update the total of all scores D?
scoreQtotal M scoreQtotal V scoreH
ra# QscoresatoQcountVVH
97
if 5 score J high6
high M scoreH
if 5 score I lo#6
lo# M scoreH
B ?D end for loop D?
if 5 ra# QscoresQtoQcount J 0 6
A
ra# Qa$erage M scoreQtotal?ra# QscoresQtoQcountH
printf5CCKnUa# a$erage M N.2fKnF, ra#Qa$erage6H
printf5F"igh score #as Ni KnF,high6H
printf5FRo# score #as Ni KnF,lo#6H
B
else
printf5F<o $alid scores enteredKnF6H

scoreQtotal M 0H
leagueQscoresQtoQcount M 0H
printf5CCKnKnR%/T LP R->1;- /CLU-/ ;/-& %< >S-U>1-KnF6H
for 5 iM 0H i I ra# QscoresQtoQcountH iCC 6
A
if 5scores_i` J W%<QR->1;-Q/CLU- 6
A
printf5CCKtNiKnCC ,scores _i`6H
leagueQscoresQtoQcountVVH
scoreQtotal C? scores_i`H
if 5 leagueQscoresQtoQcount J 0 6
A
leagueQa$erage M scoreQtotal ? leagueQscoresQtoQcountH
printf5FKnReague a$erage M N.2fKnF,leagueQa$erage6H
else
leagueQa$erage M 100H
B ?Dend ain D?
98
"o# any scores #ill you be enteringY
Oou entered 10 scores
-nter score @1' Oou entered 100
-nter score @2' Oou entered 200
-nter score @2' Oou entered 200
-nter score @3' Oou entered ! 2
%possible score
-nter score @4' Oou entered 40
-nter score @7' Oou entered 100
-nter score @8' Oou entered 200
-nter score @9' Oou entered 200
-nter score @:' Oou entered 8:
-nter score @10' Oou entered 308
%possible score
Ua# a$erage M 177.12
"igh score #as 200
Ro# score #as 40
R%/T LP R->1;- /CLU-/ ;/-& %< >S-U>1-
200
200
200
200
Reague a$erage M 240.00

99
rog+D.c character arrays
Ls address of s
s value of s
>s value stored at address stored in s
?D progra to illustrate initiali(ing a character array D?
?D #ill be initiali(ed three different #ays D?
?D null terinator is added to #ord1 D?
?D si(e of #ordl #ould be deterined at initiali(ation tieD?
int i,tH
char #ordl_` M
AFabcdefghijFBH
ain 5 6
A
char #ord2_` M AF12234789:012234789:FBH
?D null terinator is not added to #ord2 D?
?D si(e of #ord2 #ould be deterined at
initiali(ation tieD?
char #ord2_` M A C"C, CeC, ClC, ClC, CLC, CGC BH
char #ord3_` M AF>*C&-P1"%JKRW<LPFBH
?D null terinator is added to s si(e of s is si(e of pointer to char D ?
?D space for s is allocated at initiali(ation tie since the thing in double
0uotes ust be stored soe#here The space for character string is
ade on stack D?
char D s M AFstill yet another #ay, pointer to characterFBH
for 5 i M 0H i I 20H iVV 6
printf5FNc N)KnF, #ord1_i`,
#ord1_i` 6H
printf5CCKnCC6H
?D this is a really terrible thing to do, calling a subroutine o$er and o$er
each tie it is called it returns the sae $alue. D?
for 5 i M 0H i I si(eof5#ord16H iVV 6
100
printf5FNcF, #ord 1 _i`6H
printf5CCKnCC6H
printf5FNsF,#ord16H ?D this is
uch better D?
printf5CCKnCC6 H
for 5i M 0H i I 20H iVV 6
printf5FNc N)KnF,
#ord2_i`,#ord2_i`6H
printf5CCKnCC6H
t M si(eof5#ord26H
printf5Fsi(eof #ord2
is Ni KnF,t6H
for 5 i M 0H i I tH iVV 6
printf5FNcF, #ord2_i`6H
printf5CCKnCC6H
printf5FNsF, #ord26H
printf5CCKnCC6H
for 5 i M 0H i I 20H iVV 6
printf5FNcF,s_i`6H
printf5CCKnCC6H
for 5 i M 0H i I si(eof5s6H iVV 6
printf5FNcF,s_i`6H
printf5CKnF6H
for 5 i M 0H i I si(eof5Ds6H iVV 6
printf5FNcF ,s_i`6H
printf5CCKnCC6H
printf5FNsF,s6H
printf5+KnF6 H
101
B
102
%utut QouIll See
a 71
b72
c 72
d73
e 74
f77
g 78
h 79
i 7:
j 7a
0
1 21
2 22
2 22
3 23
4 24
7 27
8 28
9 29
: 2:
abcdefghij
abcdefghij
" 39
e 74
l7 c
1 7c
o 7f
G 21
1 21
2 22
2 22
3 23
4 24
7 27
8 28
9 29
: 2:
0 20
1 21
2 22
2 22
3 23
si(eof #ord2 is 7
"elloG
"elloG 12234789:012234789:
still yet another #a
stil
s
still yet another #ay, pointer to character

103
/7ercise E
/* #rite a progra to input a list of nubers into an array D?
/* print the array eleents for#ards and back#ards D?
/*
.rite a progra to input a list of nubers into an array
Pind the largest eleent of the array
Pind the sallest eleent of the array
Put the sallest $alue at position 0 in the array and
put the $alue that #as at position 0 #here the
sallest $alue used to be
Print out the updated array D?

104
Solution for /7ercise E
int ain 5 6
A
int array_l0` M A1, 2,4, !2, !7, 8, 3, :, 12,:22 BH
int i, hipos, lopos, tepH
hipos M lopos M 0H
printf5FLriginal >rray KnF6H
for 5 i M 0H i I 10H iVV 6
A
printf5F>rray position Ni $alue Ni
CnF,i,array_i`6H
if 5 array_i` J array_hipos` 6
hipos M iH
if 5 array_i` I array_lopos` 6
lopos M iH
B
printfC5+Rargest $alue is Ni at inde) Ni KnF,array_hipos`,hipos6H
printf5F/allest $alue is Ni at inde) Ni KnF,array_10pos`,lopos6H
?D s#itch lo#est $alue to position 0, o$ing position 0 to #here lo#est cae
fro D?
tep M array_lopos`H
array_lopos` M array_0`H
array_0` M tepH
printf5F;pdated
>rray KnF6H
for 5 i M 0H i I 10H
iVV 6
printf5F>rray position Ni $alue Ni
CnF,i,array_i`6H
B ?D end ain D?
105
/7ercise 'F
?D #rite a progra to sort an array of
nubers D?
?D use the array 1 24 !2 !78 3: 12:22
D?
?D sort the array fro lo# to high D?
?D print out the original and the sorted array D?
?D &L <LT use a second array to sort the
nubers into,
you ha$e to sort the in the array
they are in D?
<ote' you ay ipleent the sort ho#e$er you are
cofortable
The follo#ing is pseudocode for the so!called
bubble sort'
5>//;W-/ T-UL *>/-& %<&-=%<16
PLU %<&-=1 %/ 0 TL <;W*-U LP -R-W-<T/ %<
>UU>O!1
5fro first to second to last6
PLU %<&-=2 %/ %<&-=1 V1 To <;W*-U LP -R-W-<T/ %<
>UU>O
5fro second to last6
%P -R-W-<T >T %<&-= 1 %/ 1U->T-U T">< T"- -R-W-<T
>T %<&-=2
/.>P -R-W-<T/ >T %<&-= 1 ><& %<&-=2
-<&%P
-<&PLU
-<&PLU
106
Solution for /7ercise 'F
ain 5 6
A
int array_l0` M A 1,2,4, !2, !7, 8, 3, :, 12,:22 BH
int tepH
int i,jH
printf5FLriginal unsorted array KnF6H
for 5 i M 0H i I 10H iVV 6
A
printf5FNiKtNiKnF ,i,array_i`6H
B
for 5 i M 0H i I :H i CC 6
A
for 5j M i V 1H j I 10H jVV 6
A
if 5 array_j` I array _i` 6
A
tep M arrayjj`H
arrayjj` M array_i`H
array_i` M tepH
B ?D end if D?
B ?D end for j loop D?
B ?D end for i loop D?
printf5CCKnKn/orted >rrayKnF6H
for 5 i M 0H i I 10H iVV 6
printf5FNiKtNiKnF ,i,arra y_i`6H
B
107
6unction definition and rototyes
.hen #e @include Istdio.hJ #hat happensY The file stdio.h gets ibeddeed into our
progra.
The file stdio.h contains the prototypes for functions like printf 5and other stuff6.
> prototype is a declaration of #hat the interface for a function looks like. Por
printf it is'
unsigned printf5char D, ... 6H
This indicates that the printf function returns an unsigned int, and re0uires at least
one arguent, #hich ust be a character string.
The copiler FreebersF the protytype after it FseesF it and #ill check our code to
$erify that
#e are using it correctly. %f #e fail to pass printf at least a character string #e #ill get
a copiler
error. %f #e assign printfCs return $alue to a non!unsigned, #e #ill get at least a
copiler #arning.
.hen #e #rite our o#n functions #e #ill #ant to use prototypes to allo# the
copiler to pro$ide the sae type of checking as #ith printf.
%f the copiler does not see a prototype for a function but sees it being used it #ill
issue a #arning and there #ill be no checking perfored. This is deeed to be poor
prograing practice. .e should al#ays use prototypes to allo# the copiler to
$erify our interfaces as #ell as our usage. > prototype is also kno#n as a function
declaration. To FdeclareF in C eans to state that soething e)ists 5usually
soe#here else6.
The actual code for a function is called the function definition. To FdefineF in C
eans to create
code or storage.
Just as a note, any other languages support siilar concepts as
prototypes.
108
rog+E.c elementary function declaration and usage
/* definition of subroutine D?
?D should be defined before
it is used D?
?D type of $alue it returns
nae
type of arguents it e)pects D?
?D progra e)ecution does not start here D ?
?D this code is only e)ecuted #hen the subrl routine
is called D?
$oid subr15$oid6 ?D this is called the function
header D?
A
printf5F%n
subroutineKnF
6H
returnH
B
/* this is #here progra
e)ecution starts D?
ain5 6
A
?D declaring that ain #ill call subr1 D?
?D function prototype header needs to go before first e)ecutable
stateent D?
$oid subr15$oid6H
printf5F%n ain
routine KnF6H
subr15 6'
printf5F*ack in ain routine KnF6H
B
109
?D saple output D?
%n ain routine
%n subroutine
*ack in ain routine
%f #e hadnCt placed the prototype for subrl in ain, the copiler by default #oud
assue that the function header correctly stated the return and paraeter types. This
only #orks because the copiler CseesC the function definition in the sae file as it is
used. >gain this is deeed poor style. %f the definition for subrl #as after ain in the
source file, #e ust place the prototype for subrl before itCs use in ain. Rea$ing out
the prototype #ouldnCt #ork as the copiler #ould not see the header line before it
#as used.
110
rog,F.c calling subroutines
/* definition of subroutine D?
?D should be defined before it is used D ?
/* type of $alue it returns
nae
type of arguents it e)pects D?
?D progra e)ecution does not start here D?
?D this code is only e)ecuted #hen the subrl routine is called D?
void subr':void;
A
printf5F%n subroutineKnF6H
returnH
B
/* this is #here progra e)ecution starts D?
ain5 6
A
?D declaring that ain #ill call subrlL D?
void subr':void;H
printf5F%n ain routine KnF6H
subr': ;H
subr15 6H
subrl 5 6H
printf5F*ack in ain routine KnF6H
B
111
rog,'.c assing constants to subroutines
/* definition of subroutine, should be defined before it is used D?
?D type of $alue it returns
nae
type of arguents it e)pects D?
?D progra e)ecution does not start here D?
?D this code is only e)ecuted #hen the subrl routine is called D?
$oid subr15int n6 A
/* n is a local $ariable 5arguent6 #hoCs purpose is to D?
?D recei$e a copy of the paraeter passed fro ain routine D?
?D i is a local $ariable it #i11li$e on stack D?
?D it #ill be deallocated #hen routine e)its D?
int iH
for 5 i M 0H i I nH iVV 6
printf5F%n subroutine i M Ni n M Ni KnF,i,n6H
returnH
B
/* this is #here progra e)ecution starts D?
ain5 6
A
?D declaring that ain #ill call subr15 6 D?
$oid subr15int6H
printf5F%n ain routine KnF6H
?D calling subrl, sending 4 by $alue D?
subr1 546H
printf5F*ack in ain routine KnF6H
B
?D saple output D?
%n ain routine
%n subroutine i M 0 n M 4
%n subroutine i M 1 n M 4
%n subroutine i M 2 n M 4
%n subroutine i M 2 n M 4
%n subroutine i M 3 n M 4
*ack in ain routine

112
rog,+.c assing variables to subroutines
?D progra e)ecution does not start here */
/* this code is only e)ecuted #hen the subrl routine is called
*/
$oid subr15int n6
A
?D n is an arguent passed fro ain routine, it is a local
$ariable */
/* i is a local $ariable, it #ill li$e on stack */
/* it #ill be deallocated #hen routine e)its, as #ill n
*/
int iH
?D static $ariable li$es in data area, itCs $alue D?
?D is retained bet#een calls be#are of static $ariables */
?D in general, assue no static area is a$ailable */
?D on soe L?/, static $ariables are shared bet#een all instances of the progra
*/
/* this defeats re!entrancy */
static int j M 0H
for 5 i M 0H i I nH iV
V 6
A
jVVH
printf5F%n subroutine i M Nd j M Nd KnF,i,j6H
B
returnH
/* this is #here progra e)ecution
starts */
ain 5 6
A
int )H
/* declaring that ain #ill call
113
subr15 6 D?
$oid subr15int6H
) M 2H printf5F%n ain routine ) M Ni
KnF,)6H
subr15)6H
printf5FWain routine location 1 ) M Ni KnKnF,)6H
) M 2H printf5F%n ain routine ) M Ni
KnF,)6H
subr15)6H
printf5FWain routine location 2 ) M Ni KnKnF,)6H
) M !3H printf5F%n ain routine ) M Ni
KnF,)6H
subr15)6H
printf5FWain routine location 2 ) M Ni KnKnF,)6H
B
/* -=-UC%/- D?
/* .">T .%RR T"- L;P;T
*- YY */
S%41T5%2 T% /U/RC5S/
%n ain routine ) M 2
%n subroutine i M 0 j M 1
%n subroutine i M 1 j M 2
Wain routine location 1 ) M 2
%n ain routine ) M 2
%n subroutine i M 0 j M 2
%n subroutine i M 1 j M 3
%n subroutine i M 2 j M 4
Wain routine location 2 ) M 2
%n ain routine ) M !3
Wain routine location 2 ) M !3
114
115
rog,,.c subroutines returning values :void key!ord;
?D routine #ill return no $alue, e)pects to recei$e an integer, #ill call integer
n D?
void cube' : int n 6
Aint cubeH ?D local $ariable for subroutine D?
cube M n D n D nH
printf5FCube of Ni is Ni
KnF,n,cube6H
returnH
B
?D routine returns an int, e)pects an integer, #ill call integer
n D?
int cube+ : int n 6
A
int cubeH ?D local $ariable for subroutine D?
cube M n D n D nH
return5cube6H
B
ain5 6
A
/* function prototype headers, not calls to subroutines D?
$oid cubel 5int 6H
int cube2 5 int 6H
?D local $ariables for ain D?
int inputQ$alueH
int returnedQ$alueH
printf5F-nter nuber to calculate cube ofKnF6H
scanf5FNiF ,[inputQ $alue6H
printf5FCalling cubelKnF6H
?D there is no return $alue to catch D?
cubel5input $alue6H
printf5CCKnCalling cube2KnF6H
?D there is a return $alue to catch D?
returnedQ$alue M cube25inputQ$alue6H
printf5Fcube of Ni is Ni KnF,inpuC$alue,returnedQ$alue6H
B
116
# 6e! Vords #bout (ultiB(odule Programs
%n the CnoralC prograing #orld, #e typically #ill not ha$e just 1 giant
source file. %t akes ore sense to ha$e a file containing the ain function, and one
or ore other files that contain functions typically grouped by functionality.
Consider the three files test1.c funs1.c and funs2.c
test1.c funs1.c funs2.c
$oid ain 5 6 $oid f1 5 6 $oid f2 5 6
A A A
f15 6H f2 5 6H soe code
f2 5 6H B B
B $oid f2 5 6
A
soe code
B
/ince ain calls nand f2 it should ha$e the prototypes for these functions
a$ailable to it at copile tie. Rike#ise, since fl calls f2, it should ha$e the prototype
for f2 a$ailable to it. .e could try to reeber to do this. "o#e$er, there is an easier
#ayG
117
.e can #rite our o#n header files 5one or ore6'
yproto.h
$oid fl 5$oid6H
$oid f25$oid6H
$oid f25$oid6H
Then #e can load the all by using @include +yprot.h.,
test1.c funs1.c funs2.c
@include +yproto.h, @include +yproto.h, @incluee +yproto.h,
$oid ain 5 6 $oid f1 5 6 $oid f2 5 6
A A A
f15 6H f2 5 6H soe code
f2 5 6H B B
B $oid f2 5 6
A
soe code
B
@ including the prototype into funs2.c is iportantG
-$en though function f2 does not call f1 or f2, the copiler #ill see the prototype for
function f2. The copiler #ill $erify that the prototype atches the actual code for the
function
f2. %f f2 #ere not coded #ith the correct nuber and type of paraeters, or #ith the
#rong return type 5$ersus the prototype6 the copiler #ould issue a #arning.
This is yet another check that our proised interface 5prototype6 atches the
actual code
#e #rote and also ho# #e #ill use it.
118
rog,9.c multile files being comiled together
?D ain routine located in one file D ?
/* subrl is located in another file func24a.c D?
?D subr2 is located in another file func24b.c D?
?D copile together $ia
acc !o prog24 prog24.c func24a.c func24b.c
D?
?D try acc prog24.c
then try acc prog24.c func24a.c
then try ace func24a.c func24b.c
then try ace !c prog24.c
D?
?D this is #here progra e)ecution starts D?
ain 5 6
A
?D declaring that ain #ill call subrlL D?
$oid subr15int6H
$oid subr25int6H
printf5F%n ain routine KnF6H
subr1546H
printf5FWain routine location 1KnKnF6H
subr2526H
printf5FWain routine location 2KnKnF6H
B

119
func,9a.c
?D progra e)ecution does not start here D?
?D this code is only e)ecuted #hen the subrl routine is called D?
void subr':int n;
A
$oid subr25int6H
?D n is an arguent passed fro ain routine D ?
?D i is a local arguent, it #ill li$e on stack D?
?D it #ill be deallocated #hen routine e)its D?
int iH
for 5 i M 0H i I nH iVV 6
A
printf5F%n subrlKnF6H
subr25 !186H
returnH
B
B
func,9b.c
/* progra e)ecution does not start here D ?
?D this code is only e)ecuted #hen the subrl routine is called D?
void subr+:int n;
A
?D n is an arguent passed fro ain routine D ?
?D i is a local arguent, it #ill li$e on stack D?
?D it #ill be deallocated #hen routine e)its D?
printf5F%n subr2KnF6H
printf5F/0uare of Ni is Ni KnF,n, nDn6H
returnH
B
120
valref.c Call $y 3alue vs. Call by Reference
?D deonstrate call by $alue and call by reference D?
$oid $al15int )6 ?D ansi function header
D?
A
)VVH ?D add one to ) D?
printf5F%n $all ) M Ni KnF,)6H ?D print out its $alue D?
returnH ?D return to calling
routine D?
B
$oid refl 5intD )6 ?D ansi function header D?
A
D) M D) V 1H ?D add one to $alue stored at address stored in ) D?
printf5F%n refl ) M Ni KnF,D)6H?D print it out D?
returnH
B
ain5 6
A
int i M 4H
printf5F%n ain i M Ni KnF,i6H
$al1 5i6H ?D pass $alue of i to $al1 D?
printf5F%n ain i M Ni KnF,i6H ?D notice that $al1 did not change i D?
printf5F%n ain i M Ni KnF,i6H
ref15[i6H ?D pass address of i to ref1 D?
printf5F%n ain i M Ni KnF,i6H ?D notice that ref1 changed i D?
B
%n ain i M 4
%n $al1 ) M 7
%n ain i M 4
%n ain i M 4
%n refl1) M 7
121
%n ain i M 7

122
call by value
ain routine stack subroutine
$alues are placed on stack
subroutine cannot FseeF eory of ain routine
subroutine can only FseeF $alues on stack
call by reference
addresses are placed on stack
subroutine can FseeF eory of ain routine through addresses found on stack
123
/7ercise ''
?D P>UT L<- D?
?D #rite a progra to input a nuber D?
/*
Print the nuber in the ain routine.
Pass the nuber to a subroutine by $alue.
"a$e the subroutine print the recei$ed $alue
"a$e the subroutine return t#ice the input $alue.
"a$e the ain routine print the original and the result.
D?
?D P>UT T.L D?
?D #rite a progra to input a nuber D?
?D
Pass the nuber to a subroutine by reference.
"a$e the subroutine ultiply the $alue by three.
"a$e the ain routine print the original $alue and the result.
D?
124
Solution for /7ercise ''
ain5 6
A
int iH
intjH
int t#ice5int6H
$oid threeQties5int D6H
printf5F-nter nuber KnF6H
scanf5FNiF,[i6H
printf5FOou entered Ni KnF,i6H
j M t#ice5i6H
printf5FT#ice Ni is NiKnF,i,j6H
printf5+three ties Ni is F,i6H
threeQties5[i6H
printf5FNi KnF,i6H
B
int t#ice5 int n 6
A
return 5n D 2 6H
B
$oid threeQties5 int D nptr 6
A
Dnptr DM 2H
returnH
B
125
rog,<.c
main : ;
A
/* scores_0` is the (eroeth entry in scores D?
/* [scores_0` is the address of the (eroeth entry D?
?D scores all by itself, is seantically e0ui$alent to [scores_0` D?
int scores_4`, iH
int deterine 1 5 int $alues_4` 6H
int deterine25 int D 6H
?D useful to use data file prog27.dat D?
printf5FPlease enter fi$e scores KnF6H
for 5 i M 0H i I 4H iVV 6
A
printf5F/core Ni' F,i6H
scanf5FNiF,[scores_i`6H
printf5CCKt Ni KnF,scores_i`6
if 5 deterine1 5scores6 MM 1 6
printf5F22 #as in array KnF6H
else
printf5F22 #as not in array KnF6H
if 5 deterine25scores6 MM 1 6
printf5F40 #as in array KnF6H
else
printf5F40 #as not in array KnF6H
if 5 deterine25scores6 MM 16
printf5F40 #as in array KnF6H
else
printf5F40 #as not in array KnF6H
B
126
B
rog,<.c assing arrays to subroutines
/* #rite functions to find out if a $alue is in an
array D? @define /;CC-// 1
@define P>%R;U- 2
?D function returns an integer
D?
?D function nae is
deterine D?
?D function accepts array of ten integers D?
?D #hat it is really accepting is a pointer to the first eleent of the array D?
int determine' : int valuesR9S 6 A
int iH
for 5 i M 0H i I 4H iVV 6 A
if 5 $alues_i` MM 22 6
return5/;CC-//6H
B
return5P>%R;
U-H
int determine+ : int D 7; A
int iH
for 5 i M 0H i I 4H iVV 6 A
if 5 )_i` MM 40 6
retu5/;CC-// 6H
B
return5P>%R;U-6H
B
int determine, : int> ) 6 A
int iH
for 5i M 0H i I 4H iVV 6 A
if 5 D5)Vi6 MM 40 6
return5/;CC-//6H
127
B
retu5P>%R;U-6H
B
128
rog,D.c assing ointers and arrays to subroutines
/* function to subtract e$ery eleent by the eleent after
itD ?
?D lea$e the last eleent alone D?
?D this function deonstrates that array eleents can
be D?
?D anipulated by the function D?
?D arrayptr is a pointer to an integer D?
?D %T ">PP-</ TL *- T"- P%U/T -R-W-<T LP > T-< -R-W-<T
>UU>O D?
$oid subtracts5 int \ array Qptr 6
A
int iH
for 5i M 0H i I :H iVV 6
array Qptr_i` M array Qptr_i` ! array Qptr_iV 1`H
B
ain 5 6
A
int scores_l0`, iH
$oid subtracts5 int D 6H
/* useful to use data file prog27.dat D?
printf5FPlease enter ten scores KnF6H
for 5 i M 0H i I 10H iVV 6
A
printf5F/core Ni' F,i6H
scanf5FNiF,[scores_i`6H
printf5CCKt Ni KnF,scores_i`6H
B
printf5F>rray before function call KnF6H
for 5 i M 0H i I 10H iVV 6
printf5Fscores_Ni`KtNiKnF,i,scores_i`6H
subtracts5 scores 6H
printf5F>rray after function call KnF6H
for 5 i M 0H i I 10H iVV 6
printf5Fscores _Ni`KtNiKnF,i,scores _i`6H
B
129
rog,8.c sorting an array of integers
/* function to sort an array of integers into ascending order D?
/* proble is, #e canCt hard code the si(e of the array into the function D?
?D first solution is to pass the si(e of the array into function D?
/* function returns nothing D?
/* its nae is sort D ?
/* it e)pects an integer array, doesnCt kno# ho# big it #ill be yet D?
?D n #ill be an integer specifying the si(e of the array D?
$oid sort 5 int Da, int n6
A
int i,j,tepH
for 5 i M 0H i I n !1H iVV 6
A
for 5j M i V 1H j I nH jVV 6
A
if 5 a_i` J a_j` 6
A
tep M a_i`H
a_i` M a_j`H
a_j` M tepH
B ?D end if D?
B ?D end for j loop D?
B ?D end for i loop D?
B /* end sort function D?

@define W>=Q>UU>O 100
?D ain routine to call sort and display results D?
ain 5 6
A
int iH
int nuQeleentsH
?D donCt kno# ho# big array needs to be D?
int array_W>=Q>UU>O` H
130
$oid sort5 int D, int6H
?D get and error check nuber of eleents D?
printf5F"o# any eleents in arrayCGKnF6H
scanf5FNiF ,[nuQeleents6H
if 5nuQeleents I 0 ]] nuQeleents J W>=Q>UU>O6
A
printf5F%possible nuber of eleentsKnF6H
e)it5!16H
B
?D ha$e a good nuber of eleents, continue D?
for 5 i M 0H i I nuQeleentsH iVV 6
A
printf5F-nter $alue for eleent Ni KnF,i6H
scanf5F Ni F,[array_i`6H
B
printf5FThe array before the sort is'KnF6H
for 5 i M 0H i I nuQeleentsH iVV 6
printf5FNi F,array _i`6H
printf5FKnKnF6H
?D call the subroutine to do the sort D?
?D pass the address of the array and nuber of eleents D?
sort5array, nuQeleents6H
printf5FThe array after the sort is' KnF6H
for 5 i M 0H i I nuQeleentsH iVV 6
printf5FNi F,array_i`6H
printf5CCKnKnCC6 H
B

131
"o# any eleents in arrayY
4
-nter $alue for eleent 0
1
-nter $alue for eleent 1
3
-nter $alue for eleent 2
2
-nter $alue for eleent 2
2
-nter $alue for eleent 3
:
The array before the sort is'
1 3 2 2 :
The array after the sort is'
1 2 2 3 :

132
sortste.c
$oid sortstep5int D, int, int6H
ain 5 6
A
int i,jH
int array_2`_3` M
A
A 0, 1,2,2 B,
A !1, !2, !2, !3 B,
A 10, 20, 20, 30 B
BH
printf5Farray before call is KnF6H
for 5 i M 0H i I 2H iVV 6
A
for 5j M 0H j I 3H jVV 6
printf5FN2i F,array_i`_j`6H
printf5CCKnCC6H
B
sortstep 5[array _0` _0`,2,36H
printf5Farray after call is KnF6H
for 5 i M 0H i I 2H iVV 6 A
for 5 j M 0H j I 3H jVV 6
printf5FN2i F,array_i` _j`6H
printf5CCKnCC6H
B
sortstep5[array_1` _0`,3, 16H
printf5Farray after call is KnF6H
for 5 i M 0H i I 2H iVV 6
A
for 5j M 0H j I 3H jVV 6
printf5FN2i F,array_i`_j`6H
printf5CCKnCC6H
133
B
B

$oid sortstep 5 int Da, int n, int stepsi(e6
A
int i, j, tepH
int iinde), jinde)H
for 5 i M 0H i I n !1H iVV 6
A
iinde) M i D stepsi(eH
for 5j M i V 1H j I nH jVV 6
A
jinde) M j D stepsi(eH
if 5 a_iinde)` J a_ jinde) ` 6
A
tep M a_iinde)`H
a_iinde)` M ajjinde)`H
aljinde)` M tepH
B ?D end if D?
B ?D end for j loop D?
B ?D end for i loop D?
B ?D end sort function D?
array before call is
0 1 2 2
!1 !2 !2 !3
10 20 20 30
array after call is
!1 1 2 2
0 !2 !2 !3
10 20 20 30
array after call is
!1 1 2 2
!3 !2 !2 0
10 20 20 30
134
rog,E.c rogram to introduce
t!o dimensional arrays
ain5 6
A
?D rc cola D?
?D ro#s, coluns D?
/* 2 ro#s, three coluns D?
?D C T"%<K/ LP />WPR-QW>TU%= >/ >< >UU>O .%T" T.L -<TU%-/
->C" -<TUO ">PP-</ TL *- >< >UU>O LP T"U--
-<TU%-/ D?
?D sapleQatri)_0` is an array, sapleQatri)_0`_0` is an
integer D?
int sapleQatri)_2` _2` M
A
A 1,2
,2 B,
A 2,4
,: B
B H
int ro#,colunH
int ro#su, colsuH
?D print original atri) D?
printf5FLriginal atri)
KnF6H
for 5 ro# M 0H ro# I 2H
ro#VV6
A
for 5colun M 0H colun I 2H colunVV 6
printf5FN2iF ,sapleQatri)_ro#`_colun`6H
printf5CCKnCC6 H
B
printf5CCKnKnW>TU%= .%T" UL./;W/ ><& CLR;W<
/;W/KnF6H
?D add up ro#s and coluns, produce report D?
printf5CCKtKt ro#suKnF6H
for 5 ro# M 0H ro# I 2H ro# VV 6
A
ro#su
M0H
printf5F
KtF6H
for 5 colun M 0H colun I 2H colunVV 6
A
printf5FN2iF ,sapleQatri) _ro# ` _colun`6H
ro#su VM sapleQatri)_ro#`_colun`H
B
printf5F N3iKnF,ro#su6H
B
135
printf5CC
KnCC6H
printf5FcolsuKtF6H
for 5 colun M 0H colun I 2H colunVV 6
A
colsu M 0H
for 5 ro# M 0H ro# I 2H ro#VV 6
colsu C? sapleQatri)_ro#` _colun`H
printf5FN2iF ,colsu6H
B
printf5CKnKnF6H
B
?D saple output D?
?D
Lriginal atri)
1 2 2
2 4 :
W>TU%= .%T" UL./;W/ ><& CLR;W< /;W/
ro#su
1 2 2 7
2 4 : 18
colsu 3 8 12
D?

136
Sending T!o Dimensional #rray To Subroutine
t!odim.c
ain5 6
A
?D function prototype header ust supply ro# and colun
inforation
if #e #ish to use ultiple sets of _` in subroutine D?
$oid s15 int a_2`_2` 6H
?D ) all by itself is the address of the 1st array D ?
int )_2`_2` M ?D ) is an array #ith t#o eleents, each eleent is itself an array
D?
A
A1,2,2B,
A 3,4,7B
BH
printf5F >> KnF6H
s15)6H ?D call using just nae of array, resol$es to [)_0`, an array D?
printf5F**KnF6H
sl5[)_0`6H ?D call using address of first +array of arrays D?
printf5FCCKnF6H
sl5[)_0`_0`6H ?D call using address of first eleent of first arrayD
?D copiler #arning b?c this is address of an integer, not an
array D?
B
$oid s15int )_2`_2` 6
?D con$erted to intDD D?
A
int i,jH
for 5 i M 0H i I 2H iVV 6
A
for 5j M 0H j
I 2H jVV 6
A
?D function declaration infors us of ho# any ro#s and
coluns D?
printf5FNi F,)_i` ;` 6H
B
p
ri
n
tf
5
FK
n
F
6H
137
B
B
138
Solution for /7ercise ',
?D function returns nothing D ?
?D its nae is sort D ?
?D it e)pects an integer array, doesnCt kno# ho# big it #ill be
yet D?
?D n #ill be an integer specifying the si(e of the array D?
$oid sort 5 int a_ `, int n6
A
int i,j,tepH
for 5i M 0H i I nH iV
V 6
A
for 5j M i V 1H j I nH jVV 6
A
if 5 a_i` J a_j` 6
A
tep M
a_i`H
a_i` M
a_j`H
a_j` M
tepH
B ?D end
if D?
B ?D end for j
loop D
B ?D end for i loop D?
B ?D end sort
function D
139
@define UL./ 2
@define CLR/ 3
ain5 6
A
int inputQarray_UL./`_CLR/`H
int tepQarray_UL./`_CLR/`H
int finalQarray_UL./`_CLR/`H
int ro#_CLR/`, col_UL./`H
$oid sort 5 int a_ `, int n 6H
int i,jH
/* get and print original array D?
printf5CCKnCC6H
for 5i M 0H i I UL./H iVV 6
A
for 5j M 0H j I CLR/H jVV6
A
scanf5FNiF,[inputQarray_i`_j`6H
printf5FN2iF,inputQarray_i`_j66H
B
printf5CCKnCC6H
B
for 5 i M 0H i I UL./H iVV 6 ?D sort by ro# D?
A
for 5j M 0H j I CLR/H jVV6
ro#_j` M inputQarray_i`_j`'
sort5ro#,CLR/6H
for 5j M 0H j I CLR/H jVV 6
tepQarray_i`_j` M ro#_j`H
B
printf5CKnKn>Pf-U /LUT%<1 UL./KnF6H /* print array D?
for 5 i M 0H i I UL./H iVV 6
A
140
for 5j M 0H j I CLR/H jVV 6
printf5FN2iF ,tep
Qarray_i` u`6H
printf5CKnF6H
B
for 5j M 0H j I CLR/H jVV 6 ?D sort by colun D?
A
for 5 i M 0H i I UL./H iVV 6
col_i` M tepQarray_i`_j`H
sort5col,UL./6H
for 5 i M 0H i I UL./H iVV 6
finalQarray_i`_j` M col_i`H
B
printf5CCKnKn>PT-U /LUT%<1 CLR/KnF6H ?D print array D?
for 5 i M 0H i I UL./H iVV 6
A
for 5j M 0H j I CLR/H jVV 6
printf5FN2iF ,finalQarray_i`_j`6'
printfC5+KnF6'
B
printf5CKnF6H
B ?D end ain D?
samle outut
1 2 2 14
2 9 0 2
: 3 !2 12
>PT-U /LUT%<1 UL./
1 2 2 14
0 2 2 9
!2 3 : 12
>PT-U /LUT%<1 CLR/
!2 2 2 9
0 2 2 12
1 3 : 14
141
(ore #rray Synta7 L Subroutines
testarrays.c
The basic proble #hen counicating array inforation to a subroutine is ho#
any ro#s
and ho# any coluns, 5 or ho# any entries per diension6 the array has. *asic
pointer synta) only pro$ides the address of the first eleent. This is fine if #e #ish to
only tra$erse the
eory allocated for the array, ho#e$er, if #e #ish to tra$erse it using the ro# and
colun layout #e ha$e specified #hen the array #as created, #e need to pro$ide soe
ro# colun inforation to the subroutine. >s a rule, if there are < diensions in the
array you need to pro$ide at least <!1 pieces of diension inforation, the coputer
can figure out the last diension. "o#e$er, to be rigorous, #hy not pro$ide as uch
as possible, all < if you kno# it. There are applications #hen you #onCt kno# the last
diension inforation.
$oid
s15int D
),int n6
A
int iH
for 5 i M 0H i I nH iVV 6
printf5FN4iF, )_i`6H
printf5CCKnCC6H
B
$o
id
s2
5in
t
)6
A
142
printf5FL)N)F,)6H
printf5CCKnCC6H
B
143
ain 5 6
A
$oid sl5int D,int 6H
$oid s25int6H
int one_4`H
int t#o_2`_3`H t#o_0`_0` M 0H
t#o_0`_1` M 1
t#o_0`_2` M 2H
t#o_0`_2` M 2H

t#o_1`_0` M 10H
t#o_1`_1` M 11H
t#o_1`_2` M 12H
t#o_1`_2` M 12H
t#o_2`_0` M 100H
t#o_2`_1` M 101H
t#o_2`_2` M 102H
t#o_2`_2` M 102H
one_0` M 0H
one_l` M 1H
one_2` M 2H
one_2` M 2H
printf5FP%U/T PU%<TKnF6H
sl5one,/6H ?D array nae by itself is pointer D?
sl5[one_2`,26H ?D subscripted eleent needs [ D?
s15one V 2,26H ?D subscripted eleent needs [ D?
@if 0
sl5one_2`,26H ?D this #ould be run tie error, subscripted eleent needs [ D?
@endif
144
s25one6H ?D array nae by itself is pointer, routine e)pecting int, prints it as int
D?
s25one_2`6H ?D subscripted eleent is a $alue, routine e)pecting $alue, okay
D?
printf5F/-CL<& PU%<TKnF6H
sl5t#o,126H ?D nae of array by itself is pointer D?
sl5t#o_0`,36H ?D nae of array by itself is pointer, t#o_0` is nae of an array
because t#o is an array of three eleents,
of #hich each eleent is itself an array D?
sl5t#o_1`,36H ?D nae of array by itself is pointer D?
sl5t#o_2`,36H ?D nae of array by itself is pointer D?
@if 0
sl5t#o_0`_0`,126H ?D subscripted eleent is $alue,
routine e)pecting address, core
dup D?
@endif
sl5[t#o_0`_0`,126H ?D subscripted eleent needs [ D?
s25t#o6H
s25t#o_0`6H
s25t#o_1`6H
s25t#o_2`6H
s25 t#o _0` _0`6H
s25t#o_1`_0`6H
s25t#o_2`_0`6H
s25[t#o_0`6H
145
/>WPR- L;TP;T
P%U/T PU%<T
0 1 2 2 3
2 2 3
L)f8fffb23
L)2
/-CL<& PU%<T
0 1 2 2 10 11 12 12 100 101 102 102
0 1 2 2
10 11 12 12
100 101 102 102
0 1 2 2 10 11 12 12 100 101 102 102
L)f8fffb03
L)f8fffb03
L)f8fffb13
L)f8fffb23
L)L
L)a
L)73
0)f8fffb03
146
Qet /ven (ore #rray Synta7 L Subroutines
test&arrays'.c
$oid s 1 5int D ),int n6
A
?D #ill access as any as you say starting #here you say D?
int iH
for 5 i M 0H i I nH iVV 6
printf5FN4iF ,)_i`6H
printf5CCKnCC6H
B
$oid s25int D ), int ro#s, int cols6
A
?D #ants to use ultiple s0uare brackets, needs diension info D?
int i,jH
for 5 i M 0H i I ro#sH iVV 6
A
for 5 j M 0H j I colsH jVV 6
A
@if 0
?D this #ill be a copiler error D?
?D routine does not ha$e info on ro#,colun
layout of eory associated #ith ) D?
printf5FN3i F,) _i`_j`6H
@endif
B
B
B
147
$oid s25int )_2`_3`,int ro#s,int cols 6
A
?D #ants to use ultiple s0uare brackets, needs diension info D?
int i,jH
for 5 i M 0H i I ro#sH iVV 6
A
for 5j M 0H j I colsH jVV 6
A
?D this #ill be a copiler error D ?
?D routine does not ha$e info on ro#,colun
layout of eory associated #ith ) D?
printf5FN3i F,)_i` _j`6H
B
B
B

148
main : ;
A
$oid s 1 5int D ,int 6H
$oid s25int D ,int,int 6H
$oid s25int _2`_3`,int,int6H
int one_4`H
int t#o_2`_3`H
t#o_0`_0` M 0H t#o_0`_1` M 1H
t#o_0`_2` M 2H t#o_0`_2` M 2H
t#o_l`_0` M 10H t#o_1`_1` M 11H
t#o_1`_2` M 12H t#o_1`_2` M 12H
t#o_2`_0` M 100H t#o_2`_1` M 101H
t#o_2`_2` M 102H t#o_2`_2` M 102H
one_0` M 0H one_1` M 1H one_2` M 2H
one_2` M 2H one_ 3` M 3H
?D call s 1 sending different lengths D?
printf5CCKncalling s 1 KnF6H
s15one,46H
s15t#o,126H ?D #ill be copiler #arning D?
s 1 5one, 106H
?D try to call s2 , it #onCt #ork D?
printf5CCKncalling s2 KnF6H
s25one,1,46H
s25t#o,2,36H ?D #ill be copiler #arning D?
?D try to call s2 D ?
printf5CCKncalling s2 for oneKnF6H
s25one,1,46H?D #ill be copiler #arning D?
printf5CCKncalling s2 for t#o KnF6H
s25t#o,2,36H
printf5CCKncalling s2 for oneKnF6H
s25one,2,36H?D #ill be copiler #arning D?
printf5CCKnCC6H
B

149
acc testarrays 1.c
Ftestarrays l.cF, line 80' #arning' arguent is incopatible #ith prototype' arg @1
Ftestarrays1.cF, line 87' #arning' arguent is incopatible #ith prototype' arg @1
Ftestarrays1.cF, line 90' #arning' arguent is incopatible #ith prototype' arg @1
Ftestarraysl.cF, line 93' #arning' arguent is incopatible #ith prototype' arg @1
a.out
calling sl
0 1 2 2 3
0 1 2 2 10 11 12 12 100 101 102 102
0 1 2 2 3 0 0 0 0 0
calling s2
calling s2 for one
0 1 2 2 3
calling s2 for t#o
0 1 2 2 10 11 12 12 100 10 1 102 102
calling s2 for one
0 1 2 2 3 0 0 0

150
rog.F.c static) automatic) global key!ords
?D t#o possible copile strings
acc !& CLWPS>U1 prog30.c additional code
acc prog30.c no additional code D?
?D progra to deonstrate static and autoatic
$ariables D?
?D progra to deonstrate global $ariables D?
/* #e already did this once, do it again D?
?D autoatic $ariables go on the stack D?
?D static $ariables go in data area D?
int gH ?D no initial $alue is assigned D?
void subrl : void;
A
int localQ $ariableQisQauto M 1H
static int localQ $ariableQisQstatic M 1H
localQ$ariableQisQautoVVH
localQ $ariableQisQstaticVVH
gVVH
printf5FNi Ni NiKnF, localQ $ariableQisQauto, localQ $ariableQisQstatic,g6H
B
main : ;
A
void subr' 5$oid6H
g M 0H
printf5F1lobal $ariable M Ni KnF,g6H
subr': ;H
gVVH
subr15 6H
@ifdef CLWPS>U1
localQ $ariableQisQautoVVH
localQ $ariableQisQstaticVVH
printf5FNi Ni NiKnF, localQ $ariableQisQauto, localQ $ariableQisQstatic,g6H
printf5FNiKnF,g6H
@endif
B
151
Scoe.c Scoe of 3ariables
int i M 1H ?D global $ariable D?
$oid subr15$oid6H
$oid subr25$oid6H
ain 5 6
A
?D local i o$errides global i D ?
int i M 2H
printf5F>>> i M Ni KnF,i6H
?D call subroutine to test scope D?
subrl5 6H
A
int i M !9022H
printf5CCKt*** i M Ni KnF,i6H
B
?D call subroutine to test scope D?
subr25 6H
B
$oid subrl5 6
A
?D local i o$errides global i D?
int i M 22H
printf5CCKtCCC5 i M Ni KnF, i6H
A
?D interior i o$errides e)terior i D?
int i M !:9H
printf5CCKtKt&&& i M Ni KnF,i6H
B
B
$oid subr25 6
A
?D no local i, refers to global i D?
printf5CCKtKtKt--- i M Ni KnF,i6H
A
?D no local i, refers to global i D?
printf5CCKtKtKtKtPPP i M Ni KnF,i6H
B
B

152
>>>iM2
CCCi M 22
&&& i M !:9
*** i M !9022
---i M 1
PPPiM 1
153
Definition0 recursi$e adj. see recursi$e
1

rog.'.c Recursion
?D progra illustrating recursi$e function D?
?D recursi$e
function D?
int
length:char
> s6
A
printf5F%n lengthKnF6H
if 5 Ds MM CK0C6
return516H
else
return51 V length5s V 16 6H
B
main : ;
A
char
string_20`H
printf5F-nter a
string KnF6H
scanf5FNsF
,[string6H
printf5FOou entered NsKnF,string6H
printf5F%ts length is Ni KnF, length5string6 6H
B
Uecursion can be isused. This is actually a poor e)aple of Ctail recursionC 5#hen the
last thing
a routine does is call itself6. Wost tail!recursi$e progras are better #ritten iterati$ely
including
154
this one. Uecursion is best used #hen the proble itself can be described in itCs
sipliest ters in a recursi$e anner 5splitting a string in half, and in half etc6, or the
data structures in$ol$ed ay be $ie#ed as recursi$e 5binary trees, fractals6
2
.
1. definition found in se$eral sources, not possible to identify first author
2. /ee the book Data Structures and Proram Des!n !n C , for a good reference
on recursion in C and guidelines on #hen to and not to use it. This book also contains
a section in one appendi) on reo$ing recursion fro progras.
155
testo.c
?D if you ipleented s 1 here, there #ould be copiler errors
#hen you tried to send a different arguent list D?
ain 5 6
A
?D if you had a prototype, you #ould get copiler errors
#hen you tried to send a different arguent list D?
s15 6H
s15l06H
s15100,2006H
s1 51000,2000,20006H
s1 510000,20000,20000,300006H
B
?D you need to declare it int to a$oid redefining the default arguent
type D?
int s15int a, int b6
A
printf5Fa is Ni KnF,a6H
printf5Fb is Ni KnF,b6H
printf5CCKnCC6H
B
a

i
s

0

b is 123
a is 10
b is 123
a
156
is
10
0
b
is
20
0
a is
100
0
b is
200
0
a is 10000
b is 20000
157
/7ercise '.
?D #rite a progra #ith functions to do array ath D?
?D use the t#o arrays D?
?D arrayG M A 1,2,2,3B D?
?D array2 M A 4, 7, 8, 9B D?
?D ha$e a fuction to add the t#o arrays D?
?D A 7, 9, 10, 12 B D?
/* ha$e a function to ultiply the arrays D?
?D A 4, 12, 21, 22 B D?
?D ha$e a funtion to do the product of the arrays D?
/* A 5l D4 V 1 D7 V 1 D8 V 1 D9 6
52D4 V 2D7 V 2D8 V 2D9 6
52D4 V 2D7 V 2D8 V 2D9 6
53D4 V 3D7 V 3D8 V 3D96 B D?
?D allo# the user to specify #hich function they #ant D?
?D to perfor, ha$e the type 0 to 0uit D?
?D allo# the to enter functions until they decide to 0uit D?

158
Solution for /7ercise '.
$oid addQarrays 5 int a_`, int b_ `, int si(e6
A
int, tepH
printf5F>dd arrays KnF6H
printf5F>rraylKt>rray2Kt'/uKnF6H
for 5 i M 0H i I si(eH iVV 6
A
tep M a_i` V b_i`H
printf5FNiKtNiKtNi KnF ,a_i` ,b_i` ,tep 6H
B
returnH
B
$oid ultQarrays 5int a_`, int b_` , int si(e6
A
int i, tepH
printf5FWultiply arrays KnF6H
printf5F>rraylKt>rray2KtWultKnF6H
for 5 i M 0H i I si(eH iVV 6
A
tep M a_i` D b_i`H
printf5FNiKtNiKtNi KnF,a_i` ,b_i` ,tep 6H
B
returnH
B
$oid product arrays 5int a_`, int b_` , int si(e6
A
int i,j,tepH
printf5Fproduct arrays KnF6H
printf5FW ProductKnF6H
for 5 i M 0H i I si(eH iVV 6
A
tep M 0H
for 5j M 0H j I si(eH jVV 6
A
tep M tep V a_i` D b_j`H
printf5FNiKnF ,tep6H
B
returnH
B
159
ain 5 6
A
$oid addQarrays 5int a_ `, int b_ ` , int si(e6H
$oid ultQarrays 5int a_ `, int b_ ` , int si(e6H
$oid product arrays 5int a_ `, int b_ ` , int si(e6H
int a1 _ ` M A 1, 2, 2, 3 BH int a2_ ` M A 4, 7, 8, 9 BH
char choice, carriageQreturnH
choice M b bH
#hile 5 choice GM C0C 6
A
printf5CCKn-nter choice'KnF6H
printf5Fa addKnF6H
printf5F ultiplyKnF6H
printf5Fp productKnF6H
printf5F0 0uitKnF6H
scanf5F NcF,[choice6H
printf5FOou entered NcKnF,choice6H
scanf5FNcF, [carriageQreturn6H
s#itch 5 choice6
A
case CaC'
addQarrays5a1 ,a2,36H
breakH
caseCC'
ultarrays5a1,a2,36H
breakH
case CpC'
productQarrays5a1,a2,36H
breakH
case C0C'
breakH
default'
printf5CCKaln$alid inputKnF6H
breakH
B ?D end s#itch D?
B ?D end #hile D?
B ?D end ain D?

160
e7seven.c
void add&arrays: int > a) int > b, int si-e;
A
inti) temH
for : i ? FH i M si-eH iCC ;
A
tem ? aRiS C bRiSH
B
returnH
B
161
rog.+.c simle stucture : struct key!ord;

ain 5 6
A
?D synta) is' data type then nae of $ariable D?
int iH
float f1H
?D synta) is' struct then nae of structure type D?
?D this is a definition of a type, not a declaration of a $raiable of that type D?
struct date
A
/* eleents of structure declared like $ariables */
int onthH
int dayH
int yearH
BH
?D synta) is' data type then nae of $ariable D?
struct date )H ) is the nae of the $ariable to be
created
struct indicates
that ne)t #ord
is user defined data type
date is the user defined data type
).onth M 3H
).day M 29H
).year M 1::2H
printf5FTodayCs date is Ni?Ni?Ni. KnF, ).onth,).day,).year6H
B
saple output
TodayCs date is 3?29?1::2.
162
rog.,.c structures !ith heterogenous
comonents
?D progra for debtQtrade anipulation D?
?D letCs assue that debts cannot be traded on certain days, i.e. Christas D?
ain 5 6
A
struct debttrade
A
int dayH
int onthH
int yearH
float priceH
float parH
B H
struct debt trade d1H
struct debtQtrade d2H
printf5F-nter info for first debt trade KnF6H
printf5Fday onth year KnF6H
scanf5FNi Ni NiF,[d1.day, [dl.onth, [d1.year6H
printf5Fprice par KnF6H
scanf5FNf Nf,,[d1.price,[d1.par6H
printf5F-nter info for second debt trade KnF6H
printf5Fday onth year KnF6H
scanf5FNi Ni NiF,[d2.day, [d2.onth, [d2.year6H
printf5Fprice par KnF6H
scanf5FNf Nf,,[d2.price,[d l.par6H
if 5 d1.day MM 24 [[ d1.onth MM 12 6
printf5FCannot trade d1 on re0uested day KnF6H
if 5d2.day MM 24 [[ d2.onth MM 126
printf5FCannot trade d2 on re0uested day KnF6H
B
163
/7ercise '9
?D #rite a c progra that has a structure to keep track
of #hat tie it is no#. /tructure should be
able to store current hour, inutes, seconds
&isplay the current tie and #hat tie it #ould be after one second.
Continue to read in ties until the tie read in is !1 !1 !1
D?

Solution for /7ercise '9
?D progra to illustrate structures soe ore D?
struct tie
A
int hourH
int inutesH
int secondsH
BH
ain5 6
A
struct tie tieQupdate 5 struct tie 6H
struct tie current tieH
struct tie ne)t tieH
B
printf5F-nter the tie 5hh''ss6' F6H
scanf5FNi' Ni' NiF,[currentQtie.hour,
[currentQtie.inutes,[currentQtie.seconds6H
?D loop until sentinel record is found D?
#hile 5currentQtie.hour GM !1 [[ current jie.inutes GM!1
[[ currentQtie. seconds GM !1 6
A
printf5FOou entered N.2i'N.2i'N.2iKnF,currentQtie.hour,
164
currentQtie. inutes , currentQtie.seconds6H
ne)tQtie M tieQupdate 5 currentQtie 6H
printf5F;pdate tie is N.2i'N.2i'N.2iKnF, ne)tQtie.hour,
ne)tQtie.inutes, ne)tQtie.seconds6'
printf5F-nter the tie 5hh''ss6' F6H
scanf5FNi'Ni'NiF, [currentQtie.hour,
[currentQtie.inutes, [currentQtie.seconds6H
B
?D function to update the tie by one second D?
struct tie tieQupdate 5 struct tie no#6
A
no#.secondsVVH
if 5 no#.seconds M 70 6
A
no#. seconds M 0H
no#.inutesVVH
if 5 no#. inutes ?? 70 6
A
no#.inutes M 0H
no#.hourVVH
if 5 no#. hour ?? 23 6
A
no#. hour M 0H
B
B
B
return5no#6H
B
165
rog.9.c 125U time.h file
?D progra illustrates use of include file and predefined structures in
tie.h D?
/* introduces concept of pointer to a structure D?
@include Itie.hJ
ain 5 6
A
long tie$alH
?D a $ariable that points to a structure of type
t D?
struct t D tpH
?D a function, local tie, that returns a pointer to a structure of type
t D?
struct t D localtie5 6H
?D a function, ctie, that returns a pointer to a
character D?
e)tern char D ctie5 6H
?D get tie fro ;<%= syste D?
?D tie is a syste call returns the nuber of
clock ticks since idnight, ne# yearCs e$e,
1:80 D?
tie 5 [tie$al 6H
?D ctie takes the tick count and produces a string of characters that can be
displayed #ith Ns forat D?
printf5F1WT tie is Ns KnF, ctie5 [ tie$al 6 6H
?D get t structure D?
?D locatie accepts the tick count and returns a pointer to a structure that it
filled up #ith $alues that it deri$ed out of the tick count D?
166
tp M localtie5[tie$al6H
?D tp is a pointer to a structure
D ?
printf5F/tructure ebers
are'KnF6H
printf5F/econds NdKnF,tp!JtQsec6H
printf5FWinutes NdKnF,tp!JtQin6H
printf5F"ours NdKnF,tp!JtQhour6H
printf5F&ay of Wonth NdKnF,tp!JtQday6H
printf5FWonth of Oear NdKnF,tp!JtQon6H r (ero based off by one D?
printf5FOear NdKnF,tp!JtQyear6H ?D 2 digit year obsolete in 2000... D?
printf5F.eekday NdKnF,tp!JtQ#day6H
printf5F&ay of Oear NdKnF,tp!Jt!yday6H
printf5F&aylight /a$ingsY NdKnF,tp!JtQisdst6H
B
1WT tie is Thu Jun 3 14'4:'21
1::2
/tructure ebers
are'
/econds
21
Winutes
4:
"ours
14
&ay of Wonth
3
Wonth of Oear
4
Oear
:2
167
.eekday
3
&ay of Oear 144
&aylight /a$ingsY
1
<ote' the onth nuber is (ero based 5JanML, &ece l l6.
.hy do you think it is this #ayY
168
rog.<.c #rrays of Structures
?D progra to illustrate arrays of structures D?
@define <;WQU-C/ 8
struct )y( A int hH int H int sH BH
ain5 6
A
struct )y( ne)t second 5 struct )y( no#6H
struct )y( arrayQstructs_<;WQU-C/` M
A A1l,4:,4:B,
A 12, 0, 0 B,
A !1, !3, !20 B,
A 1, 1, 70 B,
A 1,2:,4:B,
A 22,4:, 4: B,
A1:,12,28B BH
int iH
struct )y( t1 ,t2H
printf5CCKnT1 Ni Ni NiKnF, arrayof structsl_1`.h, array ofstructs_l`.,
array QofQstructs_ 1`.s6H
arrayQofQstructs_ l` M ne)tQsecond 5 array ofC structs_l` 6H
printf5FT2 Ni Ni NiKnF,arrayQofQstructs_1`.h,
arrayQofQstructs_l`., arrayQofQstructs_1`.s6H
for 5i M 0H i I <;WQU-C/H iVV6
A
printf5CCKnTl Ni Ni NiKnF, arrayof structs_i`.h, arrayof structs_i`.,
array QofQstructs_i`.s6H
t1 M arrayQofQstructs_i`H?D eber#ise copy of data D?
?D $alidate the data D?
if 5 t1.h JM 0 [[ t1.h IM 22 [[ t1. JM 0 [[ t1. IM 4: [[
t1.s JM 0 [[ tl.s IM 4:6
169
t2 M ne)t second 5 t1 6H
printf5FTie one second later is Ni Ni NiKnF, t2.h, t2., t2.s6H
else
printf5F%<S>R%& &>T> KnF6H
B
B
170
?D function to update the )y( by one
second D?
struct )y( ne)tQsecond 5 struct )y( no#6
A
no#.sVVH
s#itch 5no#.s6
A
case 70'
no#.s M 0H
no#.VVH
s#itch5no#
.6
A
case 70'
no#. M0H
no#.hVVH
s#itch5no
#.h6
A
case 23'
printf5FThe /tart Lf > <e# &ay K
nF6H
no#.h M0H
breakH
default'
return5no#6H
B
breakH
default'
return5no
#
6H
171
B
breakH
default'
return5no#6H
B
return5no#6H B
172
rog.D.c Structures and #rrays
?D sho#s an array of characters inside a structure defined t#o #ays D?
struct piece
A
int pointQ$alueH
char nae_9`H
BH
?D global data structure po nested curly braces to initiali(e sub!structuresD?
struct piece po_ ` M
A
A 20, FK%<1F B,
A 10, FZ;--<F B,
A L4, F*%/"LPF B,
A 03, FK<%1"T, B,
A 08, FULLKF B,
A 01, FP>.<F B BH
ain 5 6
A
int iH
?D local data structure D?
struct piece pi_ 7` M
A A 20, A CKC, CiC, CnC, CgC, C , B B,
A 10, A CZC, CuC, CeC, CeC, CnC B B,
A 04, A C*C, CiC, CsC, ChC, CoC, CpC B B,
A03, A CKC, CnC, CiC, CgC, ChC, CtC B B,
A 08, A CUC, CoC, CoC, CkC, C , B B,
A 01, A CPC, CaC, C#C, CnC, C , B B
B H
printf5FPieceKt Sal ueKnF6H
printtf5+!!!!!Kt!!!!!KnF6'
for 5 i M 0H i I 7H iVV 6
A
173
printf5F NcNcNcNcNcNcKtN2iKnF, pi_i`.nae_0`,
pi_i`.nae_1`,pi_i`.nae_2`, pi_i`.nae_2`, pi_i`.nae_3`,
pi_i`.nae_4`, pi_i`.pointQ$alue6H
printf5CCKn fro po KnF6H
printf5FPieceKtSalueKnF6H
printff5F!!!!!!Kt!!!!!!KnF6H
for 5 i M 0H i I 7H iVV 6
printf5FNsKtN2iKnF, po_i`.nae,po_i`.pointQ$alue6H
B
Piece Salue
!!!!! !!!!!
King 20
Zueen 10
*ishop 4
Knight 3
Uook 8
Pa#n 1
fro po
Piece Salue
!!!!! !!!!!
King 20
Zueen 10
*ishop 4
Knight 3
Uook 8
Pa#n 1
174
/7ercise '<
#rite a progra that reads in an opening
balance
for a checking account, a list of
check nubers
dates and aounts.
print out a nice list of the opening
balance,
the list of transactions, sorted by
check nuber
and the running balance after each
transaction
use structures and functions
saple input data
4000.00
1 1?22?:2 24.00
2 1?23?:2 22.00
4 2?2?:2 128.00
3 2?1?:2 :2.00
13 3?14?:2 3400.00
2 1?22?:2 100.00
/aple Lutput
Lpening *alance c4000
Check <uber Transaction &ate >ount <e# *alance
1 1?22?:2 24.00 3:84.00
2 1?22?:2 100.00 3984.00
2 1?23?:2 22.00 3942.00
3 2?1?:2 :2.00 384:.00
4 2?2?:2 128.00 3722.00
13 3?14?:2 3400.00 122.00
175
/7ercise '<.c
@define W>=U-C/ 20
struct trans
A
int chkH
char date_:`H
float atH
BH
$oid sorttrans 5 tptr, count6
struct trans D tptrH
int countH
A
int i,jH
struct trans tepH
for 5 i M 0H i I count ! 1H iVV 6
A
for 5j M i V 1H j I countH jVV 6
A
if 5 tptr_i`.chk J tptr_j`.chk 6
A
tep M tptr_i`H
tptrji` M tptr_j`H
tptr_j` M tepH
B
B
B
B
176
ain 5 6
A
struct trans ttrans_W>=U-C/`H
$oid sorttrans5 6H
int i,rec,chkH
float bal,ne#balH
printf5Fopening balance please KnF6H
scanf5FNfC ,[bal6H
chk M 0H rec M 0H
#hile 5 chk GM
!1 6
A
printf5F-nter check nuber
KnF6H
scanf5FNiF,[chk6H
if 5chk GM !1 6
A
ttrans_rec`.chk M chkH
printf5F-nter date ?dd?yy and aount 5float6
KnF6H
scanf5FNs Nf,,[ttrans_rec`.date,[ttrans_rec`.at6H
recVVH
printf5FLU%1%<>R T>*R-
KnF6H
for 5 i M 0H i I recH iVV 6
A
printf5FNi Ns NfKnF ,ttrans_i` .chk,ttrans _i` .date,ttrans_i`
.at6H
B
sorttrans5 [ttrans _0` ,rec6H
printf5F/LUT-& T>*R-
KnF6H
for 5 i M 0H i I recH iVV 6
A
printf5FNi Ns NfKnF, ttrans_i`.chk, ttrans_i`.date,
ttrans_i`.at6H
B
printf5FT>*R- #ith balances KnF6H
ne#bal M balH
for 5 i M 0H i I recH iVV 6
A
ne#bal M ne#bal ! ttrans_i`.atH
printf5FNi Ns Nf NtKnF,ttrans_i`.chk, ttrans_i`.date,
ttrans_i`.at,ne#bal6H
B
177
B
178
e7ercise'<c.dat
1000.00
1
1?1?:240.00
4
1?2?:224.00
8
1?2?:2 10.00
2
1?1?:224.00
2
1?1?:284.00
9
1?3?:2 100.00
3
1?1?:2 4.00
7
1?2?:2 20.00
10
2?29?:2100.00
:
2?14?:220.00
!1

179
%R5W52#4 T#$4/
11?1?:240.000000
4 1?2?:2 24.000000
8 1G2?:2 10.000000
2 1?1?:224.000000
2 1?1?:284.000000
91?3?:2 100.000000
3 1?1?:2 4.000000
7 1?2?:2 20.000000
10 2?29?:2 100.000000
: 2?14?,:2 20.000000
S%RT/D T#$4/
1 1?1?:2 40.000000
2 1?1?:2 24.000000
2 1?1?:2 84.000000
31?1?:24.000000
4 1?2?:2 24.000000
7 1?2?:2 20.000000
8 1?2?:2 10.000000
9 1?3?:2 100.000000
: 2?14?:2 20.000000
10 2?29?:2 100.000000
T#$4/ !ith balances
1 1?1?:2 40.000000 :40.000000
21?1?:224.000000 :24.000000
2 1?1?:2 84.000000 940.000000
31?1?:24.000000 934.000000
4 1?2?:2 24.000000 920.000000
7 1?2?:2 20.000000 900.000000
8 1?2?:2 10.000000 8:0.000000
9 1?3?:2 100.000000 7:0.000000
: 2?14?:2 20.000000 770.000000
10 2?29?:2 100.000000 470.000000

rog.8.c String Processing strlen
180
?D function to count the nuber of characters in a string D?
?D also the ;<%= function that does the sae thing D?
@include Istring.hJ
?D returns a count of ho# any characters are in string D?
?D count does not include null terinator D?
?D accepts a null terinated string D?
int ourQstringQlength 5 char D input string 6
A
int count M 0H
/* note the null terinator is binary (ero D ?
#hile 5inputQstring_count` 6
countVVH
return5count6H
B
ain5 6
A
int ourQstringQlength 5 char D string 6H
char#ordl_ ` M ACTC, CeC, CrC, CrC, CiC, ClC, ClC, FK0,BH
char #ord2_` M A CLC, b#C, CeC, CnC, CsC, CK0C BH
printf5F;/%<1 L;U UL;T%<- .- &%/CLS-UKnF6H
printf5Flength of Ns is Ni KnF,#ordl, ourQstringQlength5#ordl66H
printf5Flength of Ns is Ni KnKnF,#ord2,ourQstringQlength5#ord266H
printf5F;/%<1 *;%RT %< ULl%T%<- .- &%/CLS-UKnF6H
printf5Flength of Ns is Ni KnF,#ordl,strlen5#ord166H
printf5Flength of Ns is Ni KnF,#ord2,strlen5#ord266H
B
;/%<1 L;U UL;T%<- .- &%/CLS-U
length of Terrill is 8
length of L#ens is 4
;/%<1 *;%RT %< UL;T%<- .- &%/CLS-U
length of Terrill is 8
length of L#ens is 4
181
rog.E.c String Processing strcat
?D progra to illustrate string concatenation D?
?D uses pointers D ?
?D uses built in functions D ?
@include Istring.hJ
@define W>=Q/%T- 100
char s1_` M AFTerrillFBH
char s2_` M AFL#ensFBH
char sa_` M AFLingo F B H
char sb_` M AF*oingo FBH
char s2_W>=Q/%T-`H
char s3_W>=Q/lT-`H
char stringa_` M AFabcde FBH
?D jtcat concatenates a and b into c, replace c if contains data D?
$oid jtcat5 charD a, charD b, charD c6
A
?D copy all of a into c, stop before copy null terinator D?
#hile 5 Da GM CK0C 6
A
DcVV M DaVVH
B
?D copy all of b onto end of c D ?
#hile 5Db 6
A
DcVV M DbVVH
B
?D reeber to tack null terinator onto end of c D?
Dc M CK0CH
B

182
ain 5 6
A
$oid jtcat5 charD, charD, charD6H ?D jts concatenation routine D?
?D call strcat, send s1 and s2
function sticks s2 onto back of s1, returns s1 D?
strcat5s1, s26H
printf5+NsKn,,s16H
?D call strcat, send s2 and s1 D?
?D function sticks s1 onto end of s2, returns s2 D?
strcat5s2,stringa6H
strcat5s2,stringa6H
strcat5s2,stringa6H
strcat5s2,stringa6H
strcat5s2,stringa6H
strcat5s2,stringa6H
printf5+Ns,,s26H
printf5+Kn,6H
?D no# use jtcat routine D?
printf5+NsKn,,sa6H
printf5+NsKn,,sb6H
jtcat5sa,sb,s36H
printf5+NsKnKn,,s36H
B
saple output
Terrill L#ens
abcde abcde abcde abcde abcde abcde
Lingo
*oingo
Lingo *oingo
183
rog9F.c String Processing strcm
@include Istring.hJ
int jte05char D s1, char D s26
A
#hile 5Ds1VV MM Ds2VV 6
A
if 5 Ds1 MM bK0d [[ Ds2 MM bK0d6
return5 0 6H ?D 0 is code for +e0ual, in y routine D?
B
return 5 1 6H ?D 1 is code for +not e0ual, in y routine D?
B
ain 5 6
A
int jte05 charD, charD 6H
char stra_` M FTerrill L#ensFH
char strb_` M FTerrillFH
int e0ualreturnH
char D strings_` M
A FThe /aeF, F<ot The /aeF BH
int cpQ$al1, cpQ$al2, cpQ$al2H
e0ualQreturn M jte05stra,stra6H
printf5FNs and KnNs are Ns KnKnF,stra,stra,strings_e0ualQreturn`6H
e0ualQreturn M jte05stra,strb6H
printf5FNs and KnNs are Ns KnKnF,stra,strb,strings_e0ualQreturn`6H
cpQ$all M strcp5stra,stra6H
printf5FcpQ$al1 MJ Ni KnF,cpQ$al16H
cpQ$al2 M strcp5stra,strb6H
printf5FcpQ$a12 MJ Ni KnF,cpQ$a126H
cpQ$al2 M strcp5strb,stra6H
printf5FcpQ$al2 MJ Ni KnF,cpQ$al26H
B
184
/7ercise 'D
.rite a progra that #ill input a list of #ords until the #ord 0uit is entered.
Create one long string fro all these #ords, seperating the in the created
string by a dollar sign. &o not allo# the #ord foobar to be entered into your
string. 5ignore it if it is entered6.
Print out a table #hich includes each of the #ords input and its length.
Print out the final created string.
"int' ;se strcat, strlen, and strcp
185
Solution 6or /7ercise 'D
@include Istring.hJ
ain 5 6
A
int )H
char s_20`H
char d_ 1000`H
printf5F-nter #ordKnF6H
scanf5FNsF ,s6H
) M strcp5s,F0uitF6H
#hile 5 ) GM 0 6?D strcp returns P>R/- if a atch D?
A
if 5 strcp5s,FfoobarF6 6
A
strcat5d,s6H
strcat5d,FcF6H
) M strlen5s6H
printf5FNs length MJ Ni KnF,s,)6H
B
else
A
printf5FCannot insert that #ordKnF6H
B
printf5F-nter #ordKnF6H
scanf5FNsF,s6H
) M strcp5s,F0uitF6H
B
printf5FPinal #ord is NsKnF,d6H
B
sttrcp5FabcF,FabcF6 #ould return 0 because they differ in 0 locations
strcp5FabcF,F)y(F6 #ould return non!(ero
186
rog9+.c getchar and gets
?D as an e)ercise, reo$e the ne)t line and copile and
run D?
@include Istdio.hJ
ain 5 6
A
?D getchar returns one character fro stdin as an
integerD?
?D gets returns one ne#line terinated line fro
stdin D?
?D the line is turned into a null terinated string #ith #s preser$ed D?
?D if the gets fails, it returns <;RR, other#ise it returns the address that you
passed it D?
int
i M
0H
int
cH
char D ptrH
char inputQline_9l`H
printf5FPlease enter string then press return KnF6H
do
A
c M getchar5 6' ?D a function that returns one character D?
inputQline_i` M 5char6cH
iVVH
B
#hile 5 c GM CKnC 6H
inputQline_i ! 1` M bK0dH ?D null terinate the line D?
printf5FOou entered NsKnF ,inputQline6H
printf5FKnPlease enter string then press return KnF6H
pointer to string returned pointer to desired location to put string
ptr M gets5[inputQline_0`6H
?D ptr M gets5input%ine6' T"%/ >R/L .LUK/, ."OYY D?
if 5 ptr MM <;RR 6
printf5Fgets failed KnF6H
else
printf5Fgets succeeded KnF6H
printf5FOou entered NsKnF,inputQ%ine6H
B
187
rog9,.c
@define P>R/- 0
@define TU;- 1
@include Ictype.hJ
">S- > RLLK >T
ctype.h
RLLK at the acro
definitions
OouCll find these in any C reference under %/))))) ususlly grouped together, or look
up ctype.h
ain 5 6
A
?D progra to input characters and report #hether they are alphabetic or not D?
ch
ar
c M
C)CH
ch
ar
crH
#hile 5
c GM C0C
6
A
printf5CCKn-nter a character, %Cll tell you if itCs
alphabeticKnF6H
scanf5FNcF,[c6H ?D get the character D?
scanf5FNcF,[cr6H ?D soak in the carriage
return D?
if 5isalpha5c6 6
printf5FNc is alp
188
habeticKnF,c6H
else
printf5FNc is not
alphabeticKnF,c6H
printf5CCKnCC6H
B
B
189
String 6unctions
@include
Istring.h
J
char D strcat5sl,s26 s2 stuck on end of s1, returns pointer to s1
char D strchr5s,c6 search s for 1
st
occurence of c, return pointer to c or
<;RR
int strcp5sl,s26 1 I 0 s1 I s2
0 s1 MM s2
J0 s1 J s2
char D strcpy5sl,s26 s2 copied o$er s1, returns pointer to s1
si(eQt strlen5sl6 find length of s1
char D strncat5s 1 ,s2,n6 copy s2 to end of s1 until null encountered or n chars
copied
int strncp5sl,s2,n6 copare s1 to s2 o$er n characters
char D strncpy5sl,s2,n6 copy s2 to s1 for at ost n characters, ay null terinate
before n
char D strrchr5s,c6 search s for last occurrence of c, returns pointer to c or
<;RR
1. strcp looks soething like'
signed strcp5const char Da.const char
Db6
A
#hile5DaMDb6
A
if5DaMMCKLC6
return 0H
a
V
V
190
H
b
V
V
H

B

retu
rn
Da!
DbH
B
191
Character 6unctions
Wost copilers actually ipleent these as acros not
functions.
@include Ictype.hJ
0 e0uates to no, false
1 e0uates to yes, true
isalnu5c6 is character c alphanuericY
isalpha5c6 is character c alphabeticY
iscntrl5c6 is character c a control characterY
isdigit5c6 is character c a digitY
islo#er5c6 is character c lo#er caseY
isprint5c6 is character c a printable character
ispunct5c6 is character c a punctuation character
isupper5c6 is character c upper caseY
isspace5c6 is character c a #hite space characterY
tolo#er5c6 con$ert character c to lo#er case
toupper5c6 con$ert character c to upper case

4arge 2umbers as Characters /7ercise
.rite a C progra to'
read in, as character strings, t#o arbitrarily large nubers 5ie' 28 digits6
add the together
display the result

192
@include Istdio.hJ
int
jcon$5ch
ar6H
char
jre$5int6H
ain56
A
char nu1_20`, nu2_20`, nu2
_21`H
int n1 _20`, n2 _20` H
int n2 _21` H
int len1, len2,
lena)H
int shuffleQdist,
iH
int ans, carryH
for 5 i M 0H i I 20H iVV 6
A
nu1 _ i` M 0)00H
nu2 _ i` M 0)00H
nu2 _ i` M 0)00H
B
printf5F-nter first nuberKnF6H
scanf5FNsF,[nu1_0`6 H
printf5F-nter second
nuberKnF6H
scanf5FNsF,[nu2_0`6 H
printf 5Fnu1 char is Ns KnF, nul
6 H
193
printf 5Fnu2 char is Ns Kn F,
nu2 6 H
?D find out ho# long the string is D?
len1 M strlen5nu16H
len2 M strlen5nu26H
?D find out #hich one is longer D?
if 5 len1 MM len2 6
A
?D you are okay, no shuffling re0uired D?
?D just re$erse the strings D?
printf5+/trings are sae lengthKnF6H
lena) M len1H
B
else
A
if 5 len1 I len2 6
A
printf5Flen1 I len2
KnF 6H
lena) M len2H
printf5Flena) is Ni KnF,lena)6H
shuffleQdist M len2 ! len1H
printf 5+shuffleQdist is Ni KnF,
shuffleQdist6H
?D need to shuffle lenl and pad #ith LCs D?
for 5 i M len1H i JM 0 H i!! 6
nu1_i V shuffleQdist` M nu1_i`
for 5 l M 0H i I shuffleQdistH iVV 6
nu1 _i` M b0dH
B
else
194
A
printf5Flen1 J len2 KnF6H
lena) M len1H
printf5Flena) is Ni KnF,lena)6H
?D need to shuffle len2 and pad #ith LCs D?
shuffleQdist M len1 ! len2H
?D need to shuffle len1 and pad #ith LCs D?
for 5 i M len2H i JM 0 H i!! 6
nu2_i V shuffle dist` M nu2_i`H
for 5 i M 0H i I shuffleQdistH iVV 6
nu2_i` M C0CH !
B
B
?Dprint after padding D?
printf5Fafter padding nu1 is Ns KnF,nu16H
printf5Fafter padding nu2 is Ns KnF,nu26H
?D no# con$ert fro character to integer D?
for 5 i M 0H i I lena)H iVV 6
A
n1_i` M jcon$5 nu1_i` 6H
n2_i` M jcon$5 nu2_i` 6H
B
printf5Fafter con$erting to array of integers KnF6
for 5 i M 0H i I lena)H iVV 6
A
printf5+N1iF,n1_i`6 H
B
printf5FKnF6 H
for 5 i M 0H i I lena)H iVV 6
195
A
printf 5+N1iF ,n2_i`6H
B
?D no# start adding fro the back to the front D?
carry M 0H
for 5 i M lena) ! 1H i JM 0H i!! 6
A
ans M n2_i` V n1_i` V carryH
printf5Fans is Ni KnF,ans6H
carry M ans ? 10H
n2 _i V 1` M ans N 10H
B
n2 _0` M carryH
196
printf5FKn n2 array is KnF6H
for 5 i M 0H i IM lena)H iVV 6
A
printf 5+N1iF ,n2 _i`6H
B
?D no# con$ert back to character D?
for 5 i M 0H i IM lena)H iVV 6
nu2_i` M jre$5 n2_i` 6H
nu2 _lena) V 1` M CK0CH
printf5FPinal string is Ns KnF,nu26H
B
197
int jcon$5char c 6
A
s#itch 5 c 6
A
case b0d'
return 0H
breakH
case b1d'
return 1H
breakH
case b2d'
return 2H
breakH
case b2d'
return 2H
breakH
case b3d'
return 3H
breakH
case b4d'
return 4H
breakH
case b7d'
return 7H
breakH
case b8d'
return 8H
breakH
case b9d'
return 9H
breakH
case b:d'
return :H
198
breakH
B
B
char jre$5int i 6
A
s#itch 5 i 6
A
case 0'
return b0dH
breakH
case 1'
return b1dH
breakH
case 2'
return b2dH
breakH
case 2'
return b2dH
breakH
case 3'
return b3dH
breakH
case 4'
return b4dH
breakH
case 7'
return b7dH
breakH
case 8'
return b8dH
breakH
case 9'
return b9dH
breakH
case :'
return b:dH
breakH
B
B
199
Solution to Characters as 4arge 5ntegers /7ercise
=> charlarge.c */
/* progra to add together large character strings representing positi$e
integers D?
@include Istring.hJ
@define W>=&%1%T/ 20
char digits_ ` M A
F012234789:FBH ain 5 6
A
char sl_W>=&%1%T/`H int lenlH ?D first string and its length D?
char s2_W>=&%1%T/`H int len2H ?D second string and its length D?
char sresult_W>=&%1%T/`H ?D result string D?
char dt1_2`H char dt2_2`H ?D teporary strings for each digit D?
int dl, d2,dsuH ?D teporary digits for integers D?
int i,a)len,jposH
int carryQflag M 0H
dtl_l` M L)LLH ?D null terinate the teporary strings D?
dt2_ 1` M L)LLH
?D input the t#o strings to add together D?
printf5F-nter first string KnF6H
scanf5FNsF,s16H
len1 M strlen5s16H
@ifdef&-*;1
printf5FThere are Ni digits in NsKnF,lenl,sl6H
@endif
printf5F-nter second string KnF6H
scanf5FNsF ,s26H
len2 M strlen5s26H
@ifdef &-*;1
printf5FThere are Ni digits in NsKnF,len2,s26H
200
@endif

/* if the first string is longer, shuffle the second string into a field the
sae si(e as the first string D?
if 5lenl J len2 6
A
@ifdef &-*;1
printf5F/huffling s2KnF6H
@endif
?D set a)len and shuffle other nuber o$er D?
a)len M len1H ?D pointer the last position in ne# s2, the
null D?
jpos M len2H ?D pointer to last position in s2, the null
D ?
?D start i at the null, o$e it back to (eroeth
position D?
for 5i M a)lenH i JM 0H i!! 6
A
if 5jpos JM 0 6 ?D if orig char o$e to ne# D?
A
s2_i` M s2_jpos`H
jpos!!H
B
else ?D other#ise put in a (ero D?
s2_i` M C0CH
B
B
?D if the second string is longer, shuffle the first string into a field the
sae si(e as the second string D?
else if 5 len2 J len 1 6
A
201
@ifdef &-*;1
printf5F/huffling s 1Kn F6H
@endif
?D set a)len and shuffle other nuber o$er D?
a)len M len2H jpos M len1H
for 5 i M a)lenH i JM 0H i!! 6
A
if 5 jpos JM 0 6
A
sl_i` M s l_jpos`H
jpos!!H
B
else
s1_i` M C0CH
B
B
e
lse A
@ifdef
&-*;
1
printf5F<o need to shuffle KnF6H
@endif
a)len M len 1H B
@ifdef &-*;1
printf5Fs 1 no# NsKnF ,s
16H
printf5Fs2 no# NsKnF
,s26H
@endif
sresult_a)len V 1` M L)LLH ?D put in the terinating null for sresult D?
sresult_0` M b bH ?D assue a space in first position D?
202
for 5 i M a)len ! 1H i JM 0 H i!! 6
A
dt1_0` M sl_i`H d1 M atoi5dtl6H ?D con$ert char to string, string to int D?
dt2_0` M s2_i`H d2 M atoi5dt26H ?D con$ert char to string, string to int D?
dsu M d1 V d2 V carryQflagH ?D copute resulting int D?
?D deterine if a carry e$ent
occurred D?
if 5 dsu JM 10 6
A
dsu M dsu ! 10H
carry flag M 1H
else A carry flag M 0H B
@ifdef &-*;1
printf5Fd 1 is Ni F, d16H
printf5Fd2 is NiKnF,d26H
@endif
sresult_i V 1` M digits_dsu`H?D con$ert int to char $ia array D?
B
if 5 carry flag MM 1 6
sresult_0` M C1CH /* if the last addition produced a carry
put the 1 in the first position D?
printf5Fsresult is NsKnF,sresult6H
B ?D end ain D?
/7ercise '8
?D odify prog44.c so that it #ill allo# the user to add ne# stocks to the stock list D?
?D odify prog44.c so that the user can search for stocks by nuber D?
?D allo# the to enter the nuber and retrie$e the nae and ticker sybol D?
203

204
rog99.c Structures and
Strings
@define /TU%<1Q/%T- 20
@define T%CK-UQ/%T- 4
@define W>=Q-<TU%-/ 20
@include
Istring.h
J
struct
stockQen
try
A
int stockQnuberH
char stockQnae_/TU%<1
Q/%T-`H
char
tickerQsybol_T%CK-UQ/
%T-`H
B H
struct stockQentry
stockQlist_W>=Q-<TU%-/` M
A
A 0, F%*WF, F%*WF B,
A 1, F1eneral
WotorsF, F1WF B,
A 2, F1eneral
-lectricF,F1-FB,
A 2, FTerrill L#ensF,
FW-UF B,
A 3, FPordF,FPF B
BH
205
?D function to look for a string that atches the input string /earch the array of
structures for the
string. Ueturn inde) in array if found Ueturn !1 if not found. D?
int findQstock5 s, #, count6
struct stockQentryD sH
char D #H
int countH
A
int i, resultH
for 5 i M 0H i I
countH iVV 6
A
result M
strcp5s5i`.stockQnae,
#6H
if 5 result MM 0 6
return5i6H ?D found it D?
result M
strcp5s_i`.tickerQsybol,#6H
if 5 result MM 0 6
return5i6H ?D found it D?
B
return5 !16H
B
ain 5 6
A
char
searchQ#ord_/TU%<1Q/%T-`
H
int id)H
int findQstock5 6H
printf5FKnKn-nter stock nae or ticker sybol to search for 50uit6 to
206
0uitKnF6H
8ifdef SC#26
scanf5FN/TU%<1 Q/%T-sF, searchQ#ord6H
@else
gets 5searchQ #ord6H
@endif
printf5FOou entered Ns K
1F,searchQ#ord6H
?D strcp returns 0 on a atch
D?
#hile 5 strcp5searchQ
#ord,F0uitF6 A
id) M findQstock5stockQlist,
searchQ#ord, 46H
if 5 id) MM !1 6
printf5FNs not found in stockQlist KnF,searchQ #ord6H
else
printf5FNi Ns N sKn F, stockQlist_id)`.stockQnuber,
stockQlist_id)`.stockQnae, stockQlist_id)`.ticker
sybol6'
printf5CCKnKn-nter stock nae or ticker sybol to search for 50uit6 to
0uitKnF6H
8ifdef SC#26
scanf5F N/TU%<1 Q/%T-s F ,searchQ#ord6H
@else
gets 5searchQ #ord6H
@endif
printf5FOou entered Ns KtF ,searchQ#ord6H
B
printf5CCK
nKnCC6H
B /* end ain D?
207
-nter stock nae or ticker sybol to search for 50uit6 to 0uit
ib
Oou entered ib ib not found in stockQlist
-nter stock nae or ticker sybol to search for 50uit6 to 0uit
%*W
Oou entered %*W 0 %*W %*W
-nter stock nae or ticker sybol to search for 50uit6 to 0uit
Terrill
Oou entered Terrill Terrill not found in stockQlist
-nter stock nae or ticker sybol to search for 50uit6 to 0uit
Terrill L#ens
Oou entered Terrill L#ens Terrill L#ens not found in stockQlist
-nter stock nae or ticker sybol to search for 50uit6 to 0uit
0uit
Oou entered 0uit
acc rog99.c => to not have debug rints >=
ace BDSC#26 rog99.c => to have debug rints >=
208
rog9D.c Pointers
/* Progra to illustrate pointers D?
ain 5 6
A
int iH
int jH
int D int pointerH ?D read as intpointer is a pointer to an integer D ?
?D intQpointer gets address of i D ?
?D intpointer no# points at eory location that $ariable D?
?D i is stored in D?
intQpointer M [iH
?D assign 4 to the location that int pointer is pointing to D?
?D this effecti$ely assigns 4 to i D?
?D and is e0ui$alent to i M 4H D?
DintQpointer M 4H
?D assign to j the $alue pointed to by int pointer D?
?D this is e0ui$alent to j M iH D?
j M DintQpointerH
printf5Fi M Ni, j M NiKnF,i,j6H
B

209
rog98.c Pointers
?D Progra to illustrate pointers D?
ain5 6
A
?D declare a character $ariable c, assign initial $alueG D?
charc M CZCH
char d M C)CH
/* declare a character pointer charQpointer */
/* assign it the address of the character $ariable c */
/* charQpointer no# points to c D?
char D charQpointer M [cH
char D dptr M [dH
char DD ddptr M [dptrH
char DDD dddptr M [ddptrH
?Dprintf5FNc NcKnF,c, DcharQpointer6HD?
printf5FNc Nc Nc Nc KnF,d,Ddptr,DDddptr,DDDdddptr6H
printf5Faddress of d Np $alue of d Nc KnF,[d,d6H
printf5Faddress of dptr Np $alue of dptr N) KnF,[dptr,dptr6H
printf5Faddress of ddptr Np $alue of ddptr N) KnF,[ddptr,ddptr6H
printf5Faddress of dddptr Np $alue of dddptr N) KnF,[dddptr,dddptr6H
?D assign a ne# $alue to c using traditional ethod D?
c M b?dH
printf5FNc NcKnF,c, DcharQpointer6H
/* assign a ne# $alue to c using pointer ethod D?
Dchar Qpointer M b5bH
printf5FNc NcKnF,c, DcharQpointer6H
?D saple output D?
))))
address of d f8fffcge $alue of d )
address of dptr f8fffc:3 $alue of dptr f8fffcge
address of ddptr f8fffc:0 $alue of ddptr f8fffc:3
address of dddptr f8fffc9c $alue of dddptr f8fffc:0
""
5 5

210
Pointers
char c M CZCH Z addr
102
char d M C)CH ) addr
102
char D dptr M [dHe 102 addr
103
char D D ddptr M [ dptrH 103 addr
109
char D D D dddptr M [ ddptrH 109 addr
112
dMJ) [d MJ 102
dptr MJ 102 Ddptr MJ ) [dptr MJ 103
ddptr MJ 103 Dddptr MJ 102
DDddptr MJ )
[ddptr MJ 109
dddptrMJ 109 Ddddptr MJ 103
DDddptr MJ 102
DDDdddptr MJ )
[dddptr MJ 112
211
rog9E.c Pointers to Structures
/* progra for debt trade anipulation D?
?D letCs assue that they cannot be traded on certain days, i.e.
Christas D?
?D letCs refer to the structures $ia pointers D?
ain 5 6 A
int iH
struct debt trade A
int dayH
int onthH
int yearH
float priceH
float parH BH
struct debtQtrade debts_4`H
struct debtQtrade D dtptrH
dtptr M [debts_0`H ?D establish pointer to first eleent of array D?
for 5i M 0H i I 4H iVV 6
A
scanf5FNi Ni Ni Nf NfC,[debts_i`.day, [debts_i`.onth,
[debts_i`.year, [debts_i`.price,[debts_i`.par6H
?D see if date is any good using array
notation D?
if 5debts_i`.day M 24 [[ debts_i`.onth MM
12 6
printf5FNf Nf C><<LT TU>&- L< Ni?Ni?NiKnF,
debts_i`.price,
debts_i` .par, debts_i` .day,debts_i`.onth,debts_i6
.year6H
else
printf5FNf Nf okay on Ni?Ni?NiF, debts_i`.price, debts_i`.par,
debts_i` .day, debts_i`.onth, debts_i`. year6H
212
?D see if date is any good using pointer notation D?
if 5 dtptr!Jday M 24 [[ dtptr!Jonth M 12 6
printf5FNf Nf C><<LT TU>&- L< Ni?Ni?NiKnF, debtsj
il.price,
debts_i` .par, debts_i` .day,debts_i`.onth,debts_i6. year6H
?D see if date is any good using pointer and array notation D?
if 5dtptr!Jday MM 24 [[ debts_i`.onth MM 12 6
printf5FNf Nf C><<LT TU>&- L< Ni?Ni?NiKnF,
debts_ i`.price,
debts_i`.par, debts_i`.day,debts_i`.onth, debts_i`.year6'
?D o$e the pointer ahead to ne)t
entry D?
dtptrVVH
B ?D end for D?
213
rog9E.dat
1 1 1::2 1.0 1.0
1 1 1::2 122.4 1.08
2 29 1::2 23.4 1.0:9
24 12 1:90 1.0 1.:9
22 111:8: 100.422.82
Samle Run
a.out I prog4:.dat
1.000000 1.000000 okay on 1?1?1::2
122.400000 1.080000 okay on 1?1?1::2
23.400000 1.0:9000 okay on 2?29?1::2
1.000000 1.:90000 C><<LT TU>&- L< 24?12?1:90
1.000000 1.:90000 C><<LT TU>&- L< 24?12?1:90
1.000000 1.:90000 C><<LT TU>&- L< 24?12?1:90
100.42::::2.820000 okay on 22?11?1:8:
214
# better linked list e7amle
struct node
A
int $alH
int $als0H
struct node D ne)tH
BH
@include Istdio.hJ
$oid ain5 6
A
struct node D headM<;RRH
int $H
printf5Fenter a positi$e $al or !1 to end KnF6H
scanf5FNiF,[$6H
#hile5$G M !1 6
A
addnode5$, [head6H
printlist5head6H
printf5Fne)t... F6H
scanf5FNiF,[$6H
B
/* list after loop */
printlist5head6H
B
$oid addnode5int in, struct node DDh6
A
struct node DpH
pMDhH
/* go through list till find $alue or reach end */
#hile5pGM<;RR [[ p!J$alG M in6
pMp!Jne)tH
/* if end #as reached addQite at head of list */
if5p MM <;RR6
A
/* allocate ne# node and copy data D?
p M 5struct nodeD6 alloc5si(eof5struct node66H
p!J$alMinH
p!J$als0 M in D inH
/* ake this node point at top ite in list */
p!Jne)tMDhH
215
/* reset head to be this ne# node D?
DhMpH
B
B
$oid printlist5struct node Dh6
A
/* repeat #hile pointer is not null */
#hile5h6
A
/* print $alue at this node */
printf5F NiKtNiKnF ,h !J$al,h !J$als06H
/* print ne)t node D "
hMh!Jne)tH
B
B
216
rog<F.c 1sing Pointers in a 4inked 4ist
?D also deonstrates dynaic eory allocation #ith alloc D?
?D #e need to read in nubers, donCt kno# ho# any D?
@include Istdlib.hJ
@include Istdio.hJ
ain 5 6
A
?D a linked list entry structure definition D?
struct lle
A
int $alueH ?D $alue in list D?
int s0uared $alueH ?D $alue in list D?
struct lle Dne)tH ?D pointer to ne)t entry D?
BH
struct lle firstQeleentH ?D first entry in list D?
struct lleD ne)tQeleentH ?D pointer to any entry in list D?
int $alH
printf5Fsi(e of lle is NiKnF,si(eof5firstQeleent66H
printf5F-nter $alue to s0uare and store 5!16 to stopKnF6H
scanf5FNiF,[$al6H
?D set up pointer to already established eleent D?
ne)tQeleent M [firstQeleentH
/* enter $alue to
s0uare and store D?
#hile 5$alGM !1 6
A
ne)tQeleent!J$alue M $alH
ne)tQeleent!Js0uaredQ $alue M $al D $alH
?D allocate eory for another structure D?
?D returns a pointer to the eory allocated, pointer #ill be of
217
type 5char D6 D?
ne)tQeleent!Jne)t M :struct lleD6
alloc5si(eof5firstQeleent66'
printf5F-nter $alue to s0uare and store
5!16 to stopKnF6H
scanf5FNiF,[$al6H
if5$al GM!16
ne)tQeleent M ne)tQeleent!
Jne)tH
else
ne)tQeleent!Jne)t M <;RRH
B
ne)tQeleent M
[firstQeleentH
#hile 5ne)t eleent GM <;RR6
A
?D print out $alues fro this linked list eleent D ?
printf5F$alue M Ni s0uared NiKnF,
ne)tQeleent!J$alue, ne)tQeleent!Js0uared , $alue6H
printf5CCKt This record stored at NpKnF,ne)tQeleent6H
printf5CCKt This record points to record at NpKnKnF,ne)tQeleent!Jne)t6H
?D ad$ance pointer to ne)t eleent in linked list D?
ne)tQeleent M ne)tQeleent!Jne)tH
B
B
218
valref.c Pointers and 6unctions
?D deonstrate that if a function recei$es the address of an ite it
can
update the ite. This is roughly e0ui$alent to call by reference,
but it still
is call by $alue, the $alue passed is the address of another ite D?
@ifdef ></%
$oid refl5intD )6 ?D ansi function header D?
@else
$oid ref15)6 ?D K [ U function header D?
intD )H
@endif
A
D) M D) V 1H ?D add one to $alue stored at address stored in )
D?
printf5F%n ref1 ) M Ni KnF,D)6H ?D print it out D?
returnH
B
ain 5 6
A
int i M 4H
printf5F%n ain i M Ni KnF,i6H
ref15[i6H ?D pass address of i to ref1 D?
printf5F%n ain i M Ni KnF,i6H ?D notice that ref1 changed i D?
B
219
/7ercise 'E
/* PLU T"L/- CLWPLUT>*R- .%T" T"- R%<K-& R%/T &>T> /TU;CT;U-
D?
?D #rite a C progra to allo#
1' ;ser to input eleents into a linked list
2' ;ser to print linked list for#ards
2' ;ser to add eleents to end of linked list
3' ;ser to delete any eleent fro list 5if it is present6 by searching
for the first
occurrance of the $alue and deleting that ite.
ipleent as you dee fit 5double linked
list6
D?
?D PLU T"L/- ."L .L;R& PU-P-U TL &L /LW-T"%<1
&%PP-U-<T D?
?D
.rite > C Progra that #ill do the
follo#ing
16 %nput te)t up to 1,023 characters
into an array
26 Create a structure that stores
@ of characters
@ of #hite space seperated #ords
longest #ord
shortest #ord
26 >llo# user to search for any string in the array
if found, allo# the to
change it
to soe other string #ithout
daaging
the characters around the
point of
220
editing and #ithout
producing any
ne# #hitespace
221
;/-P;R P;<CT%L</
is#space5c6
strstr5 s 1 ,s26
=> e7'E.c >=
?D solution to e)ercise 1: D?
@include Istdio.hJ
@include Istdlib.hJ
@include Istring.hJ
@include Ialloc.hJ
struct lle
A
char $alue _10` H
struct lle D pH
BH
?D functions #ill be gi$en pointer to head of list D?
?D functions #ill return pointer to head of list D?
struct lle D addQite5struct lle D6H
struct lle D deleteQite5struct lle D6H
?D function accepts pointer to head of list and returns nothing D?
$oid printQlist 5struct lle D6H
ain56
A
int choiceH
struct lle D hptr M <;RRH
for 5 H H 6
A
printf5FKn&o you #ant to KnF6H
printf5Fl add an iteKnF6H
printf5F2 delete an iteKnF6H
222
printf5F2 print listKnF6H
printf 5F3 0uitKn,6H
scanf5FNiF,[choice6 H
s#itch5choice6
A
case 1'
hptr M addQite 5hptr6 H
breakH
case 2'
hptr M deleteQite5hptr6H
breakH
case 2'
printQlist 5hptr6 H
breakH
case 3'
printf 5F1ood!byeKnF6 H
e)it5l6 H
default'
printf 5F1ood!byeKnF6 H
e)i t 5!16 H
B
B ?D end fore$er loop D?
B ?D end ain D?
struct lle D addQite5struct lle D ptr6
A
char
#ord_40`
H
struct lle D
223
tpH
struct lle D originalQhead M ptrH
printf5F-nter string to enterKnF6H
scanf 5+Ns,, [#ord _0` 6 H
#hile 5 strlen5#ord6 J 20 6
A
printf5F.ord too long, 20 chars a)KnF6H
scanf5+NsF,[#ord_0`6 H
B
?D is the list currently eptyY D?
if 5 ptr MM <;RR 6
A
?D #e are at the head of the list D?
?D get ore eory D?
tp M 5struct lle D 6 alloc si(eof5struct lle6 6H
?D ake sure the alloc #orked D?
if 5 tp MM <;RR 6
A
printf5Falloc
failedKnF6H
e)i t 5! 26 H
B
?D assign $alue and pointer D?
strcpy5tp!J$alue,#ord6 H
tp!Jp M <;RRH
?D return ne# head of list D?
return 5 tp 6H
B
224
?D tra$erse the list D?
#hile 5 ptr!Jp GM
<;RR6
A
ptr M ptr!JpH
B
?D at this point in tie, ptr is at the end of the list D?
?D get ore eory D?
tp M 5struct lle D 6 alloc 5 si(eof5struct lle6 6H
?D ake sure the alloc #orked D?
if 5 tp MM <;RR 6
A
printf5Falloc
failedKnF6H
e)i t 5! 26 H
B
?D add ne#ly created tail ite to list D?
ptr!Jp M tpH
strcpy5tp!J$alue,#ord6 H
tp!Jp M <;RRH
return 5originalQhead6 H
B
struct lle D deleteQite5struct lle D ptr6
A
char #ord_40`H
struct lle D plH
struct lle D tpH
?D is there anything %n the listY D?
if 5 ptr MM <;RR 6
225
A
printf5+There are no ites in listKnF6H
?D return that list is still epty D?
return 5<;RR6 H
B
printf5F-nter string to deleteKnF6H
scanf 5+Ns,, [#ord _0`6 H
#hile 5 strlen5#ord6 J 20 6
A
printf 5+.ord too long, 20 chars a)Kn,6 H
scanf5+NsF,[#ord_0`6 H
B
?D is it at the head of the listY D?
if strcp5ptr!J$alue,#ord6 MM 06
A
?D it is at the head of the list D?
?D is this a singletonY D?
if 5 ptr!Jp MM <;RR6
A
?D gi$e the eory back D?
free 5ptr6 H
?D list is no# epty D?
return 5<;RR6 H
B
else
A
?D return the pointer field of the head as the ne# head D?
tp M ptr!JpH
free 5ptr6 H
return 5tp6 H
?D tra$erse list to find ite D?
226
tp M ptrH ?D sa$e the head of the list D?
pl M ptrH ?D sa$e the current position D?
ptr M ptr!JpH ?D get the ne)t position D?
#hile 5 ptr GM <;RR 6
A
if 5 strcp5ptr!J$alue,#ord6 MM 0 6
A
?D delete the ite D?
pl!Jp M ptr!JpH
free 5ptr6 H ?D gi$e the eory back D?
return 5tp6 H ?D return original pointer D?
B
ptr M ptr!JpH
p1 M p1!JpH
B
?D if #e got here then the #ord #as not in the list D?
printf5+%te not in list Kn,6H
return5tp6H ?D return original head D
B
$oid printQlist 5struct lle D ptr6
A
if 5 ptr MM <;RR 6
A
printf5Flist is eptyKnF6H
returnH
B
?D tra$erse the list printing things as you go D?
#hile 5 ptr GM <;RR6
A
printf 5FNs F, ptr!J$alue6H
ptr M ptr!JpH
227
B
returnH
B
228
rogD<.c getchar L utchar
?D progra to read and echo characters until D ?
?D end of file 5-LP6 is encountered D?
?D t#o #ays to run this progra D?
?D 1' run it fro the terinal prog87 D?
/* type in your input, press control d for -LP D?
?D 2' run it fro the terinal prog87 I input file D?
?D pro$ide the nae of an input file and redirect D ?
?D the input to coe fro that file using ;<%= stdin D?
?D #hen -LP is encountered, progra #ill terinate D?
?D you donCt need to put any special -LP character
in the data file, syste #ill figure it out D?
@include Istdio.hJ
ain 5 6
A
?D e$en though #e are reading in characters D?
?D #e need c to be declared as an int because getchar returns an int D ?
int cH
c M getchar5 6H
#hile 5c GM -LP6
A
?D echo the input character to stdout D?
putchar5c6H
/* get the ne)t char fro stdin D?
c M getchar5 6H
B
B
229
rogDD.c foen) frintf) fclose) getc) utc
?D progra to copy one file to another D ?
?D and that cleans up after itself, not counting on the
os D?
@define P%R-<>W-Q/%T- 30
@include Istdio.hJ
ain 5 6
A
char source_P%R-<>W-Q/%T-`, dest_P%R-<>W-Q/%T-`H
P%R- Din, DoutH
int cH
int charQcount M 0H
printf5F-nter source file nae'F6H
scanf5FN2:sF, source6H
printf5tCOou entered Ns as file to copy froKnF,source6H
in M fopen5source,FrF6H
if 5 in MM <;RR 6
A
printf5FCannot open Ns KnF,source6H
e)it5!16H
B
printf5F-nter dest filenae' F6H
scanf5FN2:sF, dest6H
printf5FOou entered Ns as file to createKnF,dest6H
out M fopen5dest,F#F6H
if 5out MM <;RR6
A
printf5FCannot open Ns KnF,dest6H
fclose5in6H
e)it5!26H
230
B
?D #rite the nae of the source file as first line in output file D?
fprintf5out,F/L;UC- P%R- <>W- .>/ NsKnF,source6H
?D #rite the nae of the source file as first line in output file D?
fprintf5out,F&est P%R- <>W- .>/ NsKnF,dest6H
c M getc5in6H
#hile 5c GM -LP6
A
charQcountVVH
putc5c,out6H
c M getc5in6H
B
fprintf5out,F/L;UC- P%R- ">& Ni C">U>CT-U/KnF,charQcount6H
printf5FPile copy coplete KnF6H
?D close the files e)plicitly D?
fclose5in6H
fclose5 out6H
B
-nter nae of file to be copied' prog83.dat
Oou entered prog83.dat as file to copy fro
-nter nae of output file' out.1
Oou entered out.l as file to create
Pile copy coplete
cat out.l
/L;UC- P%R- <>W- .>/ prog83.dat
&est P%R- <>W- .>/ out.1
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
/L;UC- P%R- ">& 220 C">U>CT-U/
231
uit.c
This rogram sho!s file i=o and string rocessing
The inut and outut files are sho!n belo!
5f you can follo! this code) you have mastered the material to this oint
Lpen a flat data file, create t#o seperate files
one flat file for further fi)ed si(ed
processing
one space deliited file for nueric
processing
@include Istdio.hJ
@include Istdlib.hJ
ain5 6
A
int ia, il , i2H
double )bid, )offerH
char type_2`H ?D three character field for type of transaction D?
char tep_20`H ?D 20 character field for teporary string operations D?
?D read directly into here using fi)ed si(es fro file D?
struct A
char
transact_l`H
char
cusip_9`H
char date_9`H
char bid_10`H
char offer_ 10`H
char lnuber_4`H
char lsybol_7`H
char nae_20`H
char isc_9`H
char crH
232
B recH
P%R- Dfp l, Dfp2, Dfp2H ?D file pointers for reading fro and #riting to
D?
int )H
?D /T>UT LP -=-C;T>*R- CL&- D?
il M 0H i2 M 0H
?D open the price.file for reading D?
if 5 5fpl M fopen5Fprice.fileF,FrF6 6 M <;RR6
A
printf 5FC>< <LT open input file 5price.file 6 KnF6H
e)it51006H
B

?D open the pricedadd.input file for #riting, if it e)ists o$er#rite it D?
if 5 5fp2 M fopen5Fpriceadd.inputF,F#F6 6 MM <;RR6 A
printf 5FC>< <LT open output file
5priceadd.input6 KnF6H
e)it52006H B
?D open the priceupd.input file for #riting, if it e)ists
o$er#rite it D?
if 5 5fp2 M fopen5Fpriceupd.inputF,F#F6 6 MM <;RR6A
printf 5FC>< <LT open output file 5priceupd.input6 KnF6H
e)it52006H B
?D read in 97 data characters and one carriage return fro file D?
?D pointer to destination, si(e of each thing to be read 5 in bytes6
count of things to be read, file pointer of file to be read fro D ?
) M fread5char D6[rec,1,98,fpl6H
?D #hile not end of file D?
#hile5 Gfeof5fpl6 6
233
A
rec.cr M CK0CH ?D con$ert the carriage return to a null D?
printf5FNs KnF,[rec6H ?D print out the #hole record D?
printf5FNc KnF ,rec. transact_0`6' ?D stdout is standard output strea D?
f#rite5[rec.cusip_0`, 1,9,stdout6H ?D print out each field, one per line D?
putc5CKnC ,stdout6H ?D add a lf to the output strea D?
f#rite5[rec.date_0`, 1,9,stdout6H
putc5CKnC ,stdout6H
f#rite5[rec.bid_0`,l, 10,stdout6H
putc5CKnC ,stdout6H
f#rite5[rec.offer_0`, 1, 10,stdout6H
putc5CKnC ,stdout6H
f#rite5[rec.lnuber_0`,1,4,stdout6H
putc5CKnC ,stdout6H
f#rite5[rec.lsybol_0`,1,7,stdout6H
putc5CKnC ,stdout6H
f#rite5[rec.nae_0`,1,20,stdout6H
putc5CKnC .stdout6H
putc5CKnC ,stdout6H
if 5 rec.transact_0` MM C>C6
A
i1 M i1 V 1H ?D add one to i1 D?
type_0` M rec.lsybol_0`H ?Dtransfer lsybol to type D?
type_1` M rec.lsybol_l`H
type_2` M rec.lsybo1_2`H
?D builld up the output file for adds, no deliiters D?
f#rite5 [rec.cusip_0`, 1 ,9,fp26H
f#rite5[rec.date_0`,1,9,fp26H
f#rite5[rec.date_0`,1,9,fp26H
f#rite5[rec.lnuber_0`, 1,4,fp26H
f#rite5[rec.lsybol_0`,1,7,fp26H
234
f#rite5[type_0`,1,2,fp26H
f#rite5[rec.nae_0`,1,20,fp26H
/* stick a carriage return on the end of output
record*/
putc5CKnC ,fp26H
B
235
if 5 rec.transact_0` MM C;C6
A
i2 M i2 V 1H ?D add one to i2 */
strncpy5[tep_0` ,[rec.bid_0`, 106H ?D transfer bid to tep D?
tep_10` M CK0CH ?D tack on a null D?
)bid M atof5tep6H ?D con$ert to float D?
)bid M )bid ? 100000#
strncpy5[tep_0`,[rec.offer_0`,106H /* transfer offer to tep D?
tep_10` M CK0CH /* tack on a null D?
)offer M atof5tep6H /* con$ert to float D?
)offer M )offer ? $%%%%%#
/* build up output file for updates, space deliiters */
f#rite5[rec.cusip_0`, 1,9,fp26H
putc5C C,fp26H
f#rite5[rec.date_0`,1,9,fp26H
putc5C C,fp26H
fprintf5fp2,FN10.4f N10.4fKnF,)bid,)offer6H
B
/* get the ne)t record */
fread55char D6[rec,1,98,fpl6H
/* end #hile */
printf5Fi1 M NdKnF,i16H
printf5Fi2 M NdKnF,i26H
fclose5fp16H
fclose5fp26H
fclose5fp26H
B

236
price.file used for inut
)459145 10199303080094868000009780300094C*9AAC+llI,-' A)S$.ALIAN *+LLA. ,+N* oooooooo
A459145 101 99303080094868000009780300094C*9AAC+llI, -' A)S$.ALIAN *+LLA. ,+N* oooooooo
)4591453019930308010S5550000109101000962-3ACC026I,-' /)L$IC)..ENC0 SE.IES 026 oooooooo
)L1LA2l)1 1 9930308345454545454545A267ACC8011S$ S)88LE/EN$AL INC.EASE -+. oooooooo
)*L767L61 1 99303080000000000000001*L1ACC8022N* S)88LE/EN$AL *E8+SI$ -+. oooooooo
)62623222199303080109450000011509800094,73AL/L37/)N IN9 $. -* 37 AL oooooooo
:)62623233199303080086177000009110700094,81AL/L36/)N IN9 $. -* 36 AL oooooooo
)62623263199303080089970000009460900094*64AL/L3N/)N IN9 $. -* 3N AL oooooooo
)62623L391993030801 07348000011 268200094*N2AL/L39/)N ;N0 $. -* 39 AL oooooooo
)62623L58199303080109610000011564800094*87AL/L30/)N IN9 $. -* 30 AL oooooooo
)62623/40199303080111100000011624100094*<IAL/I:A1/)N IN9 $. -* 41 AL oooooooo
)62623N79199303080109647000011466300094*59AL/lA</)N IN9 $. -* 4< AL oooooooo
)4591452019930308009543500000968890009*,L+A/L++lI,- -S$ C$S A)S$: -1N 7L*. 1=E00000000
)4591452319930308009537300000968260009*,LlA/L++2I,- -S$ C$S A)S$>2-1N 7L*. 1=E00000000
)4591452519930308009738400000988670009*,L2A/L++3A)SSIE /+2I?1A1ELIN2 SE.IES 3 oooooooo
)62623.71199303080105325000011131600094652A/$001/)N IN9 $. -* A/$ 001 /8S oooooooo
)62623$26199303080105287000011077500094653A/$++2/)N IN9 $. -* A/$ 002 /8S oooooooo
)62623$S4199303080099206000010497700094654A/$003/)N IN9 $. -* A/$ 003 /8S oooooooo
)62623$65 199303080091926000009719400094655A/$++4/)N IN9 $. -* A/$ 004 /8S oooooooo
)62623)l 71993030801 09282000011 539800094656A/$++S/)N IN9 $. -* A/$ 005 /8S oooooooo
)62623)19199303080095965000010145200094657A/$++6/ $. -* A/$ 006 /8S oooooooo
)62623)49199303080107253000011349500094658A/$++7/I$. -* A/$ 007 /8S oooooooo
)62623945199303080107109000011333400094659A/$008/I$. -* A/$ 008 /8S oooooooo
)62623953199303080105878000011180000094660A/$++9/I$. -* A/$ 009 /8S oooooooo
)62623980199303080108501000011462600094661A/$+I0/I$. -* A/$ 010 /8S oooooooo
)62623984199303080088507000009342300094662A/$011/I$. -* A/$ 011 /8S oooooooo
)62623985199303080106821000011285700094663A/$+I212$7 A/$ SE.IES oooooooo
)62623<851993030801 063980000 11253200094664A/$+ 1313$7 A/$ SE.IES oooooooo
)62623@20199303080107965000011424500094665A/$+I4/I$- 14$7 A/$ oooooooo
)62623@I9199303080107774000011404000094666A/$+I5/I$- 15$7 A/$ oooooooo
237
riceadd.inut created by uit.c
45914510199303081993030894C*9AAC+llAACI,-'A)S$.ALlAN*+LLA.,+N*
riceud.inut created by uit.c
45914510 19930308 948:68000 978:03000
4591453019930308 1055:55000 1091:01000
L1LA2761 19930308 0:00000 0:00000
*L7:67L61 19930308 0:00000 0:00000
62623222 19930308 1094:50000 1150:98000
6262323319930308 861:77000 911:07000
6262326319930308 899:70000 946:09000
62623L39 19930308 1073:48000 1126:82000
62623L58 19930308 1096:10000 1156:48000
62623/40 19930308 1111:00000 1162:41000
62623N79 19930308 1096:47000 1146:63000
4591452019930308 954:35000 968:89000
45914523 19930308 953:73000 968:26000
45914525 19930308 973:84000 988:67000
62623.71 19930308 1053:25000 1113:16000
62623$26 19930308 1052:87000 1107:75000
62623$54 19930308 992:06000 1049:77000
62623$65 19930308 919:26000 971:94000
62623)17 19930308 1092:82000 1153:98000
62623)19 19930308 959:65000 1014:52000
62623)49 19930308 1072:53000 1134:95000
62623945 19930308 1071:09000 1133:34000
62623953 19930308 1058:78000 1118:00000
62623980 19930308 1085:01000 1146:26000
62623984 19930308 885:07000 934:23000
62623985 19930308 1068:21000 1128:57000
62623<85 19930308 1063:98000 1125:32000
62623@20 19930308 1079:65000 1142:45000
62623@19 19930308 1077:74000 1140:40000
238
argtest.c
?D progra to access coand line arguents D ?
@include Istdio.hJ
?D $oid ain5int argc, char D arg$_`6 ></% $ersion D?
ain 5 argc, arg$ 6 ?D K [ U $ersion D?
int argcH ?D count of the nuber of coands on the coand line D?
char D arg$_`H ?D the arguents as strings D?
A
int i M 0H
printf5F>rg count argc MJ NiKnF,argc6H
printf5FCoand line args are KnF6H
?D #hile 5arg$_i` 6 also #orks D?
#hile 5arg$_i` GM <;RR 6
A
printf5Farg$_Ni` MJ NsKnF,i,arg$_i`6H
iVVH
B
e)it506H
B
run this progra by typing'
a.out
a.out 1 2 2
a.out dog cat bird hello kitty
and see #hat output you get
itdll e)plain argc and arg$ copletely
239
argc) argv) env
argc count of arguments on command line
argv array of strings) arsed command line
env array of strings) arsed environment
e7'+ filel file+
argc
,
argv
e7'+ JF
filel JF
file+ JF
null
240
envtest.c C 5nterface to 125U /nvironment
/* progra to access coand line arguents, progra to access en$ironent $ariables
D?
@include Istdio.hJ
ain 5 argc, arg$, en$p 6
int argcH
char D arg$_`H
char D en$p _`H
A
int en$ Qcount M 0H
#hile 5 en$p_en$ Qcount` GM
<;RR6
A
printf5FNsKnF ,en$p_en$
Qcount`6H
en$ QcountVVH
B
e)it506H
B
&%/PR>OM'L
&/Z;-UOM/O*>/-
PL<TP>T"M?usr?open#in?lib?fonts
PU>W-*;PP-UM?de$?fb
"-RPP>T"M?usr?open#in?lib?help
"LW-M?usr?jtk
R& QR%*U>UO QP>T"M?usr?open#in?lib
RL1<>W-Mjtk
W><P>T"M?usr?open#in?share?an'?usr?an
<-.//-US-UM2348 78237: .2000Hspd21
LP-<.%<"LW-M?usr?open#in
P>T"M?usr?jtk?bin'?usr?open#in?bin?)$ie#'?usr?open
#in?bin'
?usr?local?bin'?usr?local?lang'?usr?local?sybase
?bin'
?usr?uc b'?usr ?bin'?usr?etc'. '?usr?4bin
P.&M?usr?local?jtk?jtk?C?yCprogras
/"-RRM?bin?csh
/O*>/-M?usr?local?sybase
T-UWMsun
;/-UMjtk
.%<&L. QP>U-<TM?de$?#inL
.W1UQ-<S QPR>C-"LR&-UM?de$?#in2
=>PPRU-/ & %UM?usr?open#in?lib?= 11?app!defaults
T-UWC>PMsun!cd'teMK-_J3h'tiMK-_J3l'tcMsun'
241
e7ercise +F
?D #rite a C progra that #ill copy one file to another file D?
?D the user should enter the file naes fro the coand line D?
?D optional brain teaser D ?
?D allo# the user to enter file naes fro the coand line LU
if they donCt put any file naes on the coand line
propt the for the file naes D?
?D optional brain buster D?
?D allo# the user to copy one file to ultiple files siultaneously D?
?D is there a liit to ho# any output files they can createYYY D?

242
sol+F.c
@include Istdlib.hJ
@include Istdio.hJ
?D argc is count of nuber of coand line arguents D?
?D arg$ is array of strings each string is one of the coand line arguents D?
$oid doQcopy5char D s, char D d6
A
P%R- D in, DoutH
int cH
in M fopen5s,FrF6H
if 5in MM <;RR6
A
printf5FCannot open Ns KnF,s6H
e)it5!l6H
B
out M fopen5d,F#F6H
if 5 out MM <;RR6
A
printf5FCannot open Ns KnF,d6H
e)it5!26H
B
#hile 5 5 c M getc5in6 GM -LP 6
putc5c,out6H
fclose5in6H
fclose5out6H
B
int ain5int argc, char D arg$_` 6
A
int iH
char dest_20`,source_20`H
if 5 argc MM 1 6
A
243
printf5FPlease enter source filenae KnF6H
scanf5FNsF, source6H
printf5FPlease enter dest filenae KnF6H
scanf5FNsF .dest6H
B
else if 5 argc MM 2 6
A
strcpy5source,arg$_l`6H
printf5FPlease enter dest filenae KnF6H
scanf5FNsF ,dest6H
B
if 5 argc JM 2 6
A
for 5 i M 2H i I argcH iVV 6
A
doQcopy5arg$_1`,arg$_i`6H
B
else
do Q copy5 source,dest6H
printf5FPile copy coplete KnF6H
B
244
rogD8.c Storage Xualifiers register) const)volatile
?D progra to introduce storage 0ualifiers D?
ain 5 6
A
?D i #ill be local to this routine D ?
?D it #ill be on the stack if there is roo D ?
?D other#ise it #ill be in data area of routine D?
int iH
?D buffer #ill be local to this routine D?
?D it #ill be on the stack if there is roo D?
?D other#ise it #ill be in data area of routine D?
?D this declaration autoatically consues 90 bytes of data D?
char buffer_90`H
?D bQptr is local to this routine D?
?D it can point to a string of arbitrary length D?
?D it consues only si(eof5char D 6 D?
?D the area holding the string #ill be anaged by the
syste, perhaps being dynaically allocated
and deallocated as space re0uireents change D?
char D bQptrH
?D #ant these $ariables in registers if possible D?
?D perhaps i #ill be used as a loop counter D?
?D putting it in a register #ill produce faster e)ecution D?
register int iH
?D te)tQpointer #ill be used in repeated string
operations, putting it in a register
#ill speed e)ecution D ?
register char D te)t pointerH
245
?D #ant these $ariables in read only eory D?
/* #ant to ake sure their $alue doesnCt change D?
?D during e)ecution of progra D?
?D they #ill not be on the stack D?
?D they are local to this routine D?
const double pi M 2.1314:2743H
const char Dcp M [buffer_0`H

/* #ant to pre$ent copiler fro reo$ing D?
/* optii(ations of code D ?
/* if % did not ha$e the $olatile key#ord here, the
copiler #ould reo$e the second stateent
sho#n at location > belo# D ?
$olatile char D out portH
/* assign initial address to te)t pointer D?
?D it no# points to the (eroeth byte of the character array buffer D ?
te)t pointer M [buffer_0`H
?D i and te)t pointer are in registers D?
?D faster e)ecution D?
for 5 i M 0H i I 90H iVV 6
Dte)tQpointerVV M 0)00H
246
?D RLC>T%L< > D?
?D this is code that is typical in de$ice dri$ers
of counication soft#are, you #ant to #rite
to bytes in a ro# to soe chip through its port address D ?
?D an optii(ing copiler #ould think that you
changed the $alue at outport to L)La and
then changed it to L)Ld, thus the first
stateent changing it to L)La has no $alue,
therefore an optii(ing copiler #ould reo$e the
first stateent fro the e)ecutable D?
?D the copiler #ould think that the first D?
?D assignent is useless and #ould optii(e D?
?D it out of the code D?
?D the $olatile pre$ents this D?
?D if out port #as assigned to col port L)2f9 D?
?D and % said D?
/* DoutQport M L)LaH D?
/* DoutQport M L)LdH D?
B
247
seedl.c Tyical 5nefficient Code
?D deonstrates soe FusualF 5and inefficient6 #ays things are done D?
@ifdef /P--& 1
ain 5 6
A
int k.l'
char buffer_2001`H
for 5 k M 0H k I 10000H kVV 6
A
for 5 l M 0H l I 2000H lVV 6
A
buffer_l` M 0)00H
B
B
B
?D tie to run 1:.3u L.Ls 0' 1: ::N 0V122k LVLio LpfVL# D?
@endif
?D copare the run tie statistics for /P--&1 to /P--&2 5on ne)t page 6 D?
248
@ifdef /P--&2
?D speed2.c D?
/* deonstrates FfasterF #ay things are done by ore e)perienced prograers D?
ain 5 6
A
register int kH
register int iH
register char D bQptrH
char buffer_200 1`H
for 5k M 0H k I 10000H kVV6
A
bQptr M [buffer_0`H
for 5i M 0H i I 2000H iVV 6
A
DbQptrVV M 0)00H
B
B
B
@endif
13.7u 0.0s 0'13 ::N 0V122k LVLio LpfVL#
12.2u 0.0s 0' 12 ::N 0V 122k LVLio LpfVL#
10.0u 0.0s 0'10 ::N 0V 122k LVLio LpfVL#
8.7u 0.0s 0'09 ::N 0V 122k LVLio LpfVL#

249
rog<..c coying strings using ointers
?D prog73.c copying strings using pointers D?
?D this routine uses a pointer to specify #here the data coes fro
and a pointer to specify #here the data is supposed to end up
it also uses pointer arithetic in the copying loop,
it has an inefficiency' #hose correction is sho#n
the test Dfro GM CK0C is unneccessary
D?
$oid copyQl 5to, fro6
char Dto, DfroH
A
for 5 H Dfro GM CK0CH froVV, toVV 6
Dto M DfroH
Dto M CK0CH
B
?D copying strings using pointers is ost efficient ethod
effecti$ely uses pointer arithetic and iplied tests D?
$oid copyQ2 5 to, fro 6
char Dto, DfroH
A
?D reeber C is an e)pression language and each stateent
returns a $alue. %n this case, #e can use that
$alue to ake our code ore concise D?
@if 0
#hile 5 Dfro 6
DtoVV M DfroVVH
Dto M CK0CH
@endif
#hile 5 DtoVV M DfroVV 6 H
char s 1 _` M FTerrill L#ensFH
char s2_30`H char s2_30`H
250
char s3_30`H char s4_30`H
char s7_ 30`H
ain5 6
A
printf5Fsl initially is NsKnF,sl6H
copyQl5s2,sl6H
printf5Fs2 is no# NsKnF ,s26H
printf5Fs2 initially is NsKnF,s26H
copyQ1 5s2,FC Prograing is Totally TubularF6H
printf5Fs2 no# is NsKnF,s26H
printf5Fs3 initially is NsKnF,s36H
copyQ25s3,sl6H
printf5Fs3 no# is NsKnF,s36H
printf5Fs4 initially is NsKnF,s46H
copyQ25s4,FC Prograing is Totally TubularF6H
printf5Fs4 no# is NsKnF ,s46H
printf5Fsl MJ Ns s7 MJ Ns KnF,sl,s76H
strcpy5s7,s 16H
printf5Fsl MJ Ns s7 MJ Ns KnF,sl,s76H
B
sl initially is Terrill L#ens
s2 is no# Terrill L#ens
s2 initially is
s2 no# is C Prograing is Totally Tubular
s3 initially is
s3 no# is Terrill L#ens
s4 initially is
s4 no# is C Prograing is Totally Tubular
s 1 MJ Terrill L#ens s7 MJ
s 1 MJ Terrill L#ens s7 MJ Terrill L#ens
251
/7ercise +'
?D #rite a C function that #ill deterine the length
of a user input string, use pointers and try to ake it
as efficient as possible D?
?D ;se the strlen built!in function to check your #ork D?

Solution 6or /7ercise +'
?D edgar.c D ?
int slength 5 char D string ptr 6
A
char D cptr M stringQptrH
#hile 5 DcptrVV 6H
return 5 cptr ! stringQptr ! 16H
B
ain5 6
A
int slength 5 char D string 6H
printf5FNi F, slength5F 12234F6 6H
printf5FNi F, slength5CCCC66H
printf5FNi F,slength5F12234789:012234789:0 12234F6 6H
printf5CCKnCC6H
B
252
rogD,.c rintf in deth
"o# to print integers
Ni integer base 10
No integer base 9
N) integer base 17
Nu unsigned integer
N) integer base 17, lo#er case
letters
N= integer base 17, upper case
letters
N@) integer base 17, lo#er case letters, leading L)
N@= integer base 17, upper case letters, leading L=
@define PU printf
ain5 6
A
int precH float fH int #H
PU5Flnteger -)aples'KnF6H
PU5CCKtbase 10 Ktbase 9 Ktbase 17Ktunsigned int KnF6H
PU5CCKtNiKtKtNoKtN)KtNuKnKnCC, 122, 122, 122, 1226H
PU5CCKtbase 17KtKtbase17 all capsKtbasel7 #ith leading )Ktbasel7 #ith C>P/ [ =K
nF6H
PU5+KtN)KtKtN=KtKtKtN@=KtKtN@=KnKnF,1008,1008,1008,10086H
PU5CCKtbase 10, signKtbasel0, lead space, base 10 rjust, f# 8,0
fillF6H
PU5+Kt base 10,8 digits in f#KnF6H
PU5CCKtNViKtKtN iKtKtKtN08iKtKtKtKtN .8iKnKnF, 1 ,2,2,36H
PU5FKn/tring -)aples'KnF6H

PU5CCKtpercent s only, string in field si(ed to fitKnF6H
253
PU5FK112234789:012234789:012234789:012234789:012234789:0KnF6H
PU5CCKtNsKnKnCC,CCthe 0uick bro#n fo) juped o$er the la(y dogF6H
PU5CCKtpercent .4s first fi$e chars fro stringKnF6H
PU5CCKt12234789:012234789:012234789:012234789:012234789:0KnF6H
PU5CCKtN.4sKnKnCC,CCthe 0uick bro#n fo) juped o$er the la(y dogF6H
PU5CCKtpercent 20s at least thirty chars fro stringKnF6H
PU5FK11223478 9:012234789:012234789:012234789:0 12234789:0KnF6H
PU5CCKtN20sKnKnCC,CCthe 0uick bro#n fo) juped o$er the la(y dogF6H
PU5CCKtpercent 20.4 s fi$e chars, rjust in a field 20 #ideKnF6H
PU5+Kt12234789:0 12234789:012234789:012234789:01223478 9:0KnF6H
PU5CCKtN20.4sKnKnCC,CCthe 0uick bro#n fo) juped o$er the la(y dogF6H
PU5CCKtpercent ! 20.4 s fi$e chars, ljust in a field 20 #ideKnF6H
PU5+Kt12234789:0 12234789:0 12234789:0 12234789:0 12234789:0KnF6H
PU5CCKtN!20.4sfKnKnCC,CCthe 0uick bro#n fo) juped o$er the la(y dogF6H
254
PU5FPloat -)aples'KnF6H
PU5CCKt8 .2fK1K18 .4fKtKt1.4f of 12234.789:0KnF6H
PU5CCKt KnF6H
PU5CCKtN 8 .2f K1N8 .4fK1N 1.4tKnKnF, 12234.789:0, 12234.789:0,
12234.789:06H
PU5CCKt8 .2fK1K18 .4f.l.4f of 1.2234KnF6H
PU5CCKt KnF6H
PU5CCKtN 8 .2f K1N8 .4fK1N 1.4tKnKnF, 1.2234, 1.2234, 1.22346H
?D special cases #here the precision is an arguent D?
PU5F-nter a floatKnF6H
scanf5FNf, ,[f6H
PU5F-nter nuber of digits after decial to displayKnF6H
scanf5FNiF,[prec6H
PU5FKn...................................F6H
PU5FN.DtKnKnF, prec,f6H
?D special case #here the precision and total field #idth are an arguent D?
PU5F-nter a fioatKnF6H
scanf5FN fC ,[f6H
PU5F-nter nuber of digits after decial to displayKnF6H
scanf5FNiF ,[prec6H
PU5F-nter total field #idth KnF6H
scanf5FNiF,[#6H
PU5F KnF6H
PU5FND. DfKnF, #,prec,f6H
PU5FKnCharacters'KnF6H
PU5F 12234789:012234789:012234789:012234789:012234789:0KnF6H
PU5FNcN2cKnF, C.C, C.C6H
B
255
%<T-1-
U/
NVi print the sign character
N i force a leading space in front of a positi$e
N08i right justified, 8 digit #idth, (ero leading fill
N.8i iniu field #ith 8 digits, right justified, leading (eroes
PRL>T/
N9.2f total field #idth eight, t#o decial positions
N.Df,C,),d6 default field #idth, ) decial positions
ND.Df,,),y,d6 total field #idth ), y decial positions
The /trings
Ns null terinated string
N4s first fi$e characters 5or until deliiter6
N.4s first fi$e characters 5 forget deliiter6
N20.4s fi$e characters, right justified in 20 character field
N!20.4s fi$e characters, left justified in 20 character field

scanf odifiers
Ns read in a string deliited by #s or null
N4s read in up to 4 characters deliited by #s or null
N4s' N4scN4s read in up to 4 characters until ' deliiter
read in up to 4 characters until c deliiter
read in up to 4 characters
N_abc`s read in characters until #s, null or non abc encountered
N_^abc`s read in characters until #s, null or abc encountered
Ni Nc read in integer, consue #s, read in charater
N iNc read in integer, do not consue #s, read in character

256
rogD..c scanf in deth
?D progra to illustrate reading using scanf D?
?D clearly deonstrates the ne)t scanf picking up D?
?D #here the last scanf left off D?
ain 5 6
A
char cH
char s_70`H
int iH
i M scanf5FNcF,[c6H
printf5Fi M Nd c MJ NeKnF,i, c6H
i M scanf5FNsF,s6H
printf5Fi M Nd s MJ NsKnF,i,s6H
i M scanf5FN4sF,s6H
printf5Fi M Nd s MJ NsKnF,i,s6H
i M scanf5FN_abc`F,s6H
printf5Fi M Nd sMJ NsKnF,i,s6H
i M scanf5FN_^abc`F,s6H
printf5Fi M Nd s MJ NsKnF,i,s6H
B
input file'
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
the alphabet abcdefghijklnop0rstu$#)y(
progra output
i M 1 c MJ t
i M 1 s MJ he
i M 1 s MJ alpha
i M 1 s MJ b
i M 1 s MJ et
257
rogD9.c scanf in deth
?D attepts to fi) scanf idiosyncracies D?
ain 5 6
A
char cH char trash_90`H char s_90`H
int iH int jH
char sl_90`H char s2_90`H char s2_90`H
?D read the first character into c D ?
?D read the rest of the line into trash D?
i M scanf5FNcN_^Kn`KnF ,[c,trash6H
printf5Fi M Nd c MJ Nc trash MJ NsKnF,i, c, trash6H
?D clean out both of the buffers D ?
for 5 i M 0H i I 90H iVV 6
A
trash_i` M s_i` M 0)00H
B
i M scanf5FNsN_^Kn`KnF,s,trash6H
printf5Fi M Nd s MJ Ns trash MJ NsKnF,i,s6H
for 5 i M 0H i I 90H iVV 6
A
trash_i` M s_i` M 0)00H
B
i M scanf5FN4sN_ ^Kn`KnF ,s,trash6H
printf5Fi M Nd s MJ Ns trash MJ NsKnF,i,s6H
for 5 i M 0H i I 90H iVV 6
A
trash_i` M s_i` M 0)00H
B
258
i M scanf5FN_abc`N_^Kn`KnF,s,trash6H
printf5Fi M Nd sMJ Ns trash MJ NsKnF,i,s6H
for 5 i M 0H i I 90H iVV 6
A
trash_i` M s_i` M 0)00H
B
i M scanf5FN_^abc`N_^Kn`KnF,s,trash6H
printf5Fi M Nd s MJ Ns trash MJ NsKnF,i,s6H

?D read the line as three #hite space separated strings D?
i M scanf5FNs Ns NsF,sl,s2,s26H
printf5Fsl MJ NsKnF,sl6H
printf5Fs2 MJ NsKnF,s26H
printf5Fs2 MJ NsKnF,s26H
B
259
input file
Pile %nput Pointer
the alphabet abcdefghijk1nop0rstu$#)y(
the alphabet abcdefghijk1nop0rstu$#)y(
the alphabet abcdefghijk1nop0rstu$#)y(
the alphabet abcdefghijk1nop0rstu$#)y(
the alphabet abcdefghijk1nop0rstu$#)y(
the alphabet abcdefghijk1nop0rstu$#)y(
the alphabet abcdefghijk1nop0rstu$#)y(
the alphabet abcdefghijk1nop0rstu$#)y(
saple output
i M 2 c MJ t trash MJ he alphabet abcdefghijklnop0rstu$#)y(
i M 2 s MJ the trash MJ alphabet abcdefghijklnop0rstu$#)y(
i M 2 s MJ the trash MJ alphabet abcdefghijklnop0rstu$#)y(
i M 0 sMJ trash MJ
i M 2 s MJ the trash MJ alphabet abcdefghijklnop0rstu$#)y(
sl MJ the
s2 MJ alphabet
s2 MJ abcdefghijklnop0rstu$#)y(
260
Samle Run :5llustrates logical oerations;
>nding things together
>nd of
10001111
00000011
00000011
Lring things together
Lr of
10001111
00000011
10001111
=oring things together
=or of
10001111
00000011
10001100
LneCs copleenting things
LneCs copleent of
10001111
01110000
LneCs copleent of
00000011
11111100

261
rog<D.c $it %erations
?D and [ D?
?D inclusi$e or ] D?
?D e)clusi$e or ^ D?
?D ones copleent a D?
?D left shift I I D?
?D right shift JJ D?

dis&binary:c;
char cH
A
int iH
for 5 i M 0H i I 9H iVV 6
A
if 5c [ 0)906
printf5F 1 F6H
else
printf5F0F6H
c ? c MM 'H => left shift c by one bit >=
=> the high bit shifted out goes in Ybit bucketZ >=
B
printf5CCKnCC6H
B
262
main : ;
A
char a,b,resultH
printf5F >nding things together KnF6H
printf5F>nd ofKnF6H
a M L)9fH ?D 1000 1111 D?
dispQbinary5a6H
b M L)02H ?D 0000 0011 D?
dispQbinary5b6H
result ? a L bH => if either bit is -ero) result is F >=
dispQbinary5result6H ?D if both bits are one, result is 1 D?
printf5CCKnCC6H

printf5FLring things together KnF6H
printf5FLr ofKnF6H
a M L)9fH ?D 1000 1111 D?
dispQbinary5a6H
b M L)02H ?D 0000 0011 D?
dispQbinary5b6H
result ? a N bH => if either bit is one)
result is one >=
dispQbinary5result6H
printf5CCKnCC6H
printf5F=oring things together KnF6H
printf5F=or ofKnF6H
a M L)9fH ?D 1000 1111 D?
dispQbinary5a6H
b M L)02H ?D 0000 0011 D?
dispQbinary5b6H
result ? a [ bH => if only one bit is one) result is one >=
dispQbinary5result6H
263
printf5CCKnCC6H
printf5FLneCs copleenting things KnF6H
printf5FLneCs copleent ofKnF6H
a M L)9fH ?D 1000 1111 D?
dispQbinary5a6H
a ? \aH => s!itch ' to F) and F to ' >=
dispQbinary5a6H
printf5CCKnCC6H
printf5FLneCs copleent ofKnF6H
b M L)02H ?D 0000 0011 D?
dispQbinary5b6H
b ? \bH
dispQbinary5b6H
printf5CCKnCC6H

264
/7ercise ++
?D #rite a c progra that #ill accept a nuber fro the user
display it in he)adecial forat then
display it in binary forat, one bit at a tie
each bit on a separate line D?

Solution 6or /7ercise ++
?D bits.c D?
?D input a positi$e integer nuber
display it in he)
display it in binary
display it one bit per line, fro high to lo#
for added challenge, lea$e off any leading (eroes
D?
ain5 6
A
int i,),ptrH
int last oneH
int bits_9 D si(eof5)6`H
printf5F-nter nuber KnF6H
scanf5FNiF,[)6H
printf5FNi base 10 0)N) base 17 F,),)6H
for 5 i M 0H i I 9 D si(eof5)6H iVV 6
A
bits_i` M ) [ 5int6 1H
) M ) JJ 1H
if 5 bits_i` MM 1 6
lastone M iH
B
#hile 5 lastQone JM 0 6
printf5FNiF ,bits_lastQone!!`6H
printf5F base 2 KnF6H
B
-nter nu ber
4
4 base 10 0)4 base 17 101 base 2
-nter nuber
128
128 base 10 L)8f base 17 1111111 base 2

265
rogD'.c
8ifdef comiler key!ord conditional comilation
?D progra to illustrate @ifdef D?
?D this progra #ill be copiled and run se$eral ties D?
?D on each copile, % #ill define *-PLU- or >PT-U differently D
?D on each copile, % #ill define *-PLU- or >PT-U differently D?
ain 5 6
A
int iH
int suH
su M LH
for 5 i M 0H i I 10H iVV 6
A
@ifdef *-PLU-
printf5Fbefore addition su M Nd i M Nd KnF,su,i6H
@endif
su M su V iH
@ifdef >PT-U
printf5Fafter addition su M Nd i M Nd KnF,su,i6H
@endif
B
printf5Fsu is Nd KnF,su6H
B
acc Xo prog81 prog81.c
su is 34
acc !& *-PLU- !o prog81 prog81.c
before addition su M 0 i M 0
before addition su M 0 i M 1
before addition su M 1 i M 2
before addition su M 2 i M 2
266
before addition su M 7 i M 3
before addition su M 10 i M 4
before addition su M 14 i M 7
before addition su M 21 i M 8
before addition su M 29 i M 9
before addition su M 27 i M :
su is 34

acc !& *-PLU- !& >Pf-U !o prog81 prog81.c
before addition su M 0 i M 0
after addition su M 0 i M 0
before addition su M 0 i M 1
after addition su M 1 i M 1
before addition su M 1 i M 2
after addition su M 2 i M 2
before addition su M 2 i M 2
after addition su M 7 i M 2
before addition su M 7 i M 3
after addition su M 10 i M 3
before addition su M 10 i M 4
after addition su M 14 i M 4
before addition su M 14 i M 7
after addition su M 21 i M 7
before addition su M 21 i M 8
after addition su M 29 i M 8
before addition su M 29 i M 9
after addition su M 27 i M 9
before addition su M 27 i M :
after addition su M 34 i M :
su is 34
acc !& *efore !& >fter !o prog81 prog81.c
su is 34
267
#endi70 Varning about order of
evaluation
%t is iportant 5critical6 to note that'
Fthe order of e$aluation of sube)pressions in a C e)pression #here the order of
e$aluation is not
defined is not definedF.
This eans that the stateent'
a M b V cH
only iplies that b and c are added and the result stored in a.
.e can ake no guarantee #hich #ill be retrie$ed first , a or b.
%f #e ha$e 2 functions that return integers fl and f2'
int cH
c M f15 6 V f25 6H
#e cannot state #hich function, fl or f2, #ill be
e)ecuted first.
like#ise'
int c M 8H
int aH
a M c V cVVH
a #ill ha$e either the $alue 13 58 V 86 or 14 59V86.
.e cannot state #hich it #ill be and be sure that the ans#er #ill be the sae on all
systes.
int i M :H
printf5FNi NiF, i, VVi6H
#ill print either : 10
or 10 10
this usually does not present any probles, but the prograer should be
a#are of it.
U-CCLWW-<&>T%L<' <-S-U ake a second reference to a $ariable being
odified in the sae e)pression #here the order of e$aluation is undefined. &ennis
Uitchie used to say that Fsuch and such is undefinedF .hat he eant #as, +if you
try to do the undefined thing then the results #ill ost likely be soething other than
268
#hat you e)pected,. Then he #ould sile and say +1arbage %n, 1arbage Lut,, or
soeties just +1%1L,
269
*uicksort.c a *uicksort e7amle
@include Istdio.hJ
@include Iath.hJ
@define W>=Z;%CK 129
int 0uick_W>=Z;%CK` ?D array that holds the data D?
int 0uickinde)H ?D inde) of ho# any eleents there are D?
P%R- D fdH P%R- D fd 1H
ain 5 6
A
$oid printdata5$oid6H
$oid sortdata5int start pos, int endQpos6H
int intepH int cH
fd M fopen5FdatafileF,FrF6H
if 5 fd MM <;RR 6
A
printf5Fopen 1 failed KnF6H
e)it5 !16H
B
fd1 M fopen5F0uickoutF ,F#F6H
if 5fd1 MM <;RR 6
A
printf5Fopen2 failed KnF6H
e)it5 !26H
B
?D input the data fro file D?
0uickinde) M 0H
#hile 5 fscanf5fd, F NdF, [intep6 GM -LP6
A
?D store data in array D?
0uick_0uickinde)VV` M intepH
270
B
0uickinde)!!H
?D print original list of data D?
printf5FLU%1%<>R R%/TKnF6H
printdata5 6H
printf5CCKnKnCC6H
sortdata50,0uickinde)6H

printdata5 6H
close5fd6H close5fdl6H
B
$oid
printdata5$oid
6
A
int iH
fprintf5fd 1 ,,KnKn,6H
for 5 i M 0H i IM 0uickinde)H iVV 6
A
printf5F Nd F,0uick_i`6H
fprintf5fd 1, F Nd F,0uick_i`6H
B
printf5FKnKnF6H
fprintf5fd1,,?n,6H
returnH
B ?D end printdata
D ?
271
@define ;P 0
@define &L.< 1
$oid sortdata5int startQpos, int endQpos6
A
int tepH
int targetQposH
int direction M &L.<H
int inQendQposH
int inQstartQposH
int tepQlo#er, tepQupperH
inQstartQpos M startQposH
inQendQpos M endQposH
target pos M startQposH
tepQlo#er M startQposH
tepQupper M endQposH
printf5F/LUT&>T> Ni Ni KnF,startQpos,endQpos6H
printdata5 6H
fprintf5fdl,F/LUT&>T> Ni Ni KnF,startQpos,endQpos6H

if 5 startQpos JM endQpos 6
returnH
#hile 5tepQlo#er I tepQupper6
A
if 5direction MM &L.<6
A
if 50uick_tepQupper` JM 0uick_targetQpos` 6
A
?D no update, o$e pointer D?
tepQupper!!H
272
B
else
A
?D s#ap $alues D?
tep M 0uick_tepQupper`H
0uick_tepQupper` M 0uick_targetQpos`H
0uick_targetQpos` M tepH
printdata5 6H
?D change direction of tra$el D?
direction M ;PH
?D change pointer to target $alue D?
targetQpos M tepQupperH
B
B
else ?D direction of tra$el is ;P D?
A
if 5 0uick_tepQlo#er` IM 0uick_targetQpos`6
tep Qlo#erVVH
else
A
?D s#ap $alues D?
tep M 0uick_tepQlo#er`H
0uick_tepQlo#er` M 0uick_targetQpos`H
0uick_targetQpos` M tepH
printdata5 6H
?D change direction of tra$el D?
direction M &L.<H
?D change pointer to target $alue D?
targetQpos M tepQlo#erH
B
B
B ?D end #hile D?
273
?D at this point the left and right pointers ha$e et or crossed D?
?D no# #e ha$e di$ided our list into t#o segents D?
?D sort each of the saller segents D?
?D U-C;U/%L< D?
?D do left side D ?
if 5 inQstartQpos I targetQpos ! 1 6
A
printf5FCalling left side KnF6H
sortdata5inQstartQpos, targetQpos ! 16H
B
?D do the right side D ?
if 5 targetQpos V 1 I inQendQpos 6
A
printf5FCalling right side KnF6H
sortdata5targetpos V 1 ,inQendQpos6H
B
returnH
B ?D end sortdata D ?

274
trtofunc.c Pointers To 6unctions
$oid e)it5 6H
static void roca:fno)al)a+)a,)a.)aS;
int fno,al,a2,a2,a3,a/H
A
int statH
stat M printf5F%n procaKnF6H
if 5 stat MM 0 6
e)it5stat6H
stat M printf5FNi Ni Ni Ni Ni NiKnF,fno,al,a2,a2,a3,a/6H
if 5 stat MM 0 6
e)it5stat6H
B
static void rocb:fno)al)a+)a,)a.)aS;
int fno,al,a2,a2,a3,a/H
A
int statH
stat M printf5F%n procbKnF6H
if 5 stat MM 0 6
e)it5stat6H
stat M printf5FN) N) N) N) N) N)KnF,fno,al,a2,a2,a3,a46H
if 5 stat MM 0 6
e)it5stat6H
B

275
static void rocc:fno)al)a+)a,)a.)a9;
int fno,al,a2,a2,a3,a4H
A
int statH
stat M printf5F%n proccKnF6H
if 5 stat MM 0 6
e)it5stat6H
stat M printf5FN4i N4i N4i N4i N4i N4iKnF,fno,al,a2,a2,a3,a46H
if 5 stat MM 0 6
e)it5stat6H
B
static void
: >rocedure&tableR S; : ; ?
A
p
r
o
c
a
,
p
r
o
c
b
,
p
r
o
c
c
BH
276
int ain 5 6
A
int funcno, arg1, arg2, arg2, arg3, arg4H
int i,statH
funcno M 0H
argl M 100H
arg2 M 200H
arg2 M 200H
arg3 M 300H
arg4 M 400H
stat M printf5F%n ain
routine KnF6H
if 5 stat MM 0 6
e)it5stat6H
#hile 5 funcno GM !1 6
A
stat M printf5,CKn-nter function you #ish to
callKnF6H
if 5 stat MM 0 6
e)it5stat6H
stat M printf5F!
1Kt0uitKnLKtprocaKn1KtprocbKn2KtproccKnF6H
if 5 stat MM 0 6
e)it5stat6H
stat M
scanf5FNiF,[funcno6H
if 5 stat MM 0 6
e)it5stat6H
if 5funcno GM !1 [[ funcno JM 0 [[ funcno
IM 26
277
A
:>rocedure&tableRfuncnoS;
: funcno)argl)arg+)arg,)arg.)arg9;H
B
B ?D end #hile D?
retur
n506H
B ?D end
ain D?
278
#endi70 Reading comle7 declarations0
static void : >rocedure&tableR S 6 5 6 M
procedureQtable is' an array of pointers at functions that return $oid
struct mystruct >struct&ointer&arrayRSH
structQpointerQarray is an array of pointers to structures of type ystruct
struct mystruct :>struct&array&ointer;RSH
structQarray Qpointer is a pointer to an array of structures of type
ystruct
279

#endi7 To $race or 2ot To $race
ain 5 6
A
int )H
printf5F-nter ) KnF6H
scanf5FNiF,[)6H
?D this decision structure is fully braced and indented in the KK style D?
if5 ) I 106
A
printf5F) less than ten KnF6H
B
else if 5 ) J 10 6
A
printf5F) is greater than ten KnF6H
if 5 ) I 100 6
A
printf5F) less than one hundredKnF6H
B
else
A
printf5F) is greater than or e0ual to 100KnF6H
B
else
A
printf5F) is e)actly ten KnF6H
B
?D this decision structure is not braced, indented only in KK style D?
if 5 ) I 10 6
printf5F) less than ten KnF6H
else if 5 ) J 10 6
if 5 ) I 100 6
printf5F) less than one hundredKnF6H
280
else
printf5F) is greater than or e0ual to lC=JKnF6H
else
printf5F) is e)actly ten KnF6H

/* this decision structure reo$es the else fro the nested if
and introduces proble encountered #hen you lea$e off the braces D?
/* the last else belongs to the if 5 ) I 100 6 <LT the if 5) I 106 D?
?D this could ha$e been a$oided by bracing D?
if 5 ) I 106
printf5F) less than ten KnF6H
else if 5 ) J 10 6
if 5 ) I l006
printf5F) less than one hundredKnF6H
else
printf5F) is e)actly ten KnF6H
?D this e)pression is indented and braced in a K[U like ethod D?
?D decide for yourself #hich style is ost readable and W>%<T>%<>*R- D?
if5 ) I 106A
printf5F) less than ten KnF6H B
else if 5 ) J 10 6 A
if 5) I 1006 A
printf5F) less than one hundredKnF6H B
else A
printf5F) is greater than or e0ual to 100KnF6H B B
else A printf5F) is e)actly ten KnF6H B
B
281
-nter ) 4
) less than ten
) less than ten
) less than ten
) less than ten
-nter ) 11
) is greater than ten
) less than one hundred
) less than one hundred
) less than one hundred
) less than one hundred
-nter ) 102
) is greater than ten
) is greater than or e0ual to 100
) is greater than or e0ual to 100
) is e)actl y ten
) is greater than or e0ual to 100
282
<LT-/'
*races #ith only one stateent #ithin the are CfreeC 5no code
o$erhead6.
-)perience has taught that there are ties #hen a single stateent #ithin a loop or
decision structure needs to ha$e a debug stateent added. This eans that you ha$e to
add the braces any#ay. Puting the in as an afterthought ay lead to probles'
if 5 $alue ?? : 6 original code
call function5 6H
if 5 $alue MM : 6
printf5Fif case true calling functionF6H
callQfunction5 6H code #ith debug stateent and added bug
code should look like this
if 5 $alue ?? :6
A
call function5 6H
B
if 5 $alue MM: 6 original code
A
printf5+if case true calling functionF6H
callQfunction5 6H
B
283
#endi7
ain 5 6
A
int i,jH
int )_4` M A 1 , 2 , 2, 3, 4 BH
int y_2`_2` M A A10,20,20B, A100, 200, 200B BH
printf5F>>> KnF6H
for 5 i M 0H i I 4H iVV 6
?D this #orks as youCd e)pect D?
printf5FNi F,)_i`6H
printf5CCKnKnCC6H
printf5F***KnF6H
for 5 iM 0H i I 4H iVV 6
/* T"%/ >R/L .LUK/ GGG D?
?D copiler kno#s i is of type int and ) is of type pointer to int
and it generates the address correctly D?
printf5FNi F,i_)`6H
printf5CCKnKnCC6H
printf5FCCCKnF6H
for 5 i M 0H i I 2H iVV 6
A
for 5 j M 0H j I 2H jVV 6
A
?D this #orks as youCd e)pect D?
printf5FNi F,y_i`_j`6H
B
printf5CCKnCC6H
B
284
285
printf5CCKnKnCC6H
printf5F&&&KnF6
H
for 5 i M 0H i I 2H iVV 6
A
for 5 j M 0H j I 2H jVV 6
A
/* T"%/ >R/L .LUK/ GGG D?
/* copiler kno#s y is of type pointer to pointer to int
and i and j are of type int, figures out address correctly
D?
printf5FNi F,i_y`_j`6'
B
printf5CCKnCC6H
B
printf5FKnKnF6H
@if 0
?D this #ould be a copiler
error D?
printf5F---KnF6H
for 5 i M 0H i I 2H
iVV 6
A
for 5j M 0H j I 2H
jVV 6
A
?D T"%/ #ould not #ork, copiler error % &L<CT K<L.
."O D?
printf5FNi F,i_j` _y`6H
B
printf5CC
KnCC6H
B
@e
ndi
f
B
>>>
12234
***
12234
CCC
10 20 20
100 200 200
286
&&&
10 20 20
100 200 200
287
Cra-y #ddress Stuff
int iH
int array_4`H
for5iM0H iI4H iVV
6
printf5FNi
KnF, array_i`6H
for5iM0H iI4H iVV
6
printf5FNi
KnF, i_array`6H
*oth these loops do the sae thing' print out the contents of the array.
This is because array_i` is copiled as D5arrayVi6 #hich is the sae as D5iVarray6.
.ith a 2 diensional array, the first inde) 5ajor inde)6 is itself an adderss, so in our
e)aple'
int i,jH
int y_2`_2` M A A10,20,20B, A1
00,200,200B BH
for 5 i M 0H i I 2H iVV 6
for 5 j M 0H j I 2H jVV6
printf5FNi F,y_i`
_j`6H
y_i`_j` eans D5 D5yVi6 Vj6 #here i is the offset into the array of ro# addresses
and j is the offset into that ro#
for 5 i M 0H i I 2H iVV 6
for 5 j M 0H j I 2H jVV 6
printf5FNi F,i_y`_j`6H
i_y`_j` eans D5 D5iVy6Vj6 #hich also #orks since it generates the sae address as in
the pre$ious e)aple
288
for 5 i M 0H i I 2H iVV 6
for 5 j M 0H j I 2H jVV 6
printf5FNi F,i_j`_y`6H
i_j`_y` eans D5 D5iVj6 Vy6 #hich results in a copiler error since #e are attepting
to add 2 integers 5i and j6 and then dereference the.
289
#PP/2D5U
/oe terinals donCt ha$e keys for 5haracters that you ay need in a C
progra.
The C language can handle this to a certain e)tent.
The echanis eployed to deal #ith this situation is the trigraph.
The follo#ing three keystrokes, #hen used together #ith no spaces bet#een the,
refer
to the indicated character on their right.
This techni0ue is useful in the 2280 en$iroent because the _ and ` characters
are not
found on the 2280 keyboard.
se*uence
YYM @
YY5 _
YY6 `
??& A
YYJ B
YY? K
YYC ^
YYG ]
??' (
290
A%ter 6$ *ecided 7e ColdnAt <rite +ne /ore 8ro#r!m::::
7e St!rted <ritin# NoBel('
8le!(e Con(ider .e!din# $Ce 8!ttern 5itA( !"ot ! pro#r!mmin# error4
+r Con(ider S!mplin# +tCer( o% 6$ 2!ln!&A( NoBel(


291
292
Reviews for JTs Programming Technothriller The Pattern
The first of JT Kalnay's works I've read, this early effort compares
nicely with Ryan's "Adolescence of P-" or !risham's "The "irm" #$t wisely
navi%ates aro$nd Powers' "!alatea &'&" territory' (o$ %et a %ood sense
this writer has "#een there" #$t there is more to "The Pattern" than )$st an
insider's view of an ind$stry and c$lt$re that is pretty m$ch a #lack #o* to
those that haven't' This one %ets a + o$t of , simply for not -$ite crackin%
the level of the #i% #oys. /lancy, 0$dl$m, /$ssler et al' 1ill #e interested
to see how this a$thor develops in this %enre'
I was s$rprised to en)oy this #ook so m$ch as it comes from a not so
well known a$thor' "antastic fiction'
I was thinkin% a#o$t the 2A0 3444 malf$nction in &44 A 5pace
6dyssey while readin% The Pattern' 7ecades a%o, I wondered if people
wo$ld risk their lives on software' 8ow we have fly-#y-wire controls in o$r
airplanes and we depend on software in o$r hospital e-$ipment as well as
o$r cars' 5oftware %litches can now kill' It's a really scary tho$%ht and I
really en)oyed the thrillin% )o$rney the a$thor takes $s on in this techno-
thriller treat' In the #est spirit of science fiction it %ives $s pa$se to
consider the dependency we freely %ive to o$r technolo%y' In addition, as
this story $nfolds o$r h$manity is laid #are in the face of technolo%ical
realities that are seldom reali9ed #y most of $s'
293
Please :n)oy This 5ample "rom The Pattern
J$ne 3, 33+
/hantilly ;ir%inia
Assem#led "rom 8ews 1ire Reports
A chartered e*ec$tive 0ear Jet in#o$nd from <e*ico /ity crashed today
in heavy fo% d$rin% final approach to 7$lles 8ational Airport in 1ashin%ton
7'/' Ten passen%ers and two crew mem#ers were killed instantly' There
were no Americans on the fli%ht and there were no s$rvivors' Altho$%h the
airplane had the latest electronics, it had a#orted one landin% d$e to the
fo% and was in the process of linin% $p for a second attempt when the
accident occ$rred' The #lack #o* fli%ht recorder has #een recovered from
the wrecka%e and the #odies have #een identified' The last transmission
from the cockpit was, "There seems to #e somethin% wron% with the
electronics' !oin% aro$nd'" The plane disappeared from radar less than
ten seconds later'
J$ne &4, 33+
5an "rancisco, /alifornia
Thin clo$ds drifted hi%h a#ove the city #y the =ay' /rai% and 5tacey sat
#ehind the AP5oft #$ildin% on the lar%e cedar deck' A %entle #ree9e
caressed 5tacey's lon%, s$mmer %olden hair' /rai% was havin% a very hard
time concentratin% on the report in his hands'
"7o yo$ want to hear somethin% weird>" 5tacey asked'
"I don't know' 7o I>" /rai% answered'
"(es' (o$ do," 5tacey said'
"6kay' 0et's have it," /rai% said'
"1e're three for three this year," 5tacey said'
"I don't %et it," /rai% said'
"6n airplane crashes' 1e're three for three'"
"I still don't %et it," /rai% said'
"0isten' "irst yo$ know that %$y in T$rkey where the =lackhawks %ot
shot down' 5econd, we #oth know Rakesh who's #een in 2on% Kon% where
the plane that crashed in 8a%oya ori%inated' Third, my friend in <e*ico
works for that company that chartered that plane that crashed in ;ir%inia
the other day' 1e're three for three'"
"=etter call the 8ational :n-$irer," /rai% said'
"Jerk," 5tacey said'
294
"1e know some#ody at almost every airline or aircraft man$fact$rer in
the world 5tacey' It'd #e a miracle if we didn't know someone somehow
related to every crash," /rai% said'
"(o$'re still a )erk," 5tacey said'
"(eah I know' It's part of my charm," he replied'
5tacey made a face at him and rolled her eyes'
"Please," she said'
"=$t yo$ know what> (o$'ve pi-$ed my c$riosity' I'm %oin% to do some
research and see how many wrecks there have #een in the last year' It
does seem like there's #een an $n$s$al amo$nt doesn't it>" /rai% asked'
"8ice try," 5tacey said'
"8o' I'm totally serio$s' 8ow that yo$'ve pointed it o$t, I really am
c$rio$s'"
"?m h$h," she said dismissively'
"Ready to throw it some more," 5tacey asked, dan%lin% /rai%'s #irthday
"ris#ee on the end of a lon% slender fin%er'
"8ot ri%ht now," /rai% said' I #etter %et started on that research'
http://jtkalnaynovels.wordpress.com/
www.jtkalnay.com
295
6$ 2!ln!& i( !n !ttorne& !nd !n !tCor: 7e C!( "een !n !tClete' !
(oldier' ! pro%e((or' ! pro#r!mmer' !n Ironm!n' !nd mont!in clim"er: 6$ noD
diBide( Ci( time "etDeen "ein# !n !ttorne&' "ein# !n !tCor' !nd Celpin# Ci( Di%e
cC!(e !%ter (eBen niece( !nd nepCeD(:
6$ D!( "orn !nd r!i(ed in ,elleBille' +nt!rio' C!n!d!: 1roDin# p liter!ll& (tep(
%rom tCe ,!& o% Einte' D!ter' ice' %i(Cin#' (Dimmin#' "o!tin#' !nd droDnin# Dere
Ber& e!rl& in%lence( !nd !ppe!r %reFentl& in Ci( Dork:
Edc!ted !t tCe .o&!l /ilit!r& Colle#e' tCe )niBer(it& o% +tt!D!' tCe )niBer(it&
o% *!&ton' !nd C!(e <e(tern .e(erBe )niBer(it&' 6$ C!( (pent contle(( Cor(
(td&in# ! Dide r!n#e o% ("Gect( incldin# m!tC' En#li(C' compter (cience'
pC&(ic(' !nd l!D: /!n& o% Ci( (torie( !re (et on colle#e c!mp(e(: 6$ 5!lon# DitC /C
!nd 2.4 i( one o% tCe %ondin# mem"er( o% tCe Stone -ri#!te /ilit!r& Ac!dem&
En#li(C Societ&:
6$ i( ! certi%ied rock clim"in# #ide !nd c!n o%ten "e %ond !top cr!#( in <e(t
9ir#ini!' C!li%orni!' $ex!(' NeD /exico' NeB!d!' 2entck&' /exico' !nd It!l&: .ock
clim"in# !ppe!r( %reFentl& in Ci( Dritin#:
6$ C!( Ditne((ed %ir(tC!nd m!n& tr!m!tic eBent( incldin# tCe <orld $r!de
Center ,om"in#' tCe Lon# I(l!nd .!ilro!d SCootin#' ! "e!r !tt!ck' ! pl!ne cr!(C'
!nd nmero( %!t!litie(' in tCe mont!in( !nd el(eDCere:
*i(!(ter(' lo((' !nd con%rontin# per(on!l %e!r !re common tCeme( in Ci( Dritin#:
www.jtkalnay.com
296

You might also like