Anda di halaman 1dari 296

88 C Programs

by JT Kalnay

This book is dedicated to Dennis Ritchie and to Steve Jobs.

To Dennis for giving us the tools to rogram.

To Steve for giving us a reason to rogram.

Published by jt Kalnay

Copyright 2012, JT Kalnay

This book is licensed for your personal use. This book "o#e$er, this book ay not be re!sold.

ay be freely gi$en a#ay to other people.

%f you #ould like to share this book #ith another person, please feel free to do so.

&isco$er other titles by jt Kalnay at' !!!."tkalnay.com

#bout This $ook


This book is not organi(ed in a traditional chapter for at. %nstead % ha$e chosen to include e)a ple progra s that e)hausti$ely illustrate the i portant points of C in an e$olutionary #ith standard algorith s. The progra s that % present are not, by the sel$es, co plete applications. The progra s are +single!issue teaching progra s,. -)perienced progra learning a ne# language ha$e told e ti e and ti e again that they ers #ho are ainly #ant to see ers tell anner. *y #orking through these progra s and are fa iliar you can teach yourself C. % assu e you already kno# ho# to progra

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

ost straightfor#ard ore subtle or

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.

er and are able to learn #ell on

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

ode arith etic

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

linked list pointers alloc, e ory allocation

$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

Sim lest C rogram ossible

A B

ain is a C key#ord. %t is the progra entry point.

%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

Sim le rogram !ith rintf out ut

>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?

?D in its si plest for ?D it

printf takes a character string to display D?

ay also take other argu ents, #e #ill e)a ine these

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

rog'.c (ore on Printf


?D stdio.h is the standard input library that pro$ides printf, scanf, and other i?o routines D? ?D @include tells the co piler #here to look for input?output routines you call D? ?D @include I na e of .h file J #ill add that .h file to your co pilation @include Istdio.hJ int A ?D curly brackets state ent. > co pound state ent of a conditional, se$eral state ents, E D ? printf5FC Progra printf5FC Progra B printf5Fstring to displayF6H ?D string to display is inside 0uotations, D? ?D can pro$ide for at specifiers that describe "L. to display things 5e.g., as integers, as strings6 D? ?D if you put in a for at specifier you need to pro$ide a $ariable to satisfy the for at specifier D? printf5Fstring for at specifierF, $ariables to satisfy for at specifiers6H ingKnF6H ingKnF6H ay be a function body, the body of a loop, the body ark the beginning and end of the scope of a co pound ain 5 6 odule D?

11

rogl.c su

lemental variable declaration) rintf out ut) return value

?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

e)ecutable can be run by typing a.out D?

?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

> co pound state ent

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?

?D the ne)t progra

sho#s that printf returns the nu ber of characters it printed. D?

12

C Progra

ing

$alue of )y( is 13 C Progra ing

@include Istdio.hJ int A ?D int declares )y( as a $ariable of type integer D? int )y(H ain56

?D )y( gets return $alue fro )y( M printf5+C Progra

printf D?

ingKn,6H

?D Ni for at specifier says print out the $alue of )y( as an integer D?

printf5+$alue of )y( is Ni Kn,,)y(6H

?D #e can ignore the return $alue of printf D? ?D Kn is the ne#line character D?

printf5+C Progra B ?D progra

ingKn,6H

e)it point D?

13

Com ile) link) run se*uence


Oou can co pile C odules to produce object files odules to produce object files Oou can asse ble >sse bler

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

.c file .o file .as file

c file object file asse bler file ANSI C Compiler

.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

comments case sensitivity

@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

printf5FPor fun and profitKnF6H ?D co

ents can be at the end of a line D?

printf 5F"ello ?D this is not a co print?Dco

ent D? dolly KnF6H


Compiler Error

ent cannot be nestedD?f5F"1KnF6H

printf5FabcKnF6H printf5FdetKnF6H

?D co

ents that span lines

can cause une)pected resultsE D?

?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

/torage Classes Table %


Type >uto "o# &eclared >uto key#ord or in function or in block /tatic key#ord in function or block Lutside all functions Uegister key#ord /tatic key#ord outside all functions .here /tored /tack %nitial Salue <one /cope Punction or block Punction or block -ntire progra /a e as auto /a e file after definition Rifeti e Punction or block -ntire life of progra -ntire life of progra /a e as auto -ntire life of progra

/tatic internal -)ternal Uegister /tatic e)ternal

"eap

Tero if not e)plicitly initiali(ed Tero if not e)plicitly initiali(ed <one Tero if not e)plicitly initiali(ed

"eap > register, if one is a$ailable "eap

C supports different storage classes that you can force by using e)plicit key#ords.

16

rog,.c variable declaration and initiali-ation


@include Istdio.hJ

int 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

typeQofQ $ariable int float char

na e1, na e2, E H ),y,(H f1 ,f2H c1, c2H ?D first char D ? ?D another char D ?

typeQofQ $ariable int float

na eQofQ $ariable M initialQ$alueH a f1 M 8H M 7.8fH

type na e M initial, na e M initial, ... H int a M 7, b M 12, c M 12H

18

rog..c
?D this progra

rintf out ut of variables


adds t#o integer $alues and D?

@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 print result D? printf5FThe su of Ni and Ni is NiKnF,$%,$2,$su 6H

?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

%P/R#T%RS0 R/T1R2 3#41/ #2D S5D/ /66/CTS

%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

mathematics o erators addition subtraction V !

ultiplication D di$ision assign ent ? M

incre enting VV decre enting !!

o s.c
ain 5 6 A int i.)' i M LH ) M iVVH incre entD?

rogram to demonstrate c o erators

?D post incre ent, return $aule is LR& $alue, side effect is

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

?D pre incre ent, return $aule is <-. $alue, side effect is

?D post decre ent, return $aule is LR& $alue, side effect is

?D pre decre ent, return $aule is <-. $alue, side effect is

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

Solution for /7ercise '


@include Istdio.hJ int A int a, b, c, resultH a M 4H b M 3H c M 2H result M 5 b D b6 X 53 D a D c6H ?D using the 5 6 re o$es doubts about the order of operations... D? printf5FNi s0uared ! 5 3 D Ni D Ni 6 MJ Ni KnF, b,a,c,result6H B ain 5 6

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

conditional include of code perfor te)t substitution

if not defined, include the follo#ing code else for any @if else if for any @if end of @if block

27

rog.a.c 8ifdef recom iler


ain 5 6 A @ifdef >>> printf5Fhello fro @endif @ifdef *** printf5Fhello fro @else printf5F.hat you donCt like bbbYKnF6H @endif @ifndef CCC printf5FdefineCCC to stop @endif B %f you co pile like this' acc prog3a.c and run a.out, you see' .hat you donCt like bbbY define CCC to stop e before % print againGGG e before % print againGG KnF6H bbbKnF6H aaaKnF6H

%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

define CCC to stop

%f you co pile like this' acc !&CCC prog3a.c


28

and run a.out, you #ill see .hat you donCt like bbbY

29

rog9.c

C basic data 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

