Professional Documents
Culture Documents
88 C Programs
88 C Programs
by JT Kalnay
Published by jt Kalnay
This book is licensed for your personal use. This book "o#e$er, this book ay not be re!sold.
%f you #ould like to share this book #ith another person, please feel free to do so.
the functionality of the ne# syntactic and se antic ele ents. The progra
e that they #ill be able to think of the applicability of the feature to their project. .hen necessary, % pro$ide a sa ple application to gi$e a feel for ho# the ne# ele ent ight be e ployed.
The progra s are presented in an order that presents the si plest, aspect of a ne# ele ent first. /ubse0uent progra s present the
confusing aspects of a ne# ele ent. 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 assu es that you are already a progra your o#n. 1ood luck in your study of C.
Table %f Contents
/i ple.c
si plest C progra ,
ain, progra
entry point
hello#orld.c one printf prog1.c prog2.c prog2.c prog3.c ops.c prog3a.c prog4.c pg23.c prog7.c prog8.c prog9.c ste$e.c prog:a.c prog10.c prog11.c prog12.c prog12.c prog13.c ore printf co ents, case sensiti$ity
$ariable declaration and initiali(ation printf output C operators printf output C data types si(eof5$ar6 operators and precedence i)ed odulus relational operators three types of loops for loop for loop, scanf nested for loops #hile loop #hile loop
5
prog14.c if.c 17.c 1:.c 20.c 21.c errors.c 22.c 22.c 24.c 27.c 28.c 2:.c 20.c 21.c 22.c 22.c 24.c $alref.c 27.c 28.c 29.c sortstep.c
#hile loop, do loop if state ents ath.h logical operators and e)pressions co ple) decision structures s#itch state ent co arrays array boundaries ore array boundaries bo#ling scores, arrays character arrays function declaration and usage calling subroutines passing constants to subroutines passing $ariables to subroutines subroutine returning $alue ultiple files co piled together call by reference, call by $alue passing array to subroutines passing pointer to subroutine sorting array of integers sorting e)a ple
6
on synta) errors
2:.c t#odi .c testarrays.c testarrays1.c prog30.c scope.c 31.c testpop.c 32.c 32.c 34.c 37.c 38.c 39.c 3:.c 40.c 42.c 42.c charlarge.c 44.c 48.c 49.c 4:.c
t#o di ensional array t#o di ensional array to subroutine ore arrays ore arrays static, auto atic, global scope of $ariables recursion stack struct key#ord, structures structures ;<%= ti e.h file >rrays of /tructures structures and arrays strlen strcat strc p getchar gets ctype.h, string functions characters as large integers structures and strings pointers pointers pointers to structures
7
string processing
70.c
$alref.c 87.c 88.c uitp.c argtest.c en$test.c sol20.c 89.c speed1.c speed2.c 73.c 82.c 83.c 84.c 78.c bits.c 81.c 0uicksort.c ptrtofunc.c
pointers and functions getchar, putchar file operations, fopen, fprintf, fclose, getc, putc file i?o and string processing arc, arg$, dealing #ith co and line argu ents
interface to ;<%= en$iron ent argc, arg$ register const storage 0ualifiers inefficiency efficiency copying strings using pointers printf in depth scanf in depth scanf in depth bit operations int octal he) binary display @ifdef conditional co pile 0uicksort pointer e)a ple pointers to functions
Sim le.c
ain 5 6
A B
%t does not need to be in colu n one. ain ay take argu ents. .e #ill deal #ith the later.
The e pty round brackets 5 6 indicate that #e arenCt going to #orry about the argu ent list at this point. > C co ent is enclosed by ?D EE. D?
ain 5 6 ?D progra A
entry point D?
?D start of block, start of scope D? *lock body *lock blody E *lock body
?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 Fsi plest C progra page 20.2 possible' Part %% full ></%G co patabilityF on
hello&!orld.c
>ll C state ents end #ith a se icolon 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?
later D? ?D printf returns a count of the nu ber of characters it displayed D? ?D the count can be ignored D? printf5Fhello #orld KnF6H B
10
11
rogl.c su
?D to co pile #ith ansi co piler #ith defaults acc prog1.c #ill produce a.out if 5o pile is successful no Fsuccess indicatorF is generated if errors, co piler essages #ill be generated
?D to co pile #ith ansi co piler and specify e)ecutableCs na e acc !o progl prog1.c
#ill produce progl if 5o pile is successful D? ?D to pass source code through a $ery picky pre co piler alint progr1.c D? ?D curly brackets ark the beginning and end of the scope of a co pound state ent. ay be a function body, the body of
a loop, the body of a conditional, se$eral state ents D? ?D c is an e)pression language e$ery state ent returns a $alue, #hich ay be discarded or ignored if unneeded D?
12
C Progra
ing
@include Istdio.hJ int A ?D int declares )y( as a $ariable of type integer D? int )y(H ain56
printf D?
ingKn,6H
ingKn,6H
e)it point D?
13
Oou can also co pile other 5e.g., Portran, Pascal6 progra s to produce object files Oou can then link all these together
>CC stands for ></% C co piler >cc na eQofQcQfile produces e)ecutable a.out
.for file
fortran file
Link Editor
.pas file pascal file .cob file CL*LR file Exec t!"le
14
rog+.c
int a in 56 A ?* co
@include Istdio.hJ
ents start #ith slash asterisk can span se$eral lines, and end #ith asterisk slash D? int foobarH ?D $ariable na es are case sensiti$e D? ents are case sensiti$e
?D all C state ents e)cept co int is LK, %<T is not D? /* #hite space is ignored D? printf5+C Progra ingKnF6H
printf5FabcKnF6H printf5FdetKnF6H
?D co
?D the printf5+det Kn,6H state ent #ould not be co piled b?c it is inside a co entG D? Printf5+$alue of foobar is NiKn,,Poobar6H B
Compiler Error
15
"eap
Tero if not e)plicitly initiali(ed Tero if not e)plicitly initiali(ed <one Tero if not e)plicitly initiali(ed
C supports different storage classes that you can force by using e)plicit key#ords.
16
int A
ain5 6
?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 %nt Ploat Char na eQofQ$ariable )H yH cH
na e1, na e2, E H ),y,(H f1 ,f2H c1, c2H ?D first char D ? ?D another char D ?
18
rog..c
?D this progra
@include Istdio.hJ
?D displays the results D? ?D it also de onstrates t#o #ays to initiali(e a $ariable D? int A ?D declare $ariables D? int $ lH int $2H int $su H ?D declare and initiali(e $ariable D? int allQinQone M 4H /* initiali(e $alues D? $ l M 1H $2 M 2H ?D co pute D? $su M $ l V $2H ain5 6
?D display all in one D? printf5FallQinQone MJ Ni KnF,allQinQone6H ?D case sensiti$ity error, #ould not co pile D? ?D printf5FallQinQone MJ Ni KnF,>RRQinQone6H D? ?D printf error D ? print5FallQinQone MJ Ni KnF,allQinQone6H B
19
%n C, all operators ha$e a return $alue and so e ha$e Fside effectsF > return $alue isa $alue gi$en back. Por e)a ple 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 Por e)a ple' int aH aM 8H The assign ent operator 5M6 changes the $alue 8. The assign ent operator also has a return $alue, na ely 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 state ent 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 inter ediate results #hen no longer needed6. Wost co pilers #ould flag a line like 2 V 3H #ith the #arning' F/tate ent has no effectF e ory location #e call CaC to contain the e ory location.
20
o s.c
ain 5 6 A int i.)' i M LH ) M iVVH incre entD?
printf5Fi M Ni ) M Ni KnF,i ,)6H i M0H ) M VViH incre entD? printf5Fi M Ni ) M Ni KnF, i, )6H i M 0H ) M i!!H decre entD? printf5Fi M Ni ) M Ni KnF, i, )6H i M 0H ) M !!iH decre ent D? printf5Fi M Ni ) M Ni KnF, i, )6H /* co pound assign ents' $ar op= $alue is the sa e as $ar M $al op $alue D?
21
i M 4H i VM 2H i M 4H i !M 2H i M 4H i DM 3H i M 20H i ?M 2H i M 24H i NM 8H i N 8D? printf5Fi M Ni KnF,i6H B Sam le %ut ut 6rom o s.c iM 1 ) M L iM1 ) M 1 iM !1 )M L iM !1 )M !1 iM8 iM2 i M 20 i M 10 iM3 ?D od e0uals sa e as i M ?D di$ides e0uals sa e as i M i ?2 D? printf5Fi M Ni KnF,i6H ?D ti es e0uals sa e as i M i D 3 D? printf5Fi M Ni KnF,i6H ?D inus e0uals sa e as i M i ! 2D? printf5Fi M Ni KnF,i6H ?D plus e0uals, add and assign, sa e as i M i V 2 D? printf5Fi M Ni KnF,i6H
22
/7ercise '
?D ake a file na ed )one.c D? to co pute the follo#ing D? ?D #rite a C progra
?D the result of b s0uared ! 3 ti es a ti es c D? ?D #here a is 4, b is 3, c is 2 D? ?D print out the ans#er D ? ?D use $ariables na ed 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
24
/7ercise +
/* fi) this progra by typing it in fro scratch as you go 5let the co piler find the errors6 find the synta) errors and fi) the
until it co piles cleanly and runs cleanly and produces the ans#er 12 D? @include stdio.h ain integer iH do so e iM1V2V2 /* do so e ath i M i V iH print5i M N i6H B /* desired output D? ?D i M7 D? inaccurate docu entation GG Kn, ore ath D ?
25
@include Istdio.hJ ain5 6 A int iH ?D do so e i M 1 V 2 V 2H ?D do so e i M i V iH printf5Fi M Ni KnF, i6H B ?D desired output D ? ?D i M 12 D? ore ath D ? ath D ?
26
Precom iler0
The preco piler 5so eti es called Preprocessor6 is the first step in the co pilation process. %ts purpose is to' 16 re o$e co 26 perfor ents before CrealC co pilation preco piler state ents 5 a!k!a Preprocessor directi$es6
Preco piler state ents start #ith a @ as the first non #hite space character on the line. .e ha$e already seen one' @include Istdio.hJ This state ent asks the preco piler to e bed the file stdio.h into our C file at the place #here the directi$e appears. There are se$eral @ define @if Ist tJ @ifdef Ist tJ @ifndef Ist tJ @else @elseif Ist tJ @endif ore that #e #ill e)a ine' perfor te)t subtitution
if not defined, include the follo#ing code else for any @if else if for any @if end of @if block
27
%f you co pile like this' acc !&>>> prog3a.c and run a.out, you see' hello fro aaa e before % print againGGG .hat you donCt like bbbY define CCC to stop
%f you co pile like this' acc !&>>> !&*** prog3a.c and run a.out, you #ill see hello fro hello fro aaa bbb e before % print againGGG
and run a.out, you #ill see .hat you donCt like bbbY
29
rog9.c
C basic data ty es
/* acc prog4.c !&C>/-1 !o prog4 D? /* acc prog4.c !&C>/-2 !o prog4 D? ain 5 6 A ?* all scalar!$ariables /* progra @ifdef C>/- 1 char c double d float f int i @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 co puter 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 Ty es
To Store # Character %n C a char is just a subtype 5skinny6 integer. .hat #e nor ally think of as a character 5displayable6 is si ply the output to the screen fro so e display function. /o ething like C>C is an integer in C #hose $alue is 74 5>/C%% code for >6. > state ent 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 sa e 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, so e co pilers support 17 bytes6 To Store 1nsigned 5ntegers) 4ogical 3alues and $it #rrays unsigned char unsigned short int unsigned int unsigned long int To Store /7 licitly Signed 5nts signed char signed short int signed int signed long int %f the key#ord int is re o$ed, say fro signed int, the default data type is int so the state ents signed int and signed are syntactally e0ui$alent built in o erator si-eof:7; si(eof5 type6 returns @ of bytes in that type si(eof5$ariable6 returns nu ber of bytes in that $ariable
32
Relationshi s $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 com iler !riter0 16 #hether the default is signed or unsigned if the progra 5har, short, int or long 26 the e)act nu ber of bytes in any data type although specified g,..c) illustrates si-eof:var; <LT-' si(es of different types 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 sa ple output D? ?D /i(e of character is 1 /i(e of short
34
ini u
ay $ary fro
syste
int is 2 /i(e of unsigned int is 3 /i(e of /i(e of long int is 3 D? ?D e)ercise' odify this progra consu e D ? to find out ho# any bytes a float and a double int is 3
35
PLUT>*%R%TO CL<C-U</
This is not a bad ti e to say a fe# introductory #ords on the issue of portability. Lne of the strongest argu ents for portability. %f a progra the target platfor has any groups aking the change to the C language is that of is coded to the ></% standard, it should be !100N portable if
an ></% co pliant C co piler a$ailable. "o#e$er, there ha$e been order for their progra s to #ork correctly cross!platfor .
that ha$e learned the hard #ay that they need to understand, the ></% standard in %t is e)tre ely i portant to note the follo#ing in light of our discussion of data types' a short integer #ill be at least 2 bytes, but an int #ill typically be the sa e si(e as a 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 ainfra e, hung their ay or ay not be 3 achine #ord, but #ill be at least 2
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 PC 5&L/ progra achines6 e$en though it had co piled #ithout error or #arning. Their illion or
#as riddled #ith counters of type int 5keeping track of the nu ber of ainfra e co piler had 3 byte ints, their PC co piler had 2 byte ints.
records read etc.6, #hich #ould keep track of counts so eti es reaching 1 ore. Their 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 !if you ean to store 2 byte 0uantities use a short ean to store 3 byte 0uantities use a long
!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 co pilers co e #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 co pilers. 5does ouse control ean anything on a that does 2289 attached to a WS/ syste 6 %t does you little good to ha$e a progra fancy screen %?L if it cannot be ported to another platfor strictly intended for only one platfor 6 Sim lest C rogram ossible0 Part 55 full #2S55 com atability !ith no com iler !arnings or errors $oid ain 5$oid6' ?D prototype for ain, usually not re0uired, but
5unless, of course, it is
guaranteed to #ork #ith all ></% co pilers D? $oid A B LU ?D ></% header stating return type D ? int int A return 0H B ain5$oid6H ?D prototype for ain 5 6 ain, usually not re0uired, but guaranteed to #ork #ith all ></% co pilers D? ain5 6
37
ultiplication D?
38
rogD.c
?D progra di$ision D?
?D ho# $alue is stored is deter ined 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 Mc ? 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
sam le out ut
a MJ 8 b MJ 2 8?2 M 2 .H C MJ 8.000000 d MJ 2.000000 integer di$ided by integer 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
42
/7ercise , ?D Part 1 D? ?D #rite a progra ?D ans M 8 ti es : plus 1: di$ided by 4 do the ultiplication first the di$ision second the D? ?D Part 2 D? ?D #rite a progra that e$aluates the follo#ing e)pression D? ?D use e)ponential for ats for the nu bers D? ?D display the result in e)ponential for at D? ?D 5.0000000:8 V 2010 6 ? 5 9:000 D 226 D? odulo third and the addition last odulo 2 that e$aluates the follo#ing e)pression D? ?D display the result in integer for at D?
43
Solution for /7ercise , ain 5 6 A int ansH float a,b,c,dH float nu eratorH float deno inatorH 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 nu erator M a V bH deno inator M c D dH printf5Fnu erator M Ne KnF,nu erator6H printf5Fdeno inator M Ne KnF,deno inator6H result M nu erator ? deno inatorH printf5FUesult M Ne KnF,result6H B
44
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)a ined 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)a ined #ithin the conte)t of a decision. The relational operators return a 1 if true, 0 if false.
45
46
47
48
n !!! 1 2 2 3 4 7 8 9 : 10 11 12 12 13 14 17 18 19 1: 20
n s0uared !!!!!!!!!!!! 1 3 : 17 24 27 3: 73 91 100 121 133 17: 1:7 224 247 29: 223 271 300
49
Por a M 1 to 28 by 2
St!rtin# Condition
Condition $o Contin e
Por 5 n M 1H n IM 20H nVV6 n is initiali(ed to 1 perfor test, if true, do body if false, skip body after body perfor ed, do incre ent ??nVV
50
?? n M 1 ?? if n IM 20
-)ercise' #ith
Ue#rite the pre$ious e)a ple 5progl0.c6 and replace the for loop a #hile loop, and then a do!#hile loop.
-)ercise' 40
10 to
-)ercise' !8
22 to
51
scanf in ut
to calculate s0uares D ?
printf5F"o# far do you #ant to go toY KnF6H scanf5FNiF,[userQnu ber6H printf5CCKnOou entered Ni KnKnF,userQnu ber6H 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 userQnu berH 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%/-' re o$e the [ fro [userQnu ber, you #ill e)perience a core du p. 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 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 progra ing, 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 co piler should
52
#ith a
#arn you that you are trying to use the $alue of the $ariable userQnu ber 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 nu ber 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 5n ut scanf:G format&s ecifierG ) address of variable to satisfy format&s ecifier;H
54
to calculate s0uares D ?
feed D?
?D using sa e 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
>ssu e ) and
) M 4H #hile 5 ) I 106 A M ) D 10H do A
are ints
57
?D CLWWL< PUL1U>WW%<1 W%/T>K- D? /* %nfinite RLLP D? i M 1H -S-UO C state ent returns a $alue that #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 progra ers replace MM #ith so e other defined $alue
58
ay be used or ignored
T"- U-T;U< $alue of an assign ent state ent is the $alue assigned
see @define state ent 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
?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
lusr?de o?/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
1 to 10 KnF6H
/* 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?de o?/L;<&?play ?usr?de o?/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 ten D ? /* factorial nu bers D? ?D desired output is a table D? ?D 1G 1 D? ?D2G 2 D? ?D2G 7 D? ?D ... D? is ore than 14 lines5of code, not counting co ents6 it is going the ?D 10G 2729900 D ? %f your progra #rong direction. "%<T' athe atical identity <G M 5<!%6G D < to co pute and print the first
63
64
/7ercise 9
/* #rite a c progra ?D i.e. input 1223 D? ?D ?D ?D ?D output 3 D? 2 D? 2 D? 1 D? to input an integer as an integerD ? ?D print out the nu ber, one digit per line D?
65
C
if .c ain 5 6 A
if if else
int iH printf5Fenter a nu ber KnF6H scanf5FNiF,[i6H if :i M 'FF; A printf5FNi is less than one hundred KnF,i6H B printf5F>fter the first if state entKnF6H 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
67
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 e7 ression;
re1 t t f f
re2 t f t f
result t t t f
70
if : relational e7 ression; relational e)pression evaluates to TR1/ or 6#4S/ if : : re'; LL : re+; ; LL is the logical and o erator
rel t t f f t f t f
re2 t f f f
result
71
scanf5FNiF,[stockQsy bol 6H scanf5FNcF,[cr6H printf5FOou entered NiKnF,stockQsy bol6H if 5 stock sy bol MM %*W 6 printf5FN.2fKnF,42.246H else if 5 stockQsy bol MM W-U6 printf5FN.2fKnF,81.846H else if 5 stockQsy bol MM Z;%T 6 printf5FOL; /-R-CT-& Z;%TKnF6H else if 5 stocksy bol MM WW& 6 A printf5F5P6referred or 5C6o scanf5FNcF,[pQorQc 6H scanf5FNcF,[cr6H if 5pQorQc MM CPC 6 A printf5FPreffered 22.4K11F6H B
72
onYKnF6H
else if 5pQorQc MM CcC 6 A printf5+Co else printf5F;nkno#n character KnF6H B else printf5F;nkno#n sy bo%KnF6H B on 21.24K11F6H
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
@include Istring.hJ @include Ictype.hJ @define @define @define @define %*W
s!itch statement
int stockQsy bolH char pQorQcH char crH printf5+Kn-nter stock sy bolKnF6H printf5F 1 printf5F2 printf5F2 printf5F3 %*WKnF6H W-UKnF6H WW&KnF6H Z;T%KnF6H
scanf5FNiF,[stockQsy bol 6H scanf5FNcF,[cr6H printf5+Oou entered NiKnF,stockQsy bol6H s#itch 5 stockQsy bol 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
onYKnF6H
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 printf5FCo B else printf5+;nkno#n characterKn,6H breakH default' printf5F;nkno#n sy bo%KnF6H B ?D end s#itch D? ?D -)ercise, re o$e the break in case %*W, #hat happensY .hyY D? T"-/- T.L R%<-/ >U- >TULC%L;/, yet co .hyY 5toupper is a acro that con$erts a character to its upper case e0ui$alent6 on. on 21.24KnF6H
76
/7ercise <
/* #rite a progra Ret the Tell the ha$e a to ha$e a person guess a secret nu ber. a)i u of 8 tries. D? Ret the range of $alid nu bers be (ero to 100. if they #ere too high or too lo#.
77
'ssKnF6H
if 5 guess I secret6 A syste 5F?usr?de o?/L;<&?play ?usr?de o?/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?de o?/L;<&?play ?usr?de o?/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 ?D input a , b , c D ? ?D check for real or i aginary roots D ? ?D ?D ?D ?D )l M !1 )l M !2, )2 M 2 )l M0 )l M.4 ake sure not to di$ide by (ero D? 121 1 !1 !7 000 0 3 !2 MJ single real root )1 M !1 D? MJ t#o real roots )1 M !2, )2 M 2 D? MJ one real root MJ one real root )1 M 0 D? )1 M .4 D? ?D test data to sol$e for the real roots of D ?
80
else if 5 discri inant ?? 06 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' the keyboard inputs an integer nu ber fro displays it for#ards displays it back#ards D? ?D big, brain buster as you re$erse the nu ber, print out each digit on a seperate line, #ith the english language #ord beside the digit D? ?D hu ungous brain destroyer print out the english #ord for the nu ber as a #hole i.e. 742 MJ si) hundred fifty three D?
83
to input an integer
printf5FNi KnF,outnu 6H ?D print it D? i M i ?10H ?D di$ide current nu ber by 10 effecti$ely dropping last digit D? safe M re$nu H printf5CCKnK nCC6H
85
?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,outnu 6H ?D print itD? printf5F N sKtF,#ords _outnu `6H s#itch5 outnu 6 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 nu ber by 10 D? B B
87
errors.c
?D putting a se i colon after a definition D? @define W>=QS>R;100H atter D?
?D forgetting that upper and lo#er case @define L<- 0H ain 5 6 A int j M 200H int k M 0H
?D adding a se i!colon #here there shouldnCt be one D? if5 j M 1006H printf5FJ M 100KnF6H ?D lea$ing off a se i!colon #here there should be one D? ?D #onCt co pile because of @if 0 D? @if 0 if5 j M 1006 ?D 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? issing a se i!colon #here you need one D? printf5Fl M 100KnF6
@if 0 j M LneH printf5Fj M Nd KnF,j6H @endif ?D forgetting the [ character in scanf calls #ill cause core du p 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 deter ine #hat if anything to do #ith or about this .. .hat #ould you ha$e doneYY
89
90
#rrays0 Discussion
To declare an array #e state the type of its ele ents, the na e of the array, and the nu ber of ele ents 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 ar_1` M 32H the first ele ent in the array. .hen an array is subscripted, like' address of the array 5the address of the (ero!th ele ent, arl6, adds the si(e of 1 integer to it 5to get the address of the ele ent at location 1 in the array6 and Cgoes toC that address. %n this case #e are doing an assign ent operation, so the correct code is generated to perfor that address. /ince the co piler generates the address in this #ay, it assu es the progra $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 other is that the authors #ish to place the responsibility for 5orrectness upon the progra design ti e. Lther languages 5like Pascal6 enforce tight run!ti e checking. >rrays t#oQdi Lr #e ay ha$e ore than 1 di ension' int t#oQdi _2` _2lMA A 1,2,2 B, A 3,4,7B BH is an array of 2 2 integer arrays. %n fact this is a better er at a)i i(e e)ecution speed, the er has a e ory store at
#hat actually happens is this, the co piler generates the code to take the starting
is a 2 by 2 array of integers. There are 2 ro#s of three colu ns. ight say t#oQdi
description as that is ho# it is stored re e ber, a 2 integer array is represented by its address. /o t#oQdi array begins in has 2 entries in it each of #hich is the address #here a 2 integer
91
e ory.
t#oQdi
1000
1012 The state ent t#oQdi _1`_2` M 32H is co piled 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
93
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 so e syste s 5&L/ for e)a ple6 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 progra ers. /o eti es 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)a ple storing at arrayl_4` #ill 0uite possibly o$er#rite the $ariable i. Ln any syste s storing a $alue at arrayl_!l` #ill cause an addressing e)ception 5 ainfra e6.
95
W>=Q/CLU-/ W>=Q/CLUW%<Q/CLU-
W%<QR->1;-Q/CLU-
scanf5FNiF, [nu scores6H printf5CCKnOou entered Nd scores KnF,nu scores6H if 5 nu scores 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 nu scoresH 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#
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>1200 200 200 200 Reague a$erage M 240.00
99
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
102
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 /* .rite a progra to input a list of nu bers into an array Pind the largest ele ent of the array Pind the s allest ele ent of the array Put the s allest $alue at position 0 in the array and put the $alue that #as at position 0 #here the s allest $alue used to be Print out the updated array D? to input a list of nu bers into an array D? /* print the array ele ents for#ards and back#ards D?
104
105
/7ercise 'F
?D #rite a progra nu bers 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 nu bers into, you ha$e to sort the they are in D? <ote' you co fortable 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 >T %<&-=2 /.>P -R-W-<T/ >T %<&-= 1 ><& %<&-=2 -<&%P -<&PLU -<&PLU %P -R-W-<T >T %<&-= 1 %/ 1U->T-U T">< T"- -R-W-<T ay i ple ent the sort ho#e$er you are in the array to sort an array of
106
107
The co piler Fre e bersF 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 co piler error. %f #e assign printfCs return $alue to a non!unsigned, #e #ill get at least a co piler #arning. .hen #e #rite our o#n functions #e #ill #ant to use prototypes to allo# the co piler to pro$ide the sa e type of checking as #ith printf. %f the co piler does not see a prototype for a function but sees it being used it #ill issue a #arning and there #ill be no checking perfor ed. This is dee ed to be poor progra ing practice. .e should al#ays use prototypes to allo# the co piler to eans to state that so ething e)ists 5usually $erify our interfaces as #ell as our usage. > prototype is also kno#n as a function declaration. To FdeclareF in C so e#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, prototypes. any other languages support si ilar concepts as
108
ain
?D sa ple output D? %n ain routine ain routine %n subroutine *ack in %f #e hadnCt placed the prototype for subrl in ain, the co piler by default #oud assu e that the function header correctly stated the return and para eter types. This only #orks because the co piler CseesC the function definition in the sa e file as it is used. >gain this is dee ed 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 co piler #ould not see the header line before it #as used.
110
111
ain routine D?
e)ecution starts D?
112
e)ecution
subr15 6 D? $oid subr15int6H ) M 2H printf5F%n KnF,)6H subr15)6H printf5FWain routine location 1 ) M Ni KnKnF,)6H ) M 2H printf5F%n KnF,)6H subr15)6H printf5FWain routine location 2 ) M Ni KnKnF,)6H ) M !3H printf5F%n 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
ain routine ) M Ni
ain routine ) M Ni
ain routine ) M Ni
115
Consider the three files test1.c funs1.c and funs2.c test1.c $oid A f15 6H f2 5 6H B B $oid f2 5 6 A so e code B /ince ain calls nand f2 it should ha$e the prototypes for these functions ain 5 6 funs1.c $oid f1 5 6 A f2 5 6H B funs2.c $oid f2 5 6 A so e code
a$ailable to it at co pile ti e. Rike#ise, since fl calls f2, it should ha$e the prototype for f2 a$ailable to it. .e could try to re e ber to do this. "o#e$er, there is an easier #ayG
117
.e can #rite our o#n header files 5one or yproto.h $oid fl 5$oid6H $oid f25$oid6H $oid f25$oid6H Then #e can load the test1.c @include + yproto.h, $oid A f15 6H f2 5 6H B B $oid f2 5 6 A so e code B @ including the prototype into funs2.c is i portantG ain 5 6
ore6'
all by using @include + yprot.h., funs1.c @include + yproto.h, $oid f1 5 6 A f2 5 6H B funs2.c @incluee + yproto.h, $oid f2 5 6 A so e code
-$en though function f2 does not call f1 or f2, the co piler #ill see the prototype for function f2. The co piler #ill $erify that the prototype function f2. %f f2 #ere not coded #ith the correct nu ber and type of para eters, or #ith the #rong return type 5$ersus the prototype6 the co piler #ould issue a #arning. This is yet another check that our pro ised interface 5prototype6 actual code #e #rote and also ho# #e #ill use it. atches the atches the actual code for the
118
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 argu ent passed fro ain routine D ? ?D i is a local argu ent, 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 argu ent passed fro ain routine D ? ?D i is a local argu ent, 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
ain i M Ni KnF,i6H ?D pass $alue of i to $al1 D? ain i M Ni KnF,i6H ?D notice that $al1 did not change i D? ain i M Ni KnF,i6H ?D pass address of i to ref1 D? ain i M Ni KnF,i6H ?D notice that ref1 changed i D?
%n
ain i M 7
122
$alues are placed on stack subroutine cannot FseeF e ory of ain routine subroutine can only FseeF $alues on stack call by reference addresses are placed on stack subroutine can FseeF e ory of ain routine through addresses found on stack
123
/7ercise ''
?D P>UT L<- D?
?D #rite a progra /*
Pass the nu ber 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 D? ?D P>UT T.L D? ?D #rite a progra ?D Pass the nu ber to a subroutine by reference. "a$e the subroutine "a$e the D? ultiply the $alue by three. ain routine print the original $alue and the result. to input a nu ber D? ain routine print the original and the result.
124
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 se antically e0ui$alent to [scores_0` D? int scores_4`, iH int deter ine 1 5 int $alues_4` 6H int deter ine25 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 deter ine1 5scores6 MM 1 6 printf5F22 #as in array KnF6H else printf5F22 #as not in array KnF6H if 5 deter ine25scores6 MM 1 6 printf5F40 #as in array KnF6H else printf5F40 #as not in array KnF6H if 5 deter ine25scores6 MM 16 printf5F40 #as in array KnF6H else printf5F40 #as not in array KnF6H B
126
rog,<.c
array D? @define @define D?
?D function returns an integer ?D function na e is deter ine D? ?D function accepts array of ten integers D? ?D #hat it is really accepting is a pointer to the first ele ent 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 retu 5/;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 retu 5P>%R;U-6H B
128
129
?D first solution is to pass the si(e of the array into function D? /* function returns nothing D? /* its na e 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,te pH 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 te p M a_i`H a_i` M a_j`H a_j` M te pH 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 A int iH int nu Qele entsH ?D donCt kno# ho# big array needs to be D? int array_W>=Q>UU>O` H
130
ain 5 6
$oid sort5 int D, int6H ?D get and error check nu ber of ele ents D? printf5F"o# any ele ents in arrayCGKnF6H scanf5FNiF ,[nu Qele ents6H if 5nu Qele ents I 0 ]] nu Qele ents J W>=Q>UU>O6 A printf5F% possible nu ber of ele entsKnF6H e)it5!16H B ?D ha$e a good nu ber of ele ents, continue D? for 5 i M 0H i I nu Qele entsH iVV 6 A printf5F-nter $alue for ele ent Ni KnF,i6H scanf5F Ni F,[array_i`6H B printf5FThe array before the sort is'KnF6H for 5 i M 0H i I nu Qele entsH 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 nu ber of ele ents D? sort5array, nu Qele ents6H printf5FThe array after the sort is' KnF6H for 5 i M 0H i I nu Qele entsH iVV 6 printf5FNi F,array_i`6H printf5CCKnKnCC6 H B
131
"o#
4
any ele ents in arrayY -nter $alue for ele ent 0 1 -nter $alue for ele ent 1 3 -nter $alue for ele ent 2 2 -nter $alue for ele ent 2 2 -nter $alue for ele ent 3 : The array before the sort is' 1322: The array after the sort is' 1223:
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, te pH 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 te p M a_iinde)`H a_iinde)` M ajjinde)`H aljinde)` M te pH 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 0122 !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
printf5CC KnCC6H printf5Fcolsu KtF6H for 5 colu n M 0H colu n I 2H colu nVV 6 A colsu M 0H colsu B printf5CKnKnF6H B ?D sa ple output D? ?D Lriginal 122 24: W>TU%= .%T" UL./;W/ ><& CLR;W< /;W/ ro#su 122 24: colsu D? 3 8 12 7 18 atri) C? sa pleQ atri)_ro#` _colu n`H for 5 ro# M 0H ro# I 2H ro#VV 6 printf5FN2iF ,colsu 6H
136
t!odim.c
ain5 6 A ?D function prototype header ust supply ro# and colu n infor ation 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 ele ents, each ele ent is itself an array D? A A1,2,2B, A 3,4,7B BH printf5F >> KnF6H s15)6H ?D call using just na e 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 ele ent of first arrayD ?D co piler #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 infor s us of ho# colu ns D? printf5FNi F,)_i` ;` 6H B p ri n tf 5 FK n F 6H
137
B B
138
139
2 3
int inputQarray_UL./`_CLR/`H int te pQarray_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 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 te pQarray_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
?D sort by ro# D?
for 5j M 0H j I CLR/H jVV 6 printf5FN2iF ,te p Qarray_i` u`6H printf5CKnF6H B for 5j M 0H j I CLR/H jVV 6 ?D sort by colu n D? A for 5 i M 0H i I UL./H iVV 6 col_i` M te pQarray_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?
sam le out ut 1 2 2 14 2902 : 3 !2 12 >PT-U /LUT%<1 UL./ 1 2 2 14 0229 !2 3 : 12 >PT-U /LUT%<1 CLR/ !2 2 2 9 0 2 2 12 1 3 : 14
141
#hen co
uch
as possible, all < if you kno# it. There are applications #hen you #onCt kno# the last
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 sl5[one_2`,26H s15one V 2,26H @if 0 sl5one_2`,26H ?D this #ould be run ti e error, subscripted ele ent needs [ D? @endif
144
?D array na e by itself is pointer D? ?D subscripted ele ent needs [ D? ?D subscripted ele ent needs [ D?
s25one6H ?D array na e by itself is pointer, routine e)pecting int, prints it as int D? s25one_2`6H D? printf5F/-CL<& PU%<TKnF6H sl5t#o,126H ?D na e of array by itself is pointer D? sl5t#o_0`,36H ?D na e of array by itself is pointer, t#o_0` is na e of an array because t#o is an array of three ele ents, of #hich each ele ent is itself an array D? sl5t#o_1`,36H ?D na e of array by itself is pointer D? sl5t#o_2`,36H ?D na e of array by itself is pointer D? @if 0 sl5t#o_0`_0`,126H du p D? @endif sl5[t#o_0`_0`,126H 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 ?D subscripted ele ent needs [ D? ?D subscripted ele ent is $alue, routine e)pecting address, core ?D subscripted ele ent is a $alue, routine e)pecting $alue, okay
145
/>WPR- L;TP;T P%U/T PU%<T 01 2 2 3 223 L)f8fffb23 L)2 /-CL<& PU%<T 0 1 2 2 10 11 12 12 100 101 102 102 0122 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
147
$oid s25int )_2`_3`,int ro#s,int cols 6 A ?D #ants to use 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 co piler error D ? ?D routine does not ha$e info on ro#,colu n layout of B B B e ory associated #ith ) D? printf5FN3i F,)_i` _j`6H ultiple s0uare brackets, needs di ension info D?
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 co piler #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 co piler #arning D? ?D try to call s2 D ? printf5CCKncalling s2 for oneKnF6H s25one,1,46H?D #ill be co piler #arning D? printf5CCKncalling s2 for t#o KnF6H s25t#o,2,36H printf5CCKncalling s2 for oneKnF6H s25one,2,36H?D #ill be co piler #arning D? printf5CCKnCC6H B
149
acc testarrays 1.c Ftestarrays l.cF, line 80' #arning' argu ent is inco patible #ith prototype' arg @1 Ftestarrays1.cF, line 87' #arning' argu ent is inco patible #ith prototype' arg @1 Ftestarrays1.cF, line 90' #arning' argu ent is inco patible #ith prototype' arg @1 Ftestarraysl.cF, line 93' #arning' argu ent is inco patible #ith prototype' arg @1 a.out calling sl 01223 0 1 2 2 10 11 12 12 100 101 102 102 0122300000 calling s2 calling s2 for one 01223 calling s2 for t#o 0 1 2 2 10 11 12 12 100 10 1 102 102 calling s2 for one 01223000
150
no additional code D?
Sco e.c
Sco e 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
153
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)a ple of Ctail recursionC 5#hen the last thing a routine does is call itself6. Wost tail!recursi$e progra s are better #ritten iterati$ely including
154
this one. Uecursion is best used #hen the proble itself can be described in itCs si pliest ter s 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, fractals62. 1. definition found in se$eral sources, not possible to identify first author 2. /ee the book Data Structures and Pro ram 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 re o$ing recursion fro progra s.
155
test o .c
?D if you i ple ented s 1 here, there #ould be co piler errors #hen you tried to send a different argu ent list D? ain 5 6 A ?D if you had a prototype, you #ould get co piler errors #hen you tried to send a different argu ent 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 argu ent 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
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 /* ha$e a function to ?D A 4, 12, 21, 22 B D? ultiply the arrays D? D? product of the arrays D?
?D ha$e a funtion to do the 52D4 V 2D7 V 2D8 V 2D9 6 52D4 V 2D7 V 2D8 V 2D9 6
/* A 5l D4 V 1 D7 V 1 D8 V 1 D9 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 ?D allo# the type 0 to 0uit D? 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, te pH printf5F>dd arrays KnF6H printf5F>rraylKt>rray2Kt'/u KnF6H for 5 i M 0H i I si(eH iVV 6 A te p M a_i` V b_i`H printf5FNiKtNiKtNi KnF ,a_i` ,b_i` ,te p 6H B returnH B $oid A ultQarrays 5int a_`, int b_` , int si(e6 int i, te pH printf5FWultiply arrays KnF6H printf5F>rraylKt>rray2KtWultKnF6H for 5 i M 0H i I si(eH iVV 6 A te p M a_i` D b_i`H printf5FNiKtNiKtNi KnF,a_i` ,b_i` ,te p 6H B returnH B $oid product arrays 5int a_`, int b_` , int si(e6 A int i,j,te pH printf5Fproduct arrays KnF6H printf5FW ProductKnF6H for 5 i M 0H i I si(eH iVV 6 A te p M 0H for 5j M 0H j I si(eH jVV 6 A te p M te p V a_i` D b_j`H printf5FNiKnF ,te p6H 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 caseC C' 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) tem H for : i ? FH i M si-eH iCC ; A tem ? aRiS C bRiSH B returnH B
161
?D synta) is' struct then na e 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 /* ele ents of structure declared like $ariables */ int onthH int dayH int yearH BH ?D synta) is' data type then na e of $ariable D? struct date )H created ) is the na e of the $ariable to be
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 sa ple output TodayCs date is 3?29?1::2.
162
d1H 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 inutes, seconds of #hat ti e it is no#. /tructure should be able to store current hour, &isplay the current ti e and #hat ti e it #ould be after one second. Continue to read in ti es until the ti e read in is !1 !1 !1 D?
scanf5FNi' Ni' NiF,[currentQti e.hour, [currentQti e. inutes,[currentQti e.seconds6H ?D loop until sentinel record is found D? #hile 5currentQti e.hour GM !1 [[ current ji e. inutes GM!1 [[ currentQti e. seconds GM !1 6 A printf5FOou entered N.2i'N.2i'N.2iKnF,currentQti e.hour,
164
currentQti e.
ne)tQti e M ti eQupdate 5 currentQti e 6H printf5F;pdate ti e is N.2i'N.2i'N.2iKnF, ne)tQti e.hour, ne)tQti e. inutes, ne)tQti e.seconds6' printf5F-nter the ti e 5hh' 'ss6' F6H scanf5FNi'Ni'NiF, [currentQti e.hour, [currentQti e. inutes, [currentQti e.seconds6H B ?D function to update the ti e by one second D? struct ti e ti eQupdate 5 struct ti e no#6 A no#.secondsVVH if 5 no#.seconds M 70 6 A no#. seconds M 0H no#. inutesVVH if 5 no#. A no#. inutes M 0H no#.hourVVH if 5 no#. hour ?? 23 6 A no#. hour M 0H B B B return5no#6H B inutes ?? 70 6
165
?D a function, cti e, that returns a pointer to a character D? e)tern char D cti e5 6H ?D get ti e fro ?D ti e is a syste 1:80 D? ti e 5 [ti e$al 6H ?D cti e takes the tick count and produces a string of characters that can be displayed #ith Ns for at D? printf5F1WT ti e is Ns KnF, cti e5 [ ti e$al 6 6H ?D get t structure D? ;<%= syste D?
?D locati e 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 localti e5[ti e$al6H ?D tp is a pointer to a structure D? printf5F/tructure are'KnF6H printf5F/econds printf5FWinutes NdKnF,tp!Jt Qsec6H NdKnF,tp!Jt Q in6H e bers
printf5F"ours NdKnF,tp!Jt Qhour6H printf5F&ay of Wonth NdKnF,tp!Jt Q day6H printf5FWonth of Oear NdKnF,tp!Jt Q on6H r (ero based off by one D? printf5FOear printf5F.eekday printf5F&ay of Oear B 1WT ti e is Thu Jun 3 14'4:'21 1::2 /tructure are' /econds 21 Winutes 4: "ours 14 &ay of Wonth 3 Wonth of Oear 4 Oear :2
167
NdKnF,tp!Jt Qyear6H ?D 2 digit year obsolete in 2000... D? NdKnF,tp!Jt Q#day6H NdKnF,tp!Jt !yday6H
e bers
.eekday 3 &ay of Oear &aylight /a$ingsY 1 <ote' the onth nu ber is (ero based 5JanML, &ece l l6. 144
168
BH
JM 0 [[ t1.
IM 4: [[
t2 M ne)t second 5 t1 6H printf5FTi e 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
172
pointQ$alueH
char na e_9`H
BH
printf5F NcNcNcNcNcNcKtN2iKnF, pi_i`.na e_0`, pi_i`.na e_1`,pi_i`.na e_2`, pi_i`.na e_2`, pi_i`.na e_3`, pi_i`.na e_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`.na e,po_i`.pointQ$alue6H B Piece !!!!! King Zueen *ishop Knight Uook Pa#n fro Piece !!!!! King Zueen *ishop Knight Uook Pa#n po Salue !!!!! 20 10 4 3 8 1 Salue !!!!! 20 10 4 3 8 1
174
/7ercise '<
#rite a progra balance for a checking account, a list of check nu bers dates and a ounts. print out a nice list of the opening balance, the list of transactions, sorted by check nu ber and the running balance after each transaction use structures and functions sa ple input data 4000.00 1 2 4 3 13 2 1?22?:2 1?23?:2 2?2?:2 2?1?:2 3?14?:2 1?22?:2 24.00 22.00 128.00 :2.00 3400.00 100.00 that reads in an opening
/a ple Lutput Lpening *alance c4000 Check <u ber 1 2 2 3 4 13 Transaction &ate 1?22?:2 1?22?:2 1?23?:2 2?1?:2 2?2?:2 3?14?:2 > ount 24.00 100.00 22.00 :2.00 128.00 3400.00
175
/7ercise '<.c
@define struct trans A int chkH char date_:`H float a tH BH $oid sorttrans 5 tptr, count6 struct trans D tptrH int countH A int i,jH struct trans te pH 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 te p M tptr_i`H tptrji` M tptr_j`H tptr_j` M te pH B B B B W>=U-C/ 20
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 nu ber KnF6H scanf5FNiF,[chk6H if 5chk GM !1 6 A ttrans_rec`.chk M chkH printf5F-nter date ?dd?yy and a ount 5float6 KnF6H scanf5FNs Nf,,[ttrans_rec`.date,[ttrans_rec`.a t6H recVVH printf5FLU%1%<>R T>*RKnF6H for 5 i M 0H i I recH iVV 6 A printf5FNi Ns NfKnF ,ttrans_i` .chk,ttrans _i` .date,ttrans_i` .a t6H B sorttrans5 [ttrans _0` ,rec6H printf5F/LUT-& T>*RKnF6H for 5 i M 0H i I recH iVV 6 A printf5FNi Ns NfKnF, ttrans_i`.chk, ttrans_i`.date, ttrans_i`.a t6H 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`.a tH printf5FNi Ns Nf NtKnF,ttrans_i`.chk, ttrans_i`.date, ttrans_i`.a t,ne#bal6H B
177
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
?D function to count the nu ber of characters in a string D? ?D also the ;<%= function that does the sa e thing D? @include Istring.hJ ?D returns a count of ho# any characters are in string D? ?D count does not include null ter inator D? ?D accepts a null ter inated string D? int ourQstringQlength 5 char D input string 6 A int count M 0H /* note the null ter inator 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
?D progra ?D uses pointers D ?
String Processing
strcat
?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 ter inator 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 re e ber to tack null ter inator onto end of c D? Dc M CK0CH B
182
ain 5 6 A $oid jtcat5 charD, charD, charD6H ?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 sa ple output Terrill L#ens abcde abcde abcde abcde abcde abcde Lingo *oingo Lingo *oingo ?D jts concatenation routine D?
183
strcm
if 5 Ds1 MM bK0d [[ Ds2 MM bK0d6 return5 0 6H ?D 0 is code for +e0ual, in B return 5 1 6H ?D 1 is code for +not e0ual, in B ain 5 6 A int jte05 charD, charD 6H char stra_` M FTerrill L#ensFH char strb_` M FTerrillFH int e0ualreturnH A FThe /a eF, F<ot The /a eF BH int c pQ$al1, c pQ$al2, c pQ$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 c pQ$all M strc p5stra,stra6H printf5Fc pQ$al1 MJ Ni KnF,c pQ$al16H c pQ$al2 M strc p5stra,strb6H printf5Fc pQ$a12 MJ Ni KnF,c pQ$a126H c pQ$al2 M strc p5strb,stra6H printf5Fc pQ$al2 MJ Ni KnF,c pQ$al26H B
184
y routine D?
y routine D?
char D strings_` M
/7ercise 'D
.rite a progra that #ill input a list of #ords until the #ord 0uit is entered. 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 strc p
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 strc p5s,F0uitF6H #hile 5 ) GM 0 6?D strc p returns P>R/- if a A if 5 strc p5s,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 strc p5s,F0uitF6H B printf5FPinal #ord is NsKnF,d6H B sttrc p5FabcF,FabcF6 #ould return 0 because they differ in 0 locations strc p5FabcF,F)y(F6 #ould return non!(ero
186
atch D?
rog9+.c
?D as an e)ercise, re o$e the ne)t line and co pile 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 ter inated line fro stdin D? ?D the line is turned into a null ter inated 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 iM 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 ter inate 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 @define P>R/TU;0 1
@include Ictype.hJ ">S- > RLLK >T ctype.h RLLK at the definitions OouCll find these in any C reference under %/))))) ususlly grouped together, or look up ctype.h ain 5 6 A ?D progra ch ar cM C)CH ch ar crH #hile 5 c GM C0C 6 A printf5CCKn-nter a character, %Cll tell you if itCs alphabeticKnF6H scanf5FNcF,[c6H scanf5FNcF,[cr6H return D? if 5isalpha5c6 6 printf5FNc is alp
188
acro
189
String 6unctions
@include Istring.h J char D strcat5sl,s26 char D strchr5s,c6 <;RR int strc p5sl,s26 1 I0 0 J0 char D strcpy5sl,s26 si(eQt strlen5sl6 copied int strnc p5sl,s2,n6 char D strncpy5sl,s2,n6 before n char D strrchr5s,c6 <;RR search s for last occurrence of c, returns pointer to c or co pare s1 to s2 o$er n characters copy s2 to s1 for at ost n characters, ay null ter inate s1 I s2 s1 MM s2 s1 J s2 s2 stuck on end of s1, returns pointer to s1 search s for 1st occurence of c, return pointer to c or
s2 copied o$er s1, returns pointer to s1 find length of s1 copy s2 to end of s1 until null encountered or n chars
1.
strc p looks so ething like' signed strc p5const char Da.const char Db6 A #hile5DaMDb6 A if5DaMMCKLC6 return 0H a V V
190
H b V V H
191
Character 6unctions Wost co pilers actually i ple ent these as functions. @include Ictype.hJ 0 1 e0uates to no, false e0uates to yes, true is character c alphanu ericY is character c alphabeticY is character c a control characterY is character c a digitY is character c lo#er caseY is character c a printable character is character c a punctuation character is character c upper caseY is character c a #hite space characterY con$ert character c to lo#er case con$ert character c to upper case acros not
isalnu 5c6 isalpha5c6 iscntrl5c6 isdigit5c6 islo#er5c6 isprint5c6 ispunct5c6 isupper5c6 isspace5c6 tolo#er5c6 toupper5c6
4arge 2umbers as Characters /7ercise .rite a C progra add the to' together read in, as character strings, t#o arbitrarily large nu bers 5ie' 28 digits6 display the result
192
@include Istdio.hJ int jcon$5ch ar6H char jre$5int6H ain56 A char nu 1_20`, nu 2_20`, nu 2 _21`H int n1 _20`, n2 _20` H int n2 _21` H int len1, len2, len a)H int shuffleQdist, iH int ans, carryH for 5 i M 0H i I 20H iVV 6 A nu 1 _ i` M 0)00H nu 2 _ i` M 0)00H nu 2 _ i` M 0)00H B printf5F-nter first nu berKnF6H scanf5FNsF,[nu 1_0`6 H printf5F-nter second nu berKnF6H scanf5FNsF,[nu 2_0`6 H printf 5Fnu 1 char is Ns KnF, nu l 6H
193
printf 5Fnu 2 char is Ns Kn F, nu 2 6 H ?D find out ho# long the string is D? len1 M strlen5nu 16H len2 M strlen5nu 26H ?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 sa e lengthKnF6H len a) M len1H B else A if 5 len1 I len2 6 A printf5Flen1 I len2 KnF 6H len a) M len2H printf5Flen a) is Ni KnF,len a)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 nu 1_i V shuffleQdist` M nu 1_i` for 5 l M 0H i I shuffleQdistH iVV 6 nu 1 _i` M b0dH B else
194
A printf5Flen1 J len2 KnF6H len a) M len1H printf5Flen a) is Ni KnF,len a)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 nu 2_i V shuffle dist` M nu 2_i`H for 5 i M 0H i I shuffleQdistH iVV 6 nu 2_i` M C0CH ! B B ?Dprint after padding D? printf5Fafter padding nu 1 is Ns KnF,nu 16H printf5Fafter padding nu 2 is Ns KnF,nu 26H ?D no# con$ert fro A n1_i` M jcon$5 nu 1_i` 6H n2_i` M jcon$5 nu 2_i` 6H B printf5Fafter con$erting to array of integers KnF6 for 5 i M 0H i I len a)H iVV 6 A printf5+N1iF,n1_i`6 H B printf5FKnF6 H for 5 i M 0H i I len a)H iVV 6
195
character to integer D?
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 len a) ! 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 len a)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 len a)H iVV 6 nu 2_i` M jre$5 n2_i` 6H nu 2 _len a) V 1` M CK0CH printf5FPinal string is Ns KnF,nu 26H 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 integers D? @include Istring.hJ @define W>=&%1%T/ 20 ain 5 6 char digits_ ` M A F012234789:FBH 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 int dl, d2,dsu H int i, a)len,jposH int carryQflag M 0H dtl_l` M L)LLH ?D null ter inate the te porary 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 sa e si(e as the first string D? if 5lenl J len2 6 A @ifdef &-*;1 printf5F/huffling s2KnF6H @endif ?D set null D? jpos M len2H D? ?D start i at the null, position D? for 5i M A if 5jpos JM 0 6 ?D if orig char A s2_i` M s2_jpos`H jpos!!H B else B B ?D if the second string is longer, shuffle the first string into a field the sa e si(e as the second string D? else if 5 len2 J len 1 6 A
201
a)len and shuffle other nu ber o$er D? ?D pointer the last position in ne# s2, the ?D pointer to last position in s2, the null
a)len M len1H
@ifdef &-*;1 printf5F/huffling s 1Kn F6H @endif ?D set a)len and shuffle other nu ber 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 ter inating null for sresult D? sresult_0` M b bH ?D assu e a space in first position D?
202
for 5 i M A
a)len ! 1H i JM 0 H i!! 6
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 co pute resulting int D?
?D deter ine if a carry e$ent occurred D? if 5 dsu 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? JM 10 6
/7ercise '8 ?D ?D odify prog44.c so that it #ill allo# the user to add ne# stocks to the stock list D? odify prog44.c so that the user can search for stocks by nu ber D? to enter the nu ber and retrie$e the na e and ticker sy bol D?
203
?D allo# the
204
rog99.c Strings
@define @define @define @include Istring.h J struct stockQen try A
Structures and
/TU%<1Q/%TT%CK-UQ/%TW>=Q-<TU%-/ 20 4 20
int stockQnu berH char stockQna e_/TU%<1 Q/%T-`H char tickerQsy bol_T%CK-UQ/ %T-`H BH 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
atches the input string /earch the array of 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 strc p5s5i`.stockQna e, #6H if 5 result MM 0 6 return5i6H result M strc p5s_i`.tickerQsy bol,#6H if 5 result MM 0 6 return5i6H B return5 !16H B ain 5 6 A char searchQ#ord_/TU%<1Q/%T-` H int id)H int findQstock5 6H printf5FKnKn-nter stock na e or ticker sy bol to search for 50uit6 to
206
?D found it D?
?D found it D?
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 strc p returns 0 on a D? #hile 5 strc p5searchQ #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)`.stockQnu ber, stockQlist_id)`.stockQna e, stockQlist_id)`.ticker sy bol6' printf5CCKnKn-nter stock na e or ticker sy bol 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
atch
-nter stock na e or ticker sy bol to search for 50uit6 to 0uit ib Oou entered ib ib not found in stockQlist
-nter stock na e or ticker sy bol to search for 50uit6 to 0uit %*W Oou entered %*W 0 %*W %*W
-nter stock na e or ticker sy bol to search for 50uit6 to 0uit Terrill Oou entered Terrill Terrill not found in stockQlist
-nter stock na e or ticker sy bol to search for 50uit6 to 0uit Terrill L#ens Oou entered Terrill L#ens Terrill L#ens not found in stockQlist
-nter stock na e or ticker sy bol to search for 50uit6 to 0uit 0uit Oou entered 0uit acc rog99.c => to not have debug rints >=
208
rog9D.c Pointers
/* Progra 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 ?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 e ory location that $ariable D? to illustrate pointers D?
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 c M b?dH printf5FNc NcKnF,c, DcharQpointer6H /* assign a ne# $alue to c using pointer Dchar Qpointer M b5bH printf5FNc NcKnF,c, DcharQpointer6H ethod D?
ethod D?
?D sa ple 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 "" 55
210
Pointers char c M CZCH 102 char d M C)CH 102 char D dptr M [dHe 103 char D D ddptr M [ dptrH 109 char D D D dddptr M [ ddptrH 112 dMJ) dptr MJ 102 ddptr MJ 103 [d MJ 102 Ddptr MJ ) Dddptr MJ 102 DDddptr MJ ) [ddptr MJ 109 dddptrMJ 109 Ddddptr MJ 103 DDddptr MJ 102 DDDdddptr MJ ) [dddptr MJ 112 [dptr MJ 103 109 addr 103 addr 102 addr ) addr Z addr
211
?D see if date is any good using pointer notation D? if 5 dtptr!Jday M 24 [[ dtptr!J onth 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
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 Sam le 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
215
216
alloc D?
$alueH
type 5char D6 D? ne)tQele ent!Jne)t M :struct lleD6 alloc5si(eof5firstQele ent66' printf5F-nter $alue to s0uare and store 5!16 to stopKnF6H scanf5FNiF,[$al6H if5$al GM!16 ne)tQele ent M ne)tQele ent! Jne)tH else ne)tQele ent!Jne)t M <;RRH B ne)tQele ent M [firstQele entH #hile 5ne)t ele ent GM <;RR6 A ?D print out $alues fro this linked list ele ent D ? printf5F$alue M Ni s0uared NiKnF, ne)tQele ent!J$alue, ne)tQele ent!Js0uared , $alue6H printf5CCKt This record stored at NpKnF,ne)tQele ent6H printf5CCKt This record points to record at NpKnKnF,ne)tQele ent!Jne)t6H ?D ad$ance pointer to ne)t ele ent in linked list D? ne)tQele ent M ne)tQele ent!Jne)tH B B
218
219
/7ercise 'E /* PLU T"L/- CLWPLUT>*R- .%T" T"- R%<K-& R%/T &>T> /TU;CT;UD? ?D #rite a C progra 1' 2' 2' 3' for the first occurrance of the $alue and deleting that ite . i ple ent as you dee 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 follo#ing 16 26 %nput te)t up to 1,023 characters into an array 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 change it to so e other string #ithout da aging the characters around the point of
220
to allo#
;ser to input ele ents into a linked list ;ser to print linked list for#ards ;ser to add ele ents to end of linked list ;ser to delete any ele ent fro list 5if it is present6 by searching
to
221
printf5F2 print listKnF6H printf 5F3 0uitKn,6H scanf5FNiF,[choice6 H s#itch5choice6 A case 1' hptr M addQite breakH case 2' hptr M deleteQite 5hptr6H 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 A char #ord_40` H struct lle D
223
5hptr6 H
ain D?
t pH 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 scanf5+NsF,[#ord_0`6 H B ?D is the list currently e ptyY D? if 5 ptr MM <;RR 6 A ?D #e are at the head of the list D? ?D get ?D A printf5F alloc failedKnF6H e)i t 5! 26 H B ?D assign $alue and pointer D? strcpy5t p!J$alue,#ord6 H t p!Jp M <;RRH ?D return ne# head of list D? return 5 t p 6H B ore e ory D? alloc si(eof5struct lle6 6H alloc #orked D? t p M 5struct lle D 6 ake sure the if 5 t p MM <;RR 6 a)KnF6H
224
?D tra$erse the list D? #hile 5 ptr!Jp GM <;RR6 A ptr M ptr!JpH B ?D at this point in ti e, ptr is at the end of the list D? ?D get ore e ory D? alloc 5 si(eof5struct lle6 6H alloc #orked D?
printf5F alloc failedKnF6H e)i t 5! 26 H B ?D add ne#ly created tail ite ptr!Jp M t pH strcpy5t p!J$alue,#ord6 H t p!Jp M <;RRH return 5originalQhead6 H B struct lle D deleteQite 5struct lle D ptr6 A char #ord_40`H struct lle D plH struct lle D t pH ?D is there anything %n the listY D? if 5 ptr MM <;RR 6
225
to list D?
A printf5+There are no ite s in listKnF6H ?D return that list is still e pty 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 scanf5+NsF,[#ord_0`6 H B ?D is it at the head of the listY D? if strc p5ptr!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 free 5ptr6 H ?D list is no# e pty D? return 5<;RR6 H B else A ?D return the pointer field of the head as the ne# head D? t p M ptr!JpH free 5ptr6 H return 5t p6 H ?D tra$erse list to find ite D?
226
a)Kn,6 H
e ory back D?
?D sa$e the head of the list D? ?D sa$e the current position D? ?D get the ne)t position D?
#hile 5 ptr GM <;RR 6 if 5 strc p5ptr!J$alue,#ord6 MM 0 6 A ?D delete the ite pl!Jp M ptr!JpH free 5ptr6 H ?D gi$e the 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 B $oid printQlist 5struct lle D ptr6 A if 5 ptr MM <;RR 6 A printf5Flist is e ptyKnF6H 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
D? e ory back D?
B returnH B
228
/* type in your input, press control d for -LP D? ?D 2' run it fro the ter inal prog87 I input file D? that file using ;<%= stdin D? #ill ter inate D? #ill figure it out D?
?D pro$ide the na e of an input file and redirect D ? ?D the input to co e fro ?D #hen -LP is encountered, progra in the data file, syste @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 c M getchar5 6H B B stdin D?
229
rogDD.c
?D progra 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 na e'F6H scanf5FN2:sF, source6H printf5tCOou entered Ns as file to copy fro KnF,source6H in M fopen5source,FrF6H if 5 in MM <;RR 6 A printf5FCannot open Ns KnF,source6H e)it5!16H B printf5F-nter dest filena e' 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 na e of the source file as first line in output file D? fprintf5out,F/L;UC- P%R- <>W- .>/ NsKnF,source6H ?D #rite the na e 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 co plete KnF6H ?D close the files e)plicitly D? fclose5in6H fclose5 out6H B -nter na e of file to be copied' prog83.dat Oou entered prog83.dat as file to copy fro -nter na e of output file' out.1 Oou entered out.l as file to create Pile copy co plete cat out.l /L;UC- P%R- <>W- .>/ prog83.dat &est P%R- <>W- .>/ out.1 the alphabet abcdefghijkl nop0rstu$#)y( the alphabet abcdefghijkl nop0rstu$#)y( the alphabet abcdefghijkl nop0rstu$#)y( the alphabet abcdefghijkl nop0rstu$#)y( the alphabet abcdefghijkl nop0rstu$#)y( the alphabet abcdefghijkl nop0rstu$#)y( the alphabet abcdefghijkl nop0rstu$#)y( the alphabet abcdefghijkl nop0rstu$#)y( /L;UC- P%R- ">& 220 C">U>CT-U/
231
uit .c
This rogram sho!s file i=o and string rocessing The in ut and out ut 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 deli ited file for nu eric 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 te p_20`H ?D 20 character field for te porary string operations D? ?D read directly into here using fi)ed si(es fro struct A char transact_l`H char cusip_9`H char date_9`H char bid_10`H char offer_ 10`H char char char lnu ber_4`H lsy bol_7`H isc_9`H
232
file D?
B recH P%R- Dfp l, Dfp2, Dfp2H 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? ?D file pointers for reading fro and #riting to
?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 ) 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? D? printf5FNs KnF,[rec6H ?D print out the #hole record D? printf5FNc KnF ,rec. transact_0`6' ?D stdout is standard output strea putc5CKnC ,stdout6H ?D add a lf to the output strea D? f#rite5[rec.cusip_0`, 1,9,stdout6H ?D print out each field, one per line 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. lnu ber_0`,1,4,stdout6H putc5CKnC ,stdout6H f#rite5[rec. lsy bol_0`,1,7,stdout6H putc5CKnC ,stdout6H f#rite5[rec.na e_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? lsy bol to type D? type_0` M rec. lsy bol_0`H ?Dtransfer type_1` M rec. lsy bol_l`H type_2` M rec. lsy bo1_2`H ?D builld up the output file for adds, no deli iters 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. lnu ber_0`, 1,4,fp26H f#rite5[rec. lsy bol_0`,1,7,fp26H
234
f#rite5[type_0`,1,2,fp26H f#rite5[rec.na e_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[te p_0` ,[rec.bid_0`, 106H ?D transfer bid to te p D? te p_10` M CK0CH )bid M atof5te p6H )bid M )bid ? 100000# strncpy5[te p_0`,[rec.offer_0`,106H /* transfer offer to te p D? te p_10` M CK0CH )offer M atof5te p6H /* tack on a null D? /* con$ert to float D? ?D tack on a null D? ?D con$ert to float D?
)offer M )offer ? $%%%%%# /* build up output file for updates, space deli iters */ 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
237
238
argtest.c ?D progra ?D $oid int argcH char D arg$_`H A int i M 0H printf5F>rg count argc MJ NiKnF,argc6H printf5FCo and 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 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$ co pletely by typing' to access co and line argu ents D ? ></% $ersion D? ands on the co and line D? @include Istdio.hJ ain5int argc, char D arg$_`6 ain 5 argc, arg$ 6 ?D K [ U $ersion D? ?D count of the nu ber of co ?D the argu ents as strings D?
239
argc) argv) env argc argv env argc , argv e7'+ JF filel JF file+ JF null count of arguments on command line array of strings) arsed command line array of strings) arsed environment
240
241
e7ercise +F
?D #rite a C progra that #ill copy one file to another file D? the co the co and line D? and line LU ?D the user should enter the file na es fro ?D optional brain teaser D ? ?D allo# the user to enter file na es fro if they donCt put any file na es on the co pro pt the for the file na es D? ultiple files si ultaneously D? ?D optional brain buster D? ?D allo# the user to copy one file to ?D is there a li it to ho# any output files they can createYYY D? and line
242
sol+F.c @include Istdlib.hJ @include Istdio.hJ ?D argc is count of nu ber of co $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 A int iH char dest_20`,source_20`H if 5 argc MM 1 6 A
243
printf5FPlease enter source filen ae KnF6H scanf5FNsF, source6H printf5FPlease enter dest filena e KnF6H scanf5FNsF .dest6H B else if 5 argc MM 2 6 A strcpy5source,arg$_l`6H printf5FPlease enter dest filena e 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 co plete KnF6H B
244
245
e ory 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 co piler fro /* opti i(ations of code D ? /* if % did not ha$e the $olatile key#ord here, the co piler #ould re o$e the second state ent 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 re o$ing D?
246
?D RLC>T%L< > D? ?D this is code that is typical in de$ice dri$ers of co unication soft#are, you #ant to #rite to bytes in a ro# to so e chip through its port address D ? ?D an opti i(ing co piler #ould think that you changed the $alue at outport to L)La and then changed it to L)Ld, thus the first state ent changing it to L)La has no $alue, therefore an opti i(ing co piler #ould re o$e the first state ent fro the e)ecutable D? ?D the co piler #ould think that the first D? ?D assign ent is useless and #ould opti i(e D? ?D it out of the code D? ?D the $olatile pre$ents this D? ?D if out port #as assigned to co l port L)2f9 D? ?D and % said D? /* DoutQport M L)LaH D? /* DoutQport M L)LdH D? B
247
s eedl.c
@ifdef 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 ti e to run 1:.3u L.Ls 0' 1: ::N 0V122k LVLio LpfVL# D? @endif ?D co pare the run ti e statistics for /P--&1 to /P--&2 5on ne)t page 6 D?
248
@ifdef /P--&2 ?D speed2.c D? /* de onstrates FfasterF #ay things are done by 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# ore e)perienced progra ers D?
249
GM CK0C is unneccessary
ost efficient
ethod
ore concise D?
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 Progra ing 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 Progra ing 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 Progra ing is Totally Tubular s3 initially is s3 no# is Terrill L#ens s4 initially is s4 no# is C Progra ing 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 deter ine the length of a user input string, use pointers and try to as efficient as possible D? ?D ;se the strlen built!in function to check your #ork D? ake it
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
"o# to print integers Ni No N) Nu N) letters N= letters N@) N@=
rintf in de th
integer base 10 integer base 9 integer base 17 unsigned integer integer base 17, lo#er case integer base 17, upper case integer base 17, lo#er case letters, leading L) integer base 17, upper case letters, leading L=
@define PU printf ain5 6 A int precH float fH int #H PU5Flnteger -)a ples'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 -)a ples'KnF6H PU5CCKtpercent s only, string in field si(ed to fitKnF6H
253
PU5FK112234789:012234789:012234789:012234789:012234789:0KnF6H PU5CCKtNsKnKnCC,CCthe 0uick bro#n fo) ju ped 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) ju ped 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) ju ped 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) ju ped 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) ju ped o$er the la(y dogF6H
254
PU5FPloat -)a ples'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 argu ent D? PU5F-nter a floatKnF6H scanf5FNf, ,[f6H PU5F-nter nu ber of digits after deci al to displayKnF6H scanf5FNiF,[prec6H PU5FKn...................................F6H PU5FN.DtKnKnF, prec,f6H ?D special case #here the precision and total field #idth are an argu ent D? PU5F-nter a fioatKnF6H scanf5FN fC ,[f6H PU5F-nter nu ber of digits after deci al 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-1U/ NVi Ni N.8i print the sign character force a leading space in front of a positi$e ini u field #ith 8 digits, right justified, leading (eroes
PRL>T/ N9.2f N.Df,C,),d6 total field #idth eight, t#o deci al positions default field #idth, ) deci al positions
ND.Df,,),y,d6 total field #idth ), y deci al positions The /trings Ns N4s N.4s N20.4s N!20.4s scanf Ns N4s null ter inated string first fi$e characters 5or until deli iter6 first fi$e characters 5 forget deli iter6 fi$e characters, right justified in 20 character field fi$e characters, left justified in 20 character field
odifiers read in a string deli ited by #s or null read in up to 4 characters deli ited by #s or null read in up to 4 characters until ' deli iter read in up to 4 characters until c deli iter read in up to 4 characters
N4s' N4scN4s
read in characters until #s, null or non abc encountered read in characters until #s, null or abc encountered read in integer, consu e #s, read in charater read in integer, do not consu e #s, read in character
256
rogD..c scanf in de th
?D progra to illustrate reading using scanf D? ?D clearly de onstrates 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 abcdefghijkl the alphabet abcdefghijkl the alphabet abcdefghijkl the alphabet abcdefghijkl the alphabet abcdefghijkl the alphabet abcdefghijkl the alphabet abcdefghijkl the alphabet abcdefghijkl progra iM1 iM1 iM1 iM1 iM1 output c MJ t s MJ he s MJ alpha s MJ b s MJ et nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y(
257
rogD9.c scanf in de th
?D atte pts 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
the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1
sa ple output i M 2 c MJ t trash MJ he alphabet abcdefghijkl nop0rstu$#)y( i M 2 s MJ the trash MJ alphabet abcdefghijkl nop0rstu$#)y( i M 2 s MJ the trash MJ alphabet abcdefghijkl nop0rstu$#)y( i M 0 sMJ trash MJ i M 2 s MJ the trash MJ alphabet abcdefghijkl nop0rstu$#)y( sl MJ the s2 MJ alphabet s2 MJ abcdefghijkl nop0rstu$#)y(
260
Sam le Run :5llustrates logical o erations; >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 co ple enting things LneCs co ple ent of 10001111 01110000 LneCs co ple ent of 00000011 11111100
261
262
main : ; A char a,b,resultH printf5F >nding things together KnF6H printf5F>nd ofKnF6H a M L)9fH b M L)02H ?D 1000 1111 D? ?D 0000 0011 D? => if either bit is -ero) result is F >= dispQbinary5a6H dispQbinary5b6H result ? a L bH printf5CCKnCC6H printf5FLring things together KnF6H printf5FLr ofKnF6H a M L)9fH b M L)02H result ? a N bH result is one >= dispQbinary5result6H printf5CCKnCC6H printf5F=oring things together KnF6H printf5F=or ofKnF6H a M L)9fH b M L)02H result ? a [ bH dispQbinary5result6H
263
dispQbinary5a6H dispQbinary5b6H
?D 1000 1111 D? ?D 0000 0011 D? => if only one bit is one) result is one >=
dispQbinary5a6H dispQbinary5b6H
printf5CCKnCC6H printf5FLneCs co ple enting things KnF6H printf5FLneCs co ple ent ofKnF6H a M L)9fH a ? \aH printf5CCKnCC6H printf5FLneCs co ple ent ofKnF6H b M L)02H b ? \bH dispQbinary5b6H printf5CCKnCC6H ?D 0000 0011 D? dispQbinary5b6H ?D 1000 1111 D? => s!itch ' to F) and F to ' >= dispQbinary5a6H dispQbinary5a6H
264
/7ercise ++
?D #rite a c progra that #ill accept a nu ber fro the user display it in he)adeci al for at then display it in binary for at, one bit at a ti e each bit on a separate line D?
101 base 2
1111111 base 2
265
rogD'.c 8ifdef
?D progra ?D this progra
?D on each co pile, % #ill define *-PLU- or >PT-U differently D ?D on each co pile, % #ill define *-PLU- or >PT-U differently D? ain 5 6 A int iH int su H su A @ifdef *-PLUprintf5Fbefore addition su @endif su @ifdef >PT-U printf5Fafter addition su @endif B printf5Fsu B acc Xo prog81 prog81.c su is 34 is Nd KnF,su 6H M Nd i M Nd KnF,su ,i6H M su V iH M Nd i M Nd KnF,su ,i6H M LH
acc !& *-PLU- !o prog81 prog81.c before addition su before addition su before addition su before addition su M0 i M0 M0 i M1 M1 i M2 M2iM2
266
before addition su before addition su before addition su before addition su before addition su before addition su su is 34
M7iM3 M 10 i M 4 M 14 i M 7 M 21 i M 8 M 29 i M 9 M 27 i M :
acc !& *-PLU- !& >Pf-U !o prog81 prog81.c before addition su after addition su before addition su after addition su before addition su after addition su before addition su after addition su before addition su after addition su before addition su after addition su before addition su after addition su before addition su after addition su before addition su after addition su before addition su after addition su su su is 34 is 34 M0 i M0 M0 i M0 M0 i M1 M1 i M1 M1 i M2 M2iM2 M2 i M2 M7 i M2 M7 i M3 M 10 i M 3 M 10 i M 4 M 14 i M 4 M 14 i M 7 M 21 i M 7 M 21 i M 8 M 29 i M 8 M 29 i M 9 M 27 i M 9 M 27 i M : M 34 i M :
267
evaluation %t is i portant 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 state ent'
a M b V cH only i plies that b and c are added and the result stored in a. .e can 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 sa e on all syste s. int i M :H printf5FNi NiF, i, VVi6H #ill print either : 10 or a#are of it. U-CCLWW-<&>T%L<' <-S-U ake a second reference to a $ariable being eant #as, +if you odified in the sa e e)pression #here the order of e$aluation is undefined. &ennis Uitchie used to say that Fsuch and such is undefinedF .hat he try to do the undefined thing then the results #ill
268
10 10 er should be
this usually does not present any proble s, but the progra
#hat you e)pected,. Then he #ould s ile and say +1arbage %n, 1arbage Lut,, or so eti es just +1%1L,
269
*uicksort.c
@include Istdio.hJ @include I ath.hJ @define int 0uickinde)H
a *uicksort e7am le
W>=Z;%CK
129 ?D array that holds the data D? any ele ents there are D?
?D inde) of ho#
$oid sortdata5int start pos, int endQpos6H int inte pH 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 0uickinde) M 0H #hile 5 fscanf5fd, F NdF, [inte p6 GM -LP6 A ?D store data in array D? 0uick_0uickinde)VV` M inte pH
270
file D?
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 @define
;P
0 1
&L.<
$oid sortdata5int startQpos, int endQpos6 A int te pH int targetQposH int direction M &L.<H int inQendQposH int inQstartQposH int te pQlo#er, te pQupperH inQstartQpos M startQposH inQendQpos M endQposH target pos M startQposH te pQlo#er M startQposH te pQupper 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 5te pQlo#er I te pQupper6 A if 5direction MM &L.<6 A if 50uick_te pQupper` JM 0uick_targetQpos` 6 A ?D no update, te pQupper!!H
272
o$e pointer D?
B else A ?D s#ap $alues D? te p M 0uick_te pQupper`H 0uick_te pQupper` M 0uick_targetQpos`H 0uick_targetQpos` M te pH printdata5 6H ?D change direction of tra$el D? direction M ;PH ?D change pointer to target $alue D? targetQpos M te pQupperH B B else ?D direction of tra$el is ;P D? A if 5 0uick_te pQlo#er` IM 0uick_targetQpos`6 te p Qlo#erVVH else A ?D s#ap $alues D? te p M 0uick_te pQlo#er`H 0uick_te pQlo#er` M 0uick_targetQpos`H 0uick_targetQpos` M te pH printdata5 6H ?D change direction of tra$el D? direction M &L.<H ?D change pointer to target $alue D? targetQpos M te pQlo#erH B B B ?D end #hile D?
273
?D at this point the left and right pointers ha$e ?D sort each of the s aller seg ents D? ?D U-C;U/%L< D? ?D do left side D ? if 5 inQstartQpos I targetQpos ! 1 6 A printf5FCalling left side KnF6H
et or crossed D?
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
$oid e)it5 6H
Pointers To 6unctions
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 A
ain 5 6 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 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
ain
278
procedureQtable is'
an array
of pointers
at functions
structQpointerQarray is
an array
of pointers
to structures of type
ystruct
a pointer
to an array of structures
of type
279
# A
endi7 To $race or 2ot To $race ain 5 6 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 re o$es the else fro and introduces proble the nested if
/* 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 ?D decide for yourself #hich style is 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 ethod D?
281
-nter ) ) 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 state ent #ithin the o$erhead6. -)perience has taught that there are ti es #hen a single state ent #ithin a loop or decision structure needs to ha$e a debug state ent added. This add the braces any#ay. Puting the if 5 $alue ?? : 6 call function5 6H if 5 $alue MM : 6 printf5Fif case true calling functionF6H callQfunction5 6H code #ith debug state ent and added bug code should look like this if 5 $alue ?? :6 A call function5 6H B if 5 $alue MM: 6 A printf5+if case true calling functionF6H callQfunction5 6H B original code in as an afterthought original code eans that you ha$e to ay lead to proble s' are CfreeC 5no code
283
# A
endi7 ain 5 6 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 co piler 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? /* co piler 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 co piler 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, co piler 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
287
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 co piler error since #e are atte pting to add 2 integers 5i and j6 and then dereference the .
289
#PP/2D5U /o e ter inals donCt ha$e keys for 5haracters that you progra . The C language can handle this to a certain e)tent. The echanis refer to the indicated character on their right.
ay need in a C
The follo#ing three keystrokes, #hen used together #ith no spaces bet#een the ,
This techni0ue is useful in the 2280 en$iro ent because the _ and ` characters are not found on the 2280 keyboard. se*uence YYM YY5 YY6 ??& YYJ YY? YYC YYG ??' @ _ ` A B K ^ ] (
290
A%ter 6$ *ecided 7e Co ldnAt <rite +ne /ore 8ro#r!m:::: 7e St!rted <ritin# NoBel(' 8le!(e Con(ider .e!din# $Ce 8!ttern 5itA( !"o t ! 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 technothriller 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 mo nt!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% E inte' D!ter' ice' %i(Cin#' (Dimmin#' "o!tin#' !nd droDnin# Dere Ber& e!rl& in%l ence( !nd !ppe!r %reF entl& in Ci( Dork: Ed c!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 co ntle(( Co r( (t d&in# ! Dide r!n#e o% ( "Gect( incl din# m!tC' En#li(C' comp ter (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 %o ndin# 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 %o nd !top cr!#( in <e(t 9ir#ini!' C!li%orni!' $ex!(' NeD /exico' NeB!d!' 2ent ck&' /exico' !nd It!l&: .ock clim"in# !ppe!r( %reF entl& in Ci( Dritin#: 6$ C!( Ditne((ed %ir(tC!nd m!n& tr! m!tic eBent( incl din# tCe <orld $r!de Center ,om"in#' tCe Lon# I(l!nd .!ilro!d SCootin#' ! "e!r !tt!ck' ! pl!ne cr!(C' !nd n mero ( %!t!litie(' in tCe mo nt!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