ay be initiali(ed #hen defined D?

to sho# declaring $ariables D?

/* and initiali(ing $ariables D? M M M M CaCH 1.22eV34 122.34H H 221H

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

er does not specify it for ranges ha$e been

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

!if you need a data $alue the si(e of a platfor 6

achine #ord 5and adjusts cross! code or

use an int 5handy #hen #riting operating syste interrupt handlers6

!analysis of the data #ill also help you decide #hether you need specify signed or
36

unsigned, if there is a need to specify it please do so. Lne last #ord for no# ... Wany C 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

rog<.c mathematics o erators) recedence


ain 5 6 A /* declare four integers and space for ans#ers D? int a M 1H int b M 2H int c M 2H int d M 3H int ansH ?D precedence of ! V D 5 6 parentheses ! unary inus V unary plus VV incre ent !! decre ent D ultiplication ? di$ision N odulo V addition ! subtraction MM e0uality M e0uals D? ?D print initial $alues D? printf5Fa MJ Ni Kt b MJ Ni Kt c MJ Ni Kt d MJ Ni KnKnF,a,b,c,d6H ?D subtraction e)a ple D? ans M a ! bH printf5Fa ! b M Ni KnF,ans6H ?D precedence proble , #ant addition then ans M a V b D cH printf5Fa V b D c M Ni KnF,ans6H ?D precedence e)a ple D? ans M 5 a V b 6 D cH printf5F5 a V b 6 D c M Ni KnF,ans6H B
=> sam le out ut >= a ?@ ' b?@ + c?@, d?@. a A b ? B' a Cb>c?D : a C b; > c ? E

ultiplication D?

38

rogD.c
?D progra di$ision D?

mi7ed mode arithmetic


de onstrates athe atics, precedence and the difference bet#een integer

?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

rog8.c the modulus :remainder) residue; o erator


/* the A int gu(intaH int re H gu(inta M 24 ?4H re M 24 N 4H printf5F4 goes into 24 Ni ti es #ith re ainder Ni KnF,gu(inta, re 6H gu(inta M 24 ? 8H re B output youCll see 4 goes into 24 4 ti es #ith re ainder 0 8 goes into 24 2 ti es #ith re ainder 3 M 24 N 8H printf5F8 goes into 24 Ni ti es #ith re ainder Ni KnF,gu(inta.re 6H odulus operator only #orks on #hole nu bersD? ain 5 6

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

Relational :Com arison; % erators


I J M IM JM GM less than greater than e0ui$alent to less than or e0ui$alent to greater than or e0ui$alent to not e0ui$alent to

Uelational operators are used in relational e)pressions. > relational e)pression is defined as anything that can produce a True or Palse ans#er. Palsity is defined as (ero. Truth is defined as non!(ero. > $ariable by itself can be a relational e)pression because its $alue #ill be e)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

?D ste$e.c >ugust 10, 1::2 D?


ain 5 6 A int ), y, (H y M 2H ?D y M 2 is a relational e)pression D ? ?D its truth or falsity is assigned to ) D? ) M y MM 2H ?D assign to ) the result of the co parison D? printf5F>>> ) M Ni y M NiKnF,),y6H y M 2H ?D y MM 2 is a relational e)pression D ? ?D its truth or falsity is assigned to ) D? ) M y MM 2H printf5F*** ) M Ni O M NiKnF,),y6H ) MM yH ?D no side effect, return $alue not used, this does nothing D? printf5FCCC ) M Ni y M NiKnF,),y6H ) I yH printf5F&&& ) M Ni y M NiKnF,),y6H ( M ) I yH printf5F--- ( M Ni ) M Ni O M NiKnF,(,),y6H ?D sa ple output D? >>> )M L y M 2 *** ) M 1 y M 2 CCC ) M 1 y M 2 &&& ) M 1 y M 2 --- ( M 1 ) M 1 O M 2 Uun this progra through alint and see that it tells you that there are se$eral bugs.

46

rogEa.c three ty es of loo s


ain 5 6 A int su H int nH ?D su and loop counter need to be initiali(ed D? su M 0H n M !4H ?D #hile 5relational e)pression6 D? ?D #hile loop, check condition at top D? #hile 5 n IM 4 6 A su M su V nH n M n V 1H printf5Fn is Ni su is Ni KnF,n,su 6H B printf5F."%R- RLLP'su is Ni KnKnKnF,su 6H ?D do loop, check condition at botto D? su M 0H n M !4H do A su M su V nH n M n V 1H printf5Fn is Ni su is Ni KnF,n,su 6H B #hile 5 n, IM 4 6H printf5F&L RLLP'su is Ni KnKnKnF,su 6H ?D for loop, C shorthand to get all loop things on one line D? for 5 su M 0, n M !4H n IM 4H nVV 6 A su M su V nH B ?D print out the results D? printf5FPLU RLLP'su is Ni KnKnF,su 6H B

47

roglF.c for loo


/* progra D? a in 56 A int s0uareH int nH printf5FT>*R- LP /Z;>U-/ <;W*-U/ KnKnF6H printf5CCKt n Kt n s0uaredKnF6H printf5CCKt!!!Kt!!!!!!!!!!KnCC6H for 5 n M 1H n IM 20H nVV 6 A s0uare M n D nH printf5CCKt Ni Kt Ni KnF,n,s0uare6H B B Kt is the tab character to calculate s0uares

48

T>*R- LP /Z;>U-/ <;W*-U/

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

Co parison of Roop /ynta)

Por a M 1 to 28 by 2

St!rtin# Condition

Condition $o Contin e

increment done !%ter "od&' "e%ore te(tin# condition

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

Wake the pre$ious progra by 2Cs. i.e, 10 12 13 17 ...

do the table of s0uares fro

10 to

-)ercise' !8

Wake the pre$ious progra by !2Cs i.e. 22, 20,28,23 ...

do the table of s0uares fro

22 to

51

rog''.c for loo


?D progra ?D introduces scanf for user input D? ain 5 6 A int s0uareH int cubeH int nH int user nu berH

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

rog'+.c nested for loo s II1kranian doll for loo sG II(atreshkaII


/* progra ain 5 6 A int s0uare, n, userQnu ber, counter, iH ?D this loop #ill be done four ti es D? ?D counter #ill take on the $alues, 1 223 D? for 5counter M 1H counter I 4H counterVV 6 A printf5F"o# far do you #ant to go toY KnF6H scanf5FNiF,[userQnu ber6H printf5CCKtOou entered Ni KnKnF,userQnu ber6H ?D Kf for printf5FT>*R- LP /Z;>U-/ KnKnF6H printf5CCKt n Kt n s0uaredKnF6H printf5CCKt!!!Kt!!!!!!!!!!KnCC6H ?D this loop #ill be done userQnu ber ti es D? ?D n #ill take on $alues 1 through userQnu ber D? for 5n M 1H n IM userQnu berH nVV 6 A s0uare M n D nH printf5CCKt Ni Kt Ni KnF,n,s0uare6H B /* end of n loop D? B ?D end of counter loop D ? printf5CCKnKnCC6H ?DCLWWL< PUL1U>WW%<1 W%/T>K-/ D? for 5 i M 0H i I 4H iVV 6 A printf5Fouter i M Ni KnF,i6H
55

to calculate s0uares D ?

?D introduces nested for loop 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 i and j are ints


.hat .ould be PrintedY for 5 i M 0H i I 4H i VV 6 A for 5j M 4H j J 2H j!! 6 A printf5FNi NiKnF .i.j6H B B

>ssu e ) and
) M 4H #hile 5 ) I 106 A M ) D 10H do A

are ints

printf5FNi Ni KnF .). 6H M V 5 ?26H B #hile 5 ) M ) V 2H B I 200 6H

57

rog',.c !hile loo


?D #hile loop D ? ?D introduces Ka, ansi alert characterD ? ain 5 6 A int iH int su i M !4H #hile 5 i IM 4 6 A printf5+Ka i M Ni KnF,i6H su iVVH B printf5F/u fro !4 to 4 is Ni KnF,su 6H VM iH M 0H

?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

rog'..c !hile loo for secret number guessing


?D #hile loops D? ?D progra ain 5 6 A int guess M !1H int secret M 8H int count ofCguesses M 0H printf5FTry to pick a nu ber fro 1 to 10 KnF6H to ask for guesses until they get it right D?

?D possible infinite loop if user is real idiot D? #hile 5 guess GM secret6 A count ofCguessesVV' printf5F-nter a guess KnF6H scanf 5FNiF,[guess6H printf5CCKn Oou entered Ni KnF ,guess6H B ?D end #hile D? printf5+Oou got it after Ni tries KnF,countQofQguesses6H B

60

prog'9.c !hile loo vs. do loo


/* progra loop */ ain 5 6 A int guessH int secret M 8H int countQofQguesses M 1H printf5FTry to pick a nu ber fro 1 to 10 KnF6H /* possible infinite loop if user is real idiot */ /* need to preinitiali(e $alue for #hile loop */ printf5F-nter guess @NiKnF,countQoCguesses6H scanf 5FNiF,[guess6H printf5CCKn Oou entered Ni KnF ,guess6H #hile 5 guess G M secret6 A printf5F.UL<1KnF6H CL<TULR #ill return fro co background control #ill return as soon as the place ent has occurred syste ("usr/demo/SOUND/play the syste state ent #hen the entire and #as placed in the to let user guess secret nu ber */ /* sho#s difference bet#een #hile loop and do

and has been co pleted. %P T"- co

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

printf5FTry to pick a nu ber fro countQofQguesses M 0H secret M 2H

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

Solution for /7ercise .


main : ; A int i, factorialH factorial M 1H for 5 i M 1H i IM 10H iVV6 A factorial M factorial D iH printf5+NiG?tNiKn,,i, factorial6H B B

64

/7ercise 9
/* #rite a c progra ?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?

Solution for /7ercise 9


main: ; A int iH int outnu H rintf:G5n ut number lease JnG;H scanf:GKiG )Li;H !hile :i @ F; A outnum ? i K 'FH rintf:GKiJnG )outnum;H i M i = 'FH B B

65

C
if .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

rog'<.c math.h include file


/* if state ent D? ?D ath.h contains 8include Mmath.h@ ain 5 6 A float nu berH float s0uareQrootH printf5CCKnKnType in a nu ber KnF6H scanf5FNf,,[nu ber6H printf5CCKnOou entered NfKnF,nu ber6H if 5 nu ber I 0 6 A printf5FCanCt get s0uare root of negati$e nu ber KnF6H B else A s0uareQroot M s0rt5nu ber6H printf5FThe s0uare root of Nf is NfKnF,nu ber,s0uareQroot6H B printfC5+Progra B ?D -=-UC%/- re o$e the @include I ath.hJ line and see #hat you get D? /* so e 5but not all6 of the ceil5)6 floor5)6 sin5)6 cos5)6 tan5)6 asin5)6 acos5)6 atan5)6 sinh5)6 cosh5)6 tanh5)6 e)p5)6 log 5)6 loglL5)6 po#5),y6 D? ath functions a$ailable for a co plete list, consult your co pilerCs docu entation co pleted KnF6H athe atical functions like s0rtL D?

67

rog'E.c logical o erators and relational e7 ressions


?D precedence of logical operators and brackets D ? ?D I IM J JM MM GV [[ ]] less than less than or e0ual to greater than greater than or e0ual to e0uality ine0uality logical and logical or ain 5 6 A int scoreH printf5F-nter the scoreKnF6H scanf5FNiF,[score6H printf5FOou entered NiKnF,score6H if 5 score I 0 ]] scoreJ 100 6 printf5+% possible scoreKn,6H else A if 5 score JM 0 [[ score I 40 6 printf5FPKnF6H else A if 5 score JM 40 [[ score I 806 printf5+&Kn,6H else A if 5 score JM 80 [[ score I 906
68

printf5+CKn,6H else if 5 score JM 90 [[ score I :06 printf5+*Kn,6H else if 5score JM :0 [[ score IM 1006 printf5,>Kn,6H else printf5+no #ay to get here Kn,6H B B B B

69

if : relational e7 ression;

relational e7 ression evaluates to TR1/ or 6#4S/

if : : r e l6 ]] : r e +; ; NN is the logical or o erator

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

rog+F.c com le7 decision structures


@define @define @define @define ain 5 6 A int stock sy bolH char pQorQcH char crH printf5CCKn-nter stock sy bo%KnF6H printf5F 1 printf5F2 %*WKnF6H WW&KnF6H printf5F2 W-U Kn,6H printf5F3 Z;%T Kn,6H %*W 1 W-U 2 WW& 2 Z;%T 3

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

W-U 2 WW& 2 Z;%T 3

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

printf5F5P6referred or 5C6o scanf5FNcF,[pQocc6H scanf5FNcF,[cr6H

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#.

Ueport the re aining range of possiblities for the

77

Solution for /7ercise <


ain 5 6 A int secretH int guessH int nu Qgu esses M 0H int hi M 100H int lo M0H int seedH printf5F.hat ti e is it hh' srand5 seed6H ?D rando secret M 5int6 rand56 ? 220H if 5 secret I 0 6 secret M 0H if 5secretJ 100 6 secret M 100H ?D ake sure that guess is incorrect to begin #ith D? guess M secret ! 1H #hile 5 5secret GM guess6 [[ 5nu guesses I 86 6 A nu QguessesVVH prfntf5F-nter a guess bet#een Ni and NiKnF,hi,lo6H scanf5FNiF, [guess6H printf5CCKnOou entered NiKnF,guess6H
78

'ssKnF6H

scanf5FNi'Ni'NiF,[seed,[seed,[seed6H nu ber function D?

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 ?

?D the 0uadratic e0uation a)^2 V b) V c D?

80

Solution for /7ercise D


@include I ath.hJ ain 5 6 A float a, b, cH float discri inantH float )l, )2H printf5FKnKninput a b and c separated by spaces KnF6H scanf5FNf Nf NfC,[a,[b,[c6H printf5Fyou entered Nf Nf NfKnKnKnF,a,b,c6H discri inant M 5 b D b6 ! 5 3 D a D c6H if 5 discri inantJ 0 6 A if 5a MM 06 A if 5 b MM 0 6 A printf5F) M 0 KnF6H else A )l M 5!c6?bH printf5F/ingle real root is NfKnF,)l6H B B else A )l M 5 !b V s0rt5bDb ! 3DaDc66 ? 52 D a6H )2 M 5 !b ! s0rt5bDb ! 3DaD66 ? 5 2 D a6H printf5FT#o real roots are KnF6H printf5FNf NfKnF,)l,)26H B
81

else if 5 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

Solution for /7ercise 8


?D #rite a c progra D? /* print out the nu ber, one digit per line D? ?D i.e. input 1223 D? ?D output 3 2 2 1 D? . ?D then print it out in re$erse order D? ?D then print the english #ord beside each digit D? char D #ords_` M A FTeroF, F;nF, F&eu)F, FTroisF, FZuatreF, FCin0F, F/i)F, F/eptF, F"uitF, F<euf,BH ?D solution D? ain 5 6 A int i,safe,outnu H int re$nu M 0H printf5F%nput nu ber KnF6H scanf5FNiF,[i6H #hile 5i J 06 A outnu re$nu M i N 10H M re$nu ?D strip off last digit D? D 10 V outnu H
84

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

#hile 5 re$nu A outnu re$nu B printf5CCKnKnCC6H

J06 M re$nu ?M 10H N 10H ?D strip off last digit D?

printf5FNi KnF,outnu 6H ?D print it D?

?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

?D the precedence of operations D? j M 1 V 2 ! 2 D 3? 4 ? 7 D 8 ! 9 V :H pri f5FJ M Nd KnF,j6H


88

@if 0 j M LneH printf5Fj M Nd KnF,j6H @endif ?D forgetting the [ character in scanf calls #ill cause core 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

rog++.c sim le array


/* introduces si ple array */ ?D note that inde)ing goes fro /* starting at inde) 0 */ ain5 6 A int array'R9SH int iH arrayl_0` M 22H array1_1` M 18H array1_2` M 2:H array1_2` M 2H array1_3` M !8H for 5 i M 0H i IM 3H iVV 6 A printf5Farray1_Ni` M Ni KnF,i,array1_i`6H B ?D arrayl_0` M 22 array 1 _1` M 18 array1_2` M 2: array 1 _2` M 2 array 1 _3` M!8 D? 0 to 3 */ /* declaration synta) indicates 4 cells */

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

rog+,.c array boundaries


ain5 6 A int array1_4` M A 22, 18, 2:, 2, !8 BH ?D print out $alues in array D? for 5i M 0! i IM 3! iVV6 printf5Farrayl_Ni` M Ni KnF,i,arrayl_i`6H ?D print out $alues in array and beyond boundaries of array D? for 5 i M !3H i I 10H iVV 6 printf5Farrayl_Ni` M Ni KnF,i,arrayl_i`6H B ?D sa ple output D? array 1 _0` M 22 array1_1` M 18 array1_2` M 2: array1_2` M 2 array 1 _3` M!8 array 1 _!3` M 2 array1_!2` M 17 array1_!2` M !212040:448 array1_!1` M !1 arrayl_0` M 22 array 1 _1` M 18 array1_2` M 2: array1_2` M 2 array 1 _3` M!8 array1_4` M 0 array 1 _7` M 0 array 1 _8` M 0 arrayl_9` M 0 array 1 _:` M 0

93

rog+9.c more array boundaries


?D note that $alues are assigned beyond declared space D? ain 5 6 A int array 1_4`H int iH /* $alid initiali(ation D ? arrayl_0` M 22H arrayl_1`Ml8H array1_2` M 2:H arrayl_2` M 2H arrayl_3` M !8H ?D these $alues are stored but canCt be addressed D? ?D you can read fro the but you canCt #rite to the D? ?D because they are not part of your data space D ? ) M array 1 _4` M 23H array1_7` M :939H array'RDS ? B,8.E9H for 5 i M 0H i IM 8H iVV 6 printf5Farrayl_Ni` M Ni KnF,i,arrayl_i`6H / *sa ple output array 1 _0` M 22 arrayl _l` M 18 array 1 _2` M 2: array 1 _2` M2 array1 _3` M! 8 arrayl _4` M
94

0 arrayl _7` M 0 array1 _8` M 0 D? Z;-/T%L<Y .ill ) be set to 23 or 0Y >ns#erG 23, e$en though array 1 _4` is not setG <LT-' on 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

rog+<.c bo!ling scores) array rocessing


?D progra scores D? ?D only count scores o$er 100 for personCs a$erage D? ?D print out the high and lo# scores, all scores, scores used in a$erageD? ?D print out a$erage D? @define @define @define @define ain 5 6 A /* scores #ill be the array of scores entered D ? int scores_W>=Q/CLU-/`H ?D nu scores is the count of ho# int nu scores, i, scoreH /* scoresQtoQcount are used to keep track of ho# #ere D? int ra# QscoresQtoQcount M 0H int leagueQscoresQtoQcount M 0H int scoreQtotal M 0H ?D the a$erages are floats because % #ant floating point accuracy */ float ra#Qa$erageH float leagueQa$erageH ?D initiali(e current high and lo# score D? int high M 0H int lo# M W>=Q/CLU-H
96

to calculate the a$erage of a set of bo#ling

W>=Q/CLU-/ W>=Q/CLUW%<Q/CLU-

100 200 0 100

W%<QR->1;-Q/CLU-

any scores they #ant to enter D?

any $alid scores there

?D find out ho# entering D? printf5F"o#

any scores the person #ill be

any scores #ill you be enteringYF6H

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#

any scores #ill you be enteringY

Oou entered 10 scores -nter score @1' Oou entered 100 -nter score @2' Oou entered 200 -nter score @2' Oou entered 200 -nter score @3' Oou entered ! 2 % possible score -nter score @4' Oou entered 40 -nter score @7' Oou entered 100 -nter score @8' Oou entered 200 -nter score @9' Oou entered 200 -nter score @:' Oou entered 8: -nter score @10' Oou entered 308 % possible score Ua# a$erage M 177.12 "igh score #as 200 Ro# score #as 40 R%/T LP R->1;- /CLU-/ ;/-& %< >S-U>1200 200 200 200 Reague a$erage M 240.00

99

rog+D.c character arrays


Ls address of s s value of s >s value stored at address stored in s ?D progra to illustrate initiali(ing a character array D? ?D #ill be initiali(ed three different #ays D? ?D null ter inator is added to #ord1 D? ?D si(e of #ordl #ould be deter ined at initiali(ation ti eD? int i,tH char #ordl_` M AFabcdefghijFBH ain 5 6 A char #ord2_` M AF12234789:012234789:FBH ?D null ter inator is not added to #ord2 D? ?D si(e of #ord2 #ould be deter ined at initiali(ation ti eD? char #ord2_` M A C"C, CeC, ClC, ClC, CLC, CGC BH char #ord3_` M AF>*C&-P1"%JKRW<LPFBH ?D null ter inator is added to s si(e of s is si(e of pointer to char D ? ?D space for s is allocated at initiali(ation ti e since the thing in double 0uotes ust be stored so e#here The space for character string is ade on stack D? char D s M AFstill yet another #ay, pointer to characterFBH for 5 i M 0H i I 20H iVV 6 printf5FNc N)KnF, #ord1_i`, #ord1_i` 6H printf5CCKnCC6H ?D this is a really terrible thing to do, calling a subroutine o$er and o$er each ti e it is called it returns the sa e $alue. D? for 5 i M 0H i I si(eof5#ord16H iVV 6
100

printf5FNcF, #ord 1 _i`6H printf5CCKnCC6H printf5FNsF,#ord16H ?D this is uch better D? printf5CCKnCC6 H for 5i M 0H i I 20H iVV 6 printf5FNc N)KnF, #ord2_i`,#ord2_i`6H printf5CCKnCC6H t M si(eof5#ord26H printf5Fsi(eof #ord2 is Ni KnF,t6H for 5 i M 0H i I tH iVV 6 printf5FNcF, #ord2_i`6H printf5CCKnCC6H printf5FNsF, #ord26H printf5CCKnCC6H for 5 i M 0H i I 20H iVV 6 printf5FNcF,s_i`6H printf5CCKnCC6H for 5 i M 0H i I si(eof5s6H iVV 6 printf5FNcF,s_i`6H printf5CKnF6H for 5 i M 0H i I si(eof5Ds6H iVV 6 printf5FNcF ,s_i`6H printf5CCKnCC6H printf5FNsF,s6H printf5+KnF6 H
101

102

%ut ut QouIll See


a 71 b72 c 72 d73 e 74 f77 g 78 h 79 i 7: j 7a 0 1 21 2 22 2 22 3 23 4 24 7 27 8 28 9 29 : 2:

abcdefghij abcdefghij " 39 e 74 l7 c 1 7c o 7f G 21 1 21 2 22 2 22 3 23 4 24 7 27 8 28 9 29 : 2: 0 20 1 21 2 22 2 22 3 23 si(eof #ord2 is 7 "elloG "elloG 12234789:012234789: still yet another #a stil s still yet another #ay, pointer to character

103

/7ercise E
/* #rite a progra /* .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

Solution for /7ercise E


int A int array_l0` M A1, 2,4, !2, !7, 8, 3, :, 12,:22 BH int i, hipos, lopos, te pH hipos M lopos M 0H printf5FLriginal >rray KnF6H for 5 i M 0H i I 10H iVV 6 A printf5F>rray position Ni $alue Ni CnF,i,array_i`6H if 5 array_i` J array_hipos` 6 hipos M iH if 5 array_i` I array_lopos` 6 lopos M iH B printfC5+Rargest $alue is Ni at inde) Ni KnF,array_hipos`,hipos6H printf5F/ allest $alue is Ni at inde) Ni KnF,array_10pos`,lopos6H ?D s#itch lo#est $alue to position 0, fro D? te p M array_lopos`H array_lopos` M array_0`H array_0` M te pH printf5F;pdated >rray KnF6H for 5 i M 0H i I 10H iVV 6 printf5F>rray position Ni $alue Ni CnF,i,array_i`6H B ?D end ain D? o$ing position 0 to #here lo#est ca e ain 5 6

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

Solution for /7ercise 'F


ain 5 6 A int array_l0` M A 1,2,4, !2, !7, 8, 3, :, 12,:22 BH int te pH int i,jH printf5FLriginal unsorted array KnF6H for 5 i M 0H i I 10H iVV 6 A printf5FNiKtNiKnF ,i,array_i`6H B for 5 i M 0H i I :H i CC 6 A for 5j M i V 1H j I 10H jVV 6 A if 5 array_j` I array _i` 6 A te p M arrayjj`H arrayjj` M array_i`H array_i` M te pH B ?D end if D? B ?D end for j loop D? B ?D end for i loop D? printf5CCKnKn/orted >rrayKnF6H for 5 i M 0H i I 10H iVV 6 printf5FNiKtNiKnF ,i,arra y_i`6H B

107

6unction definition and rototy es


.hen #e @include Istdio.hJ #hat happensY The file stdio.h gets i beddeed into our progra . The file stdio.h contains the prototypes for functions like printf 5and other stuff6. > prototype is a declaration of #hat the interface for a function looks like. Por printf it is' unsigned printf5char D, ... 6H This indicates that the printf function returns an unsigned int, and re0uires at least one argu ent, #hich ust be a character string.

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

rog+E.c elementary function declaration and usage


/* definition of subroutine D? ?D should be defined before it is used D? ?D type of $alue it returns na e type of argu ents it e)pects D? ?D progra is called D? $oid subr15$oid6 ?D this is called the function header D? A printf5F%n subroutineKnF 6H returnH B /* this is #here progra e)ecution starts D? ain5 6 A ?D declaring that state ent D? $oid subr15$oid6H printf5F%n subr15 6' printf5F*ack in B
109

e)ecution does not start here D ?

?D this code is only e)ecuted #hen the subrl routine

ain #ill call subr1 D?

?D function prototype header needs to go before first e)ecutable

ain

routine KnF6H ain routine KnF6H

?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

rog,F.c calling subroutines


/* definition of subroutine D? ?D should be defined before it is used D ? /* type of $alue it returns na e type of argu ents it e)pects D? ?D progra e)ecution does not start here D? ?D this code is only e)ecuted #hen the subrl routine is called D? void subr':void; A printf5F%n subroutineKnF6H returnH B /* this is #here progra ain5 6 A ?D declaring that void subr':void;H printf5F%n subr': ;H subr15 6H subrl 5 6H printf5F*ack in B ain routine KnF6H ain routine KnF6H ain #ill call subrlL D? e)ecution starts D?

111

rog,'.c assing constants to subroutines


/* definition of subroutine, should be defined before it is used D? ?D type of $alue it returns na e type of argu ents it e)pects D? ?D progra e)ecution does not start here D? ?D this code is only e)ecuted #hen the subrl routine is called D? $oid subr15int n6 A /* n is a local $ariable 5argu ent6 #hoCs purpose is to D? ?D recei$e a copy of the para eter passed fro ?D i is a local $ariable it #i11li$e on stack D? ?D it #ill be deallocated #hen routine e)its D? int iH for 5 i M 0H i I nH iVV 6 printf5F%n subroutine i M Ni n M Ni KnF,i,n6H returnH B /* this is #here progra ain5 6 A ?D declaring that $oid subr15int6H printf5F%n subr1 546H printf5F*ack in B
?D sa ple output D? %n ain routine %n subroutine i M 0 n M 4 %n subroutine i M 1 n M 4 %n subroutine i M 2 n M 4 %n subroutine i M 2 n M 4 %n subroutine i M 3 n M 4 *ack in ain routine

ain routine D?

e)ecution starts D?

ain #ill call subr15 6 D?

ain routine KnF6H

?D calling subrl, sending 4 by $alue D? ain routine KnF6H

112

rog,+.c assing variables to subroutines


?D progra */ $oid subr15int n6 A ?D n is an argu ent passed fro $ariable */ /* i is a local $ariable, it #ill li$e on stack */ /* it #ill be deallocated #hen routine e)its, as #ill n */ int iH ?D static $ariable li$es in data area, itCs $alue D? ?D is retained bet#een calls be#are of static $ariables */ ?D in general, assu e no static area is a$ailable */ ?D on so e L?/, static $ariables are shared bet#een all instances of the progra */ /* this defeats re!entrancy */ static int j M 0H for 5 i M 0H i I nH iV V6 A jVVH printf5F%n subroutine i M Nd j M Nd KnF,i,j6H B returnH /* this is #here progra starts */ ain 5 6 A int )H /* declaring that ain #ill call
113

e)ecution does not start here */

/* this code is only e)ecuted #hen the subrl routine is called

ain routine, it is a local

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

rog,,.c subroutines returning values :void key!ord;


?D routine #ill return no $alue, e)pects to recei$e an integer, #ill call integer n D? void cube' : int n 6 Aint cubeH ?D local $ariable for subroutine D? cube M n D n D nH printf5FCube of Ni is Ni KnF,n,cube6H returnH B ?D routine returns an int, e)pects an integer, #ill call integer n D? int cube+ : int n 6 A int cubeH ?D local $ariable for subroutine D? cube M n D n D nH return5cube6H B ain5 6 A /* function prototype headers, not calls to subroutines D? $oid cubel 5int 6H int cube2 5 int 6H ?D local $ariables for ain D? int inputQ$alueH int returnedQ$alueH printf5F-nter nu ber to calculate cube ofKnF6H scanf5FNiF ,[inputQ $alue6H printf5FCalling cubelKnF6H ?D there is no return $alue to catch D? cubel5input $alue6H printf5CCKnCalling cube2KnF6H ?D there is a return $alue to catch D? returnedQ$alue M cube25inputQ$alue6H printf5Fcube of Ni is Ni KnF,inpuC$alue,returnedQ$alue6H B
116

# 6e! Vords #bout (ultiB(odule Programs


%n the Cnor alC progra source file. %t or akes ing #orld, #e typically #ill not ha$e just 1 giant ain function, and one ore sense to ha$e a file containing the

ore other files that contain functions typically grouped by functionality.

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

rog,9.c multi le files being com iled together


?D ain routine located in one file D ? /* subrl is located in another file func24a.c D? ?D subr2 is located in another file func24b.c D? ?D co pile together $ia acc !o prog24 prog24.c func24a.c func24b.c D? ?D try acc prog24.c then try acc prog24.c func24a.c then try ace func24a.c func24b.c then try ace !c prog24.c D? ?D this is #here progra ain 5 6 A ?D declaring that $oid subr15int6H $oid subr25int6H printf5F%n subr1546H printf5FWain routine location 1KnKnF6H subr2526H printf5FWain routine location 2KnKnF6H B ain routine KnF6H ain #ill call subrlL D? e)ecution starts D?

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

valref.c Call $y 3alue vs. Call by Reference


?D de onstrate call by $alue and call by reference D? $oid $al15int )6 D? A )VVH returnH routine D? B $oid refl 5intD )6 A D) M D) V 1H returnH B ain5 6 A int i M 4H printf5F%n $al1 5i6H printf5F%n printf5F%n ref15[i6H printf5F%n B %n ain i M 4 %n $al1 ) M 7 %n ain i M 4 %n ain i M 4 %n refl1) M 7
121

?D ansi function header

?D add one to ) D? ?D return to calling

printf5F%n $all ) M Ni KnF,)6H ?D print out its $alue D?

?D ansi function header D? ?D add one to $alue stored at address stored in ) D?

printf5F%n refl ) M Ni KnF,D)6H?D print it out D?

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

call by value ain routine stack subroutine

$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 /*

to input a nu ber D? ain routine.

Print the nu ber in the

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

Solution for /7ercise ''


ain5 6 A int iH intjH int t#ice5int6H $oid threeQti es5int D6H printf5F-nter nu ber KnF6H scanf5FNiF,[i6H printf5FOou entered Ni KnF,i6H j M t#ice5i6H printf5FT#ice Ni is NiKnF,i,j6H printf5+three ti es Ni is F,i6H threeQti es5[i6H printf5FNi KnF,i6H B int t#ice5 int n 6 A return 5n D 2 6H B $oid threeQti es5 int D nptr 6 A Dnptr DM 2H returnH B

125

rog,<.c
main : ; A /* scores_0` is the (eroeth entry in scores D? /* [scores_0` is the address of the (eroeth entry D? ?D scores all by itself, is 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?

assing arrays to subroutines


/;CC-// 2 1

/* #rite functions to find out if a $alue is in an P>%R;U-

?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

rog,D.c assing ointers and arrays to subroutines


/* function to subtract e$ery ele ent by the ele ent after itD ? ?D lea$e the last ele ent alone D? ?D this function de onstrates that array ele ents can be D? ?D anipulated by the function D? ?D arrayptr is a pointer to an integer D? ?D %T ">PP-</ TL *- T"- P%U/T -R-W-<T LP > T-< -R-W-<T >UU>O D? $oid subtracts5 int \ array Qptr 6 A int iH for 5i M 0H i I :H iVV 6 array Qptr_i` M array Qptr_i` ! array Qptr_iV 1`H B ain 5 6 A int scores_l0`, iH $oid subtracts5 int D 6H /* useful to use data file prog27.dat D? printf5FPlease enter ten scores KnF6H for 5 i M 0H i I 10H iVV 6 A printf5F/core Ni' F,i6H scanf5FNiF,[scores_i`6H printf5CCKt Ni KnF,scores_i`6H B printf5F>rray before function call KnF6H for 5 i M 0H i I 10H iVV 6 printf5Fscores_Ni`KtNiKnF,i,scores_i`6H subtracts5 scores 6H printf5F>rray after function call KnF6H for 5 i M 0H i I 10H iVV 6 printf5Fscores _Ni`KtNiKnF,i,scores _i`6H B

129

rog,8.c sorting an array of integers


/* function to sort an array of integers into ascending order D? /* proble is, #e canCt hard code the si(e of the array into the function D?

?D first solution is to pass the si(e of the array into function D? /* function returns nothing D? /* its 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 routine to call sort and display results D?

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

rog,E.c rogram to introduce t!o dimensional arrays


ain5 6 A ?D rc cola D? ?D ro#s, colu ns D? /* 2 ro#s, three colu ns D? ?D C T"%<K/ LP />WPR-QW>TU%= >/ >< >UU>O .%T" T.L -<TU%-/ ->C" -<TUO ">PP-</ TL *- >< >UU>O LP T"U--<TU%-/ D? ?D sa pleQ atri)_0` is an array, sa pleQ atri)_0`_0` is an integer D? int sa pleQ atri)_2` _2` M A A 1,2 ,2 B, A 2,4 ,: B BH int ro#,colu nH int ro#su , colsu H ?D print original atri) D? printf5FLriginal atri) KnF6H for 5 ro# M 0H ro# I 2H ro#VV6 A for 5colu n M 0H colu n I 2H colu nVV 6 printf5FN2iF ,sa pleQ atri)_ro#`_colu n`6H printf5CCKnCC6 H B printf5CCKnKnW>TU%= .%T" UL./;W/ ><& CLR;W< /;W/KnF6H ?D add up ro#s and colu ns, produce report D? printf5CCKtKt ro#su KnF6H for 5 ro# M 0H ro# I 2H ro# VV 6 A ro#su M0H printf5F KtF6H for 5 colu n M 0H colu n I 2H colu nVV 6 A printf5FN2iF ,sa pleQ atri) _ro# ` _colu n`6H ro#su VM sa pleQ atri)_ro#`_colu n`H B printf5F N3iKnF,ro#su 6H B
135

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

Sending T!o Dimensional #rray To Subroutine

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

any ro#s and

B B

138

Solution for /7ercise ',


?D function returns nothing D ? ?D its na e is sort D ? ?D it e)pects an integer array, doesnCt kno# ho# big it #ill be yet D? ?D n #ill be an integer specifying the si(e of the array D? $oid sort 5 int a_ `, int n6 A int i,j,te pH for 5i M 0H i I nH iV V6 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 ?D end sort function D

139

@define UL./ @define CLR/ ain5 6 A

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

(ore #rray Synta7 L Subroutines testarrays.c


The basic proble any ro#s and ho# any colu ns, 5 or ho# any entries per di ension6 the array has. *asic pointer synta) only pro$ides the address of the first ele ent. This is fine if #e #ish to only tra$erse the e ory allocated for the array, ho#e$er, if #e #ish to tra$erse it using the ro# and colu n layout #e ha$e specified #hen the array #as created, #e need to pro$ide so e ro# colu n infor ation to the subroutine. >s a rule, if there are < di ensions in the array you need to pro$ide at least <!1 pieces of di ension infor ation, the co puter can figure out the last di ension. "o#e$er, to be rigorous, #hy not pro$ide as di ension infor ation. $oid s15int D ),int n6 A int iH for 5 i M 0H i I nH iVV 6 printf5FN4iF, )_i`6H printf5CCKnCC6H B $o id s2 5in t )6 A
142

#hen co

unicating array infor ation to a subroutine is ho#

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

Qet /ven (ore #rray Synta7 L Subroutines test&arrays'.c


$oid s 1 5int D ),int n6 A ?D #ill access as int iH for 5 i M 0H i I nH iVV 6 printf5FN4iF ,)_i`6H printf5CCKnCC6H B $oid s25int D ), int ro#s, int cols6 A ?D #ants to use int i,jH for 5 i M 0H i I ro#sH iVV 6 A for 5 j M 0H j I colsH jVV 6 A @if 0 ?D this #ill be a co piler error D? ?D routine does not ha$e info on ro#,colu n layout of @endif B B B e ory associated #ith ) D? printf5FN3i F,) _i`_j`6H ultiple s0uare brackets, needs di ension info D? any as you say starting #here you say D?

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

rog.F.c static) automatic) global key!ords


?D t#o possible co pile strings acc !& CLWPS>U1 prog30.c additional code acc prog30.c ?D progra $ariables D? ?D progra to de onstrate global $ariables D? /* #e already did this once, do it again D? ?D auto atic $ariables go on the stack D? ?D static $ariables go in data area D? int gH ?D no initial $alue is assigned D? void subrl : void; A int localQ $ariableQisQauto M 1H static int localQ $ariableQisQstatic M 1H localQ$ariableQisQautoVVH localQ $ariableQisQstaticVVH gVVH printf5FNi Ni NiKnF, localQ $ariableQisQauto, localQ $ariableQisQstatic,g6H B main : ; A void subr' 5$oid6H g M 0H printf5F1lobal $ariable M Ni KnF,g6H subr': ;H gVVH subr15 6H @ifdef CLWPS>U1 localQ $ariableQisQautoVVH localQ $ariableQisQstaticVVH printf5FNi Ni NiKnF, localQ $ariableQisQauto, localQ $ariableQisQstatic,g6H printf5FNiKnF,g6H @endif B
151

no additional code D?

to de onstrate static and auto atic

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

>>>iM2 CCCi M 22 &&& i M !:9 *** i M !9022 ---i M 1 PPPiM 1

153

Definition0 recursi$e adj. see recursi$e1

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

is 10 0 b is 20 0 a is 100 0 b is 200 0 a is 10000 b is 20000

157

/7ercise '. ?D #rite a progra #ith functions to do array ath D? ?D use the t#o arrays D? ?D arrayG M A 1,2,2,3B D? ?D array2 M A 4, 7, 8, 9B D? ?D ha$e a fuction to add the t#o arrays D? ?D A 7, 9, 10, 12 B /* 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

rog.+.c sim le stucture : struct key!ord;


ain 5 6 A ?D synta) is' data type then na e of $ariable D? int float iH f1H

?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

rog.,.c structures !ith heterogenous com onents


?D progra ain 5 6 A struct debttrade A int dayH int onthH int yearH float priceH float parH BH struct debt trade struct debtQtrade for debtQtrade anipulation D? ?D letCs assu e that debts cannot be traded on certain days, i.e. Christ as D?

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?

Solution for /7ercise '9


?D progra struct ti e A int int int BH ain5 6 A struct ti e ti eQupdate 5 struct ti e 6H struct ti e current ti eH struct ti e ne)t ti eH B printf5F-nter the ti e 5hh' 'ss6' F6H hourH inutesH secondsH to illustrate structures so e ore 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.

inutes , currentQti e.seconds6H

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

rog.9.c 125U time.h file


?D progra ti e.h D? /* introduces concept of pointer to a structure D? @include Iti e.hJ ain 5 6 A long ti e$alH ?D a $ariable that points to a structure of type t D? D tpH struct t illustrates use of include file and predefined structures in

?D a function, local ti e, that returns a pointer to a structure of type t D? D localti e5 6H struct t

?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?

call returns the nu ber of idnight, ne# yearCs e$e,

clock ticks since

?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

printf5F&aylight /a$ingsY NdKnF,tp!Jt Qisdst6H

e bers

.eekday 3 &ay of Oear &aylight /a$ingsY 1 <ote' the onth nu ber is (ero based 5JanML, &ece l l6. 144

.hy do you think it is this #ayY

168

rog.<.c #rrays of Structures


?D progra @define ain5 6 A struct )y( ne)t second 5 struct )y( no#6H struct )y( arrayQstructs_<;WQU-C/` M A A1l,4:,4:B, A 12, 0, 0 B, A !1, !3, !20 B, A 1, 1, 70 B, A 1,2:,4:B, A 22,4:, 4: B, A1:,12,28B int iH struct )y( t1 ,t2H printf5CCKnT1 Ni Ni NiKnF, arrayof structsl_1`.h, array ofstructs_l`. , array QofQstructs_ 1`.s6H arrayQofQstructs_ l` M ne)tQsecond 5 array ofC structs_l` 6H printf5FT2 Ni Ni NiKnF,arrayQofQstructs_1`.h, arrayQofQstructs_l`. , arrayQofQstructs_1`.s6H for 5i M 0H i I <;WQU-C/H iVV6 A printf5CCKnTl Ni Ni NiKnF, arrayof structs_i`.h, arrayof structs_i`. , array QofQstructs_i`.s6H t1 M arrayQofQstructs_i`H?D ?D $alidate the data D? if 5 t1.h JM 0 [[ t1.h IM 22 [[ t1. t1.s JM 0 [[ tl.s IM 4:6
169

to illustrate arrays of structures D? <;WQU-C/ 8 H int sH BH

struct )y( A int hH int

BH

e ber#ise copy of data D?

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

B breakH default' return5no#6H B return5no#6H B

172

rog.D.c Structures and #rrays


?D sho#s an array of characters inside a structure defined t#o #ays D? struct piece A int BH ?D global data structure po nested curly braces to initiali(e sub!structuresD? struct piece po_ ` M A A 20, FK%<1F B, A 10, FZ;--<F B, A L4, F*%/"LPF B, A 03, FK<%1"T, B, A 08, FULLKF B, A 01, FP>.<F B ain 5 6 A int iH ?D local data structure D? struct piece pi_ 7` M A A 20, A CKC, CiC, CnC, CgC, C , B B, A 10, A CZC, CuC, CeC, CeC, CnC B B, A 04, A C*C, CiC, CsC, ChC, CoC, CpC B B, A03, A CKC, CnC, CiC, CgC, ChC, CtC B B, A 08, A CUC, CoC, CoC, CkC, C , B B, A 01, A CPC, CaC, C#C, CnC, C , B B BH printf5FPieceKt Sal ueKnF6H printtf5+!!!!!Kt!!!!!KnF6' for 5 i M 0H i I 7H iVV 6 A
173

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

<e# *alance 3:84.00 3984.00 3942.00 384:.00 3722.00 122.00

/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

rog.8.c String Processing strlen


180

?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

to illustrate string concatenation D?

?D uses built in functions D ? @include Istring.hJ @define W>=Q/%T- 100 char s1_` M AFTerrillFBH char s2_` M AFL#ensFBH char sa_` M AFLingo F B H char sb_` M AF*oingo FBH char s2_W>=Q/%T-`H char s3_W>=Q/lT-`H char stringa_` M AFabcde FBH ?D jtcat concatenates a and b into c, replace c if contains data D? $oid jtcat5 charD a, charD b, charD c6 A ?D copy all of a into c, stop before copy null 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

rog9F.c String Processing


@include Istring.hJ int jte05char D s1, char D s26 A #hile 5Ds1VV MM Ds2VV 6 A

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

Create one long string fro

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

getchar and gets

?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

to input characters and report #hether they are alphabetic or not D?

?D get the character D? ?D soak in the carriage

habeticKnF,c6H else printf5FNc is not alphabeticKnF,c6H printf5CCKnCC6H B B

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

char D strncat5s 1 ,s2,n6

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

B retu rn Da! DbH B

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?

for 5 i M 0H i I len a)H iVV 6

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

to add together large character strings representing positi$e

?D te porary strings for each digit D? ?D te porary digits for integers D?

@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

o$e it back to (eroeth

a)lenH i JM 0H i!! 6 o$e to ne# D?

?D other#ise put in a (ero D? s2_i` M C0CH

@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

?D function to look for a string that structures for the string.

atches the input string /earch the array of Ueturn !1 if not found. D?

Ueturn inde) in array if found

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 >=

ace BDSC#26 rog99.c => to 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

rog9E.c Pointers to Structures


/* progra for debt trade anipulation D? ?D letCs assu e that they cannot be traded on certain days, i.e. Christ as D? ?D letCs refer to the structures $ia pointers D? ain 5 6 A int iH struct debt trade int dayH int onthH int yearH float priceH float parH struct debtQtrade struct debtQtrade D dtptr M [debts_0`H for 5i M 0H i I 4H iVV 6 A scanf5FNi Ni Ni Nf NfC,[debts_i`.day, [debts_i`. onth, [debts_i`.year, [debts_i`.price,[debts_i`.par6H ?D see if date is any good using array notation D? if 5debts_i`.day M 24 [[ debts_i`. onth MM 12 6 printf5FNf Nf C><<LT TU>&- L< Ni?Ni?NiKnF, debts_i`.price, debts_i` .par, debts_i` .day,debts_i`. onth,debts_i6 .year6H else printf5FNf Nf okay on Ni?Ni?NiF, debts_i`.price, debts_i`.par, debts_i` .day, debts_i`. onth, debts_i`. year6H
212

BH debts_4`H dtptrH ?D establish pointer to first ele ent of array D?

?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

entry D? dtptrVVH B ?D end for D?

213

rog9E.dat
1 1 1::2 1.0 1.0 1 1 1::2 122.4 1.08 2 29 1::2 23.4 1.0:9 24 12 1:90 1.0 1.:9 22 111:8: 100.422.82 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

# better linked list e7am le


struct node A int $alH int $als0H struct node D ne)tH BH @include Istdio.hJ $oid ain5 6 A struct node D headM<;RRH int $H printf5Fenter a positi$e $al or !1 to end KnF6H scanf5FNiF,[$6H #hile5$G M !1 6 A addnode5$, [head6H printlist5head6H printf5Fne)t... F6H scanf5FNiF,[$6H B /* list after loop */ printlist5head6H B $oid addnode5int in, struct node DDh6 A struct node DpH pMDhH /* go through list till find $alue or reach end */ #hile5pGM<;RR [[ p!J$alG M in6 pMp!Jne)tH /* if end #as reached addQite at head of list */ if5p MM <;RR6 A /* allocate ne# node and copy data D? p M 5struct nodeD6 alloc5si(eof5struct node66H p!J$alMinH p!J$als0 M in D inH /* ake this node point at top ite p!Jne)tMDhH in list */

215

/* reset head to be this ne# node D? DhMpH B B


$oid printlist5struct node Dh6 A /* repeat #hile pointer is not null */ #hile5h6 A /* print $alue at this node */ printf5F NiKtNiKnF ,h !J$al,h !J$als06H /* print ne)t node D " hMh!Jne)tH B B

216

rog<F.c 1sing Pointers in a 4inked 4ist


?D also de onstrates dyna ic @include Istdlib.hJ @include Istdio.hJ ain 5 6 A ?D a linked list entry structure definition D? struct lle A int int BH struct lle int $alH printf5Fsi(e of lle is NiKnF,si(eof5firstQele ent66H printf5F-nter $alue to s0uare and store 5!16 to stopKnF6H scanf5FNiF,[$al6H ?D set up pointer to already established ele ent D? ne)tQele ent M [firstQele entH /* enter $alue to s0uare and store D? #hile 5$alGM !1 6 A ne)tQele ent!J$alue M $alH ne)tQele ent!Js0uaredQ $alue M $al D $alH ?D allocate e ory for another structure D? e ory allocated, pointer #ill be of
217

e ory allocation #ith any D?

alloc D?

?D #e need to read in nu bers, donCt kno# ho#

$alueH

?D $alue in list D? ?D pointer to ne)t entry D?

s0uared $alueH ?D $alue in list D?

struct lle Dne)tH

firstQele entH ?D first entry in list D? ?D pointer to any entry in list D?

struct lleD ne)tQele entH

?D returns a pointer to the

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

valref.c Pointers and 6unctions


?D de onstrate that if a function recei$es the address of an ite can update the ite . This is roughly e0ui$alent to call by reference, but it still is call by $alue, the $alue passed is the address of another ite @ifdef ></% $oid refl5intD )6 @else $oid ref15)6 intD )H @endif A D) M D) V 1H D? printf5F%n ref1 ) M Ni KnF,D)6H ?D print it out D? returnH B ain 5 6 A int i M 4H printf5F%n ref15[i6H printf5F%n B 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? ?D add one to $alue stored at address stored in ) ?D K [ U function header D? ?D ansi function header D? D? it

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

fit 5double linked

that #ill do the

to

editing and #ithout producing any ne# #hitespace

221

;/-P;R P;<CT%L</ is#space5c6 strstr5 s 1 ,s26

=> e7'E.c >=


?D solution to e)ercise 1: D? @include Istdio.hJ @include Istdlib.hJ @include Istring.hJ @include I alloc.hJ struct lle A char $alue _10` H struct lle D pH BH ?D functions #ill be gi$en pointer to head of list D? ?D functions #ill return pointer to head of list D? struct lle D addQite 5struct lle D6H struct lle D deleteQite 5struct lle D6H ?D function accepts pointer to head of list and returns nothing D? $oid printQlist 5struct lle D6H ain56 A int choiceH struct lle D hptr M <;RRH for 5 H H 6 A printf5FKn&o you #ant to KnF6H printf5Fl add an ite KnF6H printf5F2 delete an ite KnF6H
222

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?

struct lle D addQite 5struct lle D ptr6

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?

t p M 5struct lle D 6 ?D ake sure the A if 5 t p MM <;RR 6

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?

t p M ptrH pl M ptrH ptr M ptr!JpH A

?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?

return 5t p6 H ?D return original pointer D?

not in list Kn,6H

return5t p6H ?D return original head D

B returnH B

228

rogD<.c getchar L utchar


?D progra to read and echo characters until D ? D? ?D end of file 5-LP6 is encountered D? ?D t#o #ays to run this progra ?D 1' run it fro the ter inal prog87 D?

/* 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?

?D you donCt need to put any special -LP character

229

rogDD.c
?D progra os D?

fo en) f rintf) fclose) getc) utc

to copy one file to another D ?

?D and that cleans up after itself, not counting on the

@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?

char na e_20`H char crH

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

price.file used for in ut


)459145 10199303080094868000009780300094C*9AAC+llI,-' A)S$.ALIAN *+LLA. ,+N* oooooooo A459145 101 99303080094868000009780300094C*9AAC+llI, -' A)S$.ALIAN *+LLA. ,+N* oooooooo )4591453019930308010S5550000109101000962-3ACC026I,-' /)L$IC)..ENC0 SE.IES 026 oooooooo )L1LA2l)1 1 9930308345454545454545A267ACC8011S$ S)88LE/EN$AL INC.EASE -+. oooooooo )*L767L61 1 99303080000000000000001*L1ACC8022N* S)88LE/EN$AL *E8+SI$ -+. oooooooo )62623222199303080109450000011509800094,73AL/L37/)N IN9 $. -* 37 AL oooooooo :)62623233199303080086177000009110700094,81AL/L36/)N IN9 $. -* 36 AL oooooooo )62623263199303080089970000009460900094*64AL/L3N/)N IN9 $. -* 3N AL oooooooo )62623L391993030801 07348000011 268200094*N2AL/L39/)N ;N0 $. -* 39 AL oooooooo )62623L58199303080109610000011564800094*87AL/L30/)N IN9 $. -* 30 AL oooooooo )62623/40199303080111100000011624100094*<IAL/I:A1/)N IN9 $. -* 41 AL oooooooo )62623N79199303080109647000011466300094*59AL/lA</)N IN9 $. -* 4< AL oooooooo )4591452019930308009543500000968890009*,L+A/L++lI,- -S$ C$S A)S$: -1N 7L*. 1=E00000000 )4591452319930308009537300000968260009*,LlA/L++2I,- -S$ C$S A)S$>2-1N 7L*. 1=E00000000 )4591452519930308009738400000988670009*,L2A/L++3A)SSIE /+2I?1A1ELIN2 SE.IES 3 oooooooo )62623.71199303080105325000011131600094652A/$001/)N IN9 $. -* A/$ 001 /8S oooooooo )62623$26199303080105287000011077500094653A/$++2/)N IN9 $. -* A/$ 002 /8S oooooooo )62623$S4199303080099206000010497700094654A/$003/)N IN9 $. -* A/$ 003 /8S oooooooo )62623$65 199303080091926000009719400094655A/$++4/)N IN9 $. -* A/$ 004 /8S oooooooo )62623)l 71993030801 09282000011 539800094656A/$++S/)N IN9 $. -* A/$ 005 /8S oooooooo )62623)19199303080095965000010145200094657A/$++6/ $. -* A/$ 006 /8S oooooooo )62623)49199303080107253000011349500094658A/$++7/I$. -* A/$ 007 /8S oooooooo )62623945199303080107109000011333400094659A/$008/I$. -* A/$ 008 /8S oooooooo )62623953199303080105878000011180000094660A/$++9/I$. -* A/$ 009 /8S oooooooo )62623980199303080108501000011462600094661A/$+I0/I$. -* A/$ 010 /8S oooooooo )62623984199303080088507000009342300094662A/$011/I$. -* A/$ 011 /8S oooooooo )62623985199303080106821000011285700094663A/$+I212$7 A/$ SE.IES oooooooo )62623<851993030801 063980000 11253200094664A/$+ 1313$7 A/$ SE.IES oooooooo )62623@20199303080107965000011424500094665A/$+I4/I$- 14$7 A/$ oooooooo )62623@I9199303080107774000011404000094666A/$+I5/I$- 15$7 A/$ oooooooo

237

riceadd.in ut created by uit .c


45914510199303081993030894C*9AAC+llAACI,-'A)S$.ALlAN*+LLA.,+N*

riceu d.in ut created by uit .c


45914510 19930308 948:68000 978:03000 4591453019930308 1055:55000 1091:01000 L1LA2761 19930308 0:00000 0:00000 *L7:67L61 19930308 0:00000 0:00000 62623222 19930308 1094:50000 1150:98000 6262323319930308 861:77000 911:07000 6262326319930308 899:70000 946:09000 62623L39 19930308 1073:48000 1126:82000 62623L58 19930308 1096:10000 1156:48000 62623/40 19930308 1111:00000 1162:41000 62623N79 19930308 1096:47000 1146:63000 4591452019930308 954:35000 968:89000 45914523 19930308 953:73000 968:26000 45914525 19930308 973:84000 988:67000 62623.71 19930308 1053:25000 1113:16000 62623$26 19930308 1052:87000 1107:75000 62623$54 19930308 992:06000 1049:77000 62623$65 19930308 919:26000 971:94000 62623)17 19930308 1092:82000 1153:98000 62623)19 19930308 959:65000 1014:52000 62623)49 19930308 1072:53000 1134:95000 62623945 19930308 1071:09000 1133:34000 62623953 19930308 1058:78000 1118:00000 62623980 19930308 1085:01000 1146:26000 62623984 19930308 885:07000 934:23000 62623985 19930308 1068:21000 1128:57000 62623<85 19930308 1063:98000 1125:32000 62623@20 19930308 1079:65000 1142:45000 62623@19 19930308 1077:74000 1140:40000

238

argtest.c ?D progra ?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

e7'+ filel file+

240

envtest.c C 5nterface to 125U /nvironment


/* progra D? @include Istdio.hJ ain 5 argc, arg$, en$p 6 int argcH char D arg$_`H char D en$p _`H A int en$ Qcount M 0H #hile 5 en$p_en$ Qcount` GM <;RR6 A printf5FNsKnF ,en$p_en$ Qcount`6H en$ QcountVVH B e)it506H B &%/PR>OM'L &/Z;-UOM/O*>/PL<TP>T"M?usr?open#in?lib?fonts PU>W-*;PP-UM?de$?fb "-RPP>T"M?usr?open#in?lib?help "LW-M?usr?jtk R& QR%*U>UO QP>T"M?usr?open#in?lib RL1<>W-Mjtk W><P>T"M?usr?open#in?share? an'?usr? an <-.//-US-UM2348 78237: .2000Hspd21 LP-<.%<"LW-M?usr?open#in P>T"M?usr?jtk?bin'?usr?open#in?bin?)$ie#'?usr?open #in?bin' ?usr?local?bin'?usr?local?lang'?usr?local?sybase ?bin' ?usr?uc b'?usr ?bin'?usr?etc'. '?usr?4bin P.&M?usr?local?jtk?jtk?C? yCprogra s /"-RRM?bin?csh /O*>/-M?usr?local?sybase T-UWMsun ;/-UMjtk .%<&L. QP>U-<TM?de$?#inL .W1UQ-<S QPR>C-"LR&-UM?de$?#in2 =>PPRU-/ & %UM?usr?open#in?lib?= 11?app!defaults T-UWC>PMsun!c d'teMK-_J3h'tiMK-_J3l'tcMsun' to access co and line argu ents, progra to access en$iron ent $ariables

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

and line argu ents D? and line argu ents D?

?D arg$ is array of strings each string is one of the co

ain5int argc, char D arg$_` 6

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

rogD8.c Storage Xualifiers register) const)volatile


?D progra ain 5 6 A ?D i #ill be local to this routine D ? ?D it #ill be on the stack if there is roo int iH ?D buffer #ill be local to this routine D? ?D it #ill be on the stack if there is roo D? ?D other#ise it #ill be in data area of routine D? ?D this declaration auto atically consu es 90 bytes of data D? char buffer_90`H ?D bQptr is local to this routine D? ?D it can point to a string of arbitrary length D? ?D it consu es only si(eof5char D 6 D? ?D the area holding the string #ill be anaged by the syste , perhaps being dyna ically allocated and deallocated as space re0uire ents change D? char D bQptrH ?D #ant these $ariables in registers if possible D? ?D perhaps i #ill be used as a loop counter D? ?D putting it in a register #ill produce faster e)ecution D? register int iH ?D te)tQpointer #ill be used in repeated string operations, putting it in a register #ill speed e)ecution D ? register char D te)t pointerH D? ?D other#ise it #ill be in data area of routine D? to introduce storage 0ualifiers D?

245

?D #ant these $ariables in read only /* #ant to ?D during e)ecution of progra D?

e ory D?

ake sure their $alue doesnCt change 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'

Ty ical 5nefficient Code


/P--& 1

?D de onstrates so e FusualF 5and inefficient6 #ays things are done D?

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

rog<..c co ying strings using ointers


?D prog73.c copying strings using pointers D? ?D this routine uses a pointer to specify #here the data co es fro and a pointer to specify #here the data is supposed to end up it also uses pointer arith etic in the copying loop, it has an inefficiency' #hose correction is sho#n the test Dfro D? $oid copyQl 5to, fro 6 char Dto, Dfro H A for 5 H Dfro Dto M CK0CH B ?D copying strings using pointers is $oid copyQ2 5 to, fro char Dto, Dfro H A ?D re e ber C is an e)pression language and each state ent returns a $alue. %n this case, #e can use that $alue to @if 0 #hile 5 Dfro Dto M CK0CH @endif #hile 5 DtoVV M Dfro VV 6 H char s 1 _` M FTerrill L#ensFH char s2_30`H char s2_30`H
250

GM CK0C is unneccessary

GM CK0CH fro VV, toVV 6 Dto M Dfro H

ost efficient

ethod

effecti$ely uses pointer arith etic and i plied tests D? 6

ake our code

ore concise D?

DtoVV M Dfro VVH

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

N08i right justified, 8 digit #idth, (ero leading fill

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

N_abc`s N_^abc`s Ni Nc N iNc

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

input file Pile %nput Pointer

the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1 the alphabet abcdefghijk1

nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y( nop0rstu$#)y(

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

rog<D.c $it % erations


?D and ?D inclusi$e or ?D e)clusi$e or ?D left shift ?D right shift dis &binary:c; char cH A int iH for 5 i M 0H i I 9H iVV 6 A if 5c [ 0)906 printf5F 1 F6H else printf5F0F6H c ? c MM 'H B printf5CCKnCC6H B => left shift c by one bit >= => the high bit shifted out goes in Ybit bucketZ >= [ ] ^ II JJ D? D? D? D? D? D?

?D ones co ple ent a

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

dispQbinary5result6H ?D if both bits are one, result is 1 D?

?D 1000 1111 D? ?D 0000 0011 D? => if either bit is one)

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?

Solution 6or /7ercise ++


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

101 base 2

1111111 base 2

265

rogD'.c 8ifdef
?D progra ?D this progra

com iler key!ord conditional com ilation


to illustrate @ifdef D? #ill be co piled and run se$eral ti es D?

?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

for 5 i M 0H i I 10H iVV 6

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 :

acc !& *efore !& >fter !o prog81 prog81.c

267

endi70 Varning about order of

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

ake no guarantee #hich #ill be retrie$ed first , a or b.

%f #e ha$e 2 functions that return integers fl and f2'

10 10 er should be

this usually does not present any proble s, but the progra

ost likely be so ething other than

#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?

int 0uick_W>=Z;%CK` P%R- D fdH P%R- D fd 1H ain 5 6 A $oid printdata5$oid6H

?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?

?D no# #e ha$e di$ided our list into t#o seg ents 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

A :> rocedure&tableRfuncnoS; : funcno)argl)arg+)arg,)arg.)arg9;H B B ?D end #hile D? retur n506H B ?D end ain D?

278

endi70 Reading com le7 declarations0 static void : > rocedure&tableR S 6 5 6 M

procedureQtable is'

an array

of pointers

at functions

that return $oid

struct mystruct >struct& ointer&arrayRSH

structQpointerQarray is

an array

of pointers

to structures of type

ystruct

struct mystruct :>struct&array& ointer;RSH

structQarray Qpointer is 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

encountered #hen you lea$e off the braces D?

/* the last else belongs to the if 5 ) I 100 6 <LT the if 5) I 106 D? ?D this could ha$e been a$oided by bracing D? if 5 ) I 106 printf5F) less than ten KnF6H else if 5 ) J 10 6 if 5 ) I l006 printf5F) less than one hundredKnF6H else printf5F) is e)actly ten KnF6H ?D this e)pression is indented and braced in a K[U like ?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?

ost readable and W>%<T>%<>*R- 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

&&& 10 20 20 100 200 200

287

Cra-y #ddress Stuff


int iH int array_4`H for5iM0H iI4H iVV 6 printf5FNi KnF, array_i`6H for5iM0H iI4H iVV 6 printf5FNi KnF, i_array`6H *oth these loops do the sa e thing' print out the contents of the array. This is because array_i` is co piled as D5arrayVi6 #hich is the sa e as D5iVarray6. .ith a 2 di ensional array, the first inde) 5 ajor inde)6 is itself an adderss, so in our e)a ple' int i,jH int y_2`_2` M A A10,20,20B, A1 00,200,200B BH for 5 i M 0H i I 2H iVV 6 for 5 j M 0H j I 2H jVV6 printf5FNi F,y_i` _j`6H y_i`_j` eans D5 D5yVi6 Vj6 #here i is the offset into the array of ro# addresses and j is the offset into that ro# for 5 i M 0H i I 2H iVV 6 for 5 j M 0H j I 2H jVV 6 printf5FNi F,i_y`_j`6H i_y`_j` eans D5 D5iVy6Vj6 #hich also #orks since it generates the sa e address as in the pre$ious e)a ple

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

e ployed to deal #ith this situation is the trigraph.

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

Anda mungkin juga menyukai