Sei sulla pagina 1di 109

Roinn na Matamaitice Feidhm Coliste na hOllscoile Corcaigh

A COURSE IN C PROGRAMMING

Diarmuid O' Rordin, BE, MEngSc, MIEI

Department of Applied Mathematics University College Cork


6th Revision !"#$%#%$!&

CHAPTER !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! " INTRODUCTION!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" !'! OR()(* OF C'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''& !'% +,- .,-//O 0OR/D1 2RO)RAM''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''3 !'" +,- C 2RO)RAMM(*) -*4(RO*M-*+''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''6 CHAPTER #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! $ %ARIAB&ES, DATA T'PES, I(O AND OPERATORS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!$ %'! 5A6(C DA+A +72-6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''8 %'% 4AR(A5/-6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''9 %'" CO*6O/- (*2U+ # OU+2U+''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''!$ %'& O2-RA+OR6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''!" %'3 +72- O4-RF/O0 : U*D-RF/O0''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''%! %'6 -;-RC(6-6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''%! CHAPTER )!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #) STATEMENTS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#) "'! -;2R-66(O*6 A*D 6+A+-M-*+6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''%" "'% (+-RA+(O* 6+A+-M-*+6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''%" "'" D-C(6(O* 6+A+-M-*+6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''%< "'& -FF(C(-*C7 CO*6(D-RA+(O*6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''"" "'3 -;-RC(6-6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''"6 CHAPTER "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! )* +UNCTIONS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!)* &'! FU*C+(O* 2RO+O+72- = D-C/ARA+(O*>'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''"9 &'% FU*C+(O* D-F(*(+(O* : /OCA/ 4AR(A5/-6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''"< &'" 6CO2- RU/-6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''&$ &'& R-+UR*(*) A 4A/U- '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''&$ &'3 FU*C+(O* AR)UM-*+6 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''&! &'6 R-CUR6(O*'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''&" &'8 ?D-F(*- D(R-C+(4-'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''&& &'9 -FF(C(-*C7 CO*6(D-RA+(O*6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''&6 &'< -;-RC(6-6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''&8 CHAPTER ,!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! "ARRA'S . STRINGS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"3'! 6(*)/- D(M-*6(O* ARRA76'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''&< 3'% 6+R(*)6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''3$ 3'" MU/+(D(M-*6(O*A/ ARRA76''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''3! 3'& ARRA76 OF 6+R(*)6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''3" 3'3 ARRA76 A6 AR)UM-*+6 +O FU*C+(O*6 = !D >''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''3& 3'6 2A66(*) MU/+(D(M-*6(O*A/ ARRA76''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''36 3'8 -;-RC(6-6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''39 CHAPTER /!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /

POINTERS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!/ 6'! 2O(*+-R 4AR(A5/-6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''6! 6'% 2O(*+-R O2-RA+OR6 @ A*D :''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''6! 6'" CA// 57 R-F-R-*C-''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''6% 6'& 2O(*+-R6 A*D ARRA76''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''6& 6'3 2O(*+-R AR(+,M-+(C'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''6& 6'6 ARRA76 OF 2O(*+-R6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''68 6'8 COMMA*D /(*- AR)UM-*+6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''69 6'9 D7*AM(C M-MOR7 A//OCA+(O*'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''6< 6'< MU/+(2/- (*D(R-C+(O* 2O(*+-R6 +O 2O(*+-R6'''''''''''''''''''''''''''''''''''''''''''''''''''''8$ 6'!$ 2O(*+-R6 +O FU*C+(O*6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''8% 6'!! -FF(C(-*C7 CO*6(D-RA+(O*6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''8& 6'!% -;-RC(6-6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''86 CHAPTER $!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! *) STRUCTURES . UNIONS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*) 8'! 6+RUC+UR-6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''9" 8'% 5(+ F(-/D6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''98 8'" U*(O*6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''98 8'& -*UM-RA+(O*6 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''99 8'3 +,- +72-D-F A-70ORD'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''9< 8'6 /(*A-D /(6+6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''<$ 8'8 -FF(C(-*C7 CO*6(D-RA+(O*6'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''<3 8'9 -;-RC(6-6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''<6 CHAPTER *!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -$ STANDARD +I&E I(O!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!-$ 9'! 6+R-AM (#O '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''<8 9'% /O0 /-4-/ (#O'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''!$" 9'" -;-RC(6-6''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''!$3 APPENDI0 A 1 ASCII CHARACTER SET !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 2*

"

Chapter !

In3roduc3ion
! Origin o4 C
+he C 2rogramming /angBage Cas initially developed Dy Denis Ritchie Bsing a UniE system in !<8%' +his Cas varied and modified Bntil a standard Cas defined Dy 5rian Aernighan and Dennis Ritchie in !<89 in F+he C 2rogramming /angBageF' 5y the early 9$Gs many versions of C Cere availaDle Chich Cere inconsistent Cith each other in many aspects' +his led to a standard Deing defined Dy A*6( in !<9"' (t is this standard this set of notes primarily addresses'

Why use C ?
Indu53r6 Pr757nc7 1 Over the last decade C has Decome one of the most Cidely Bsed development langBages in the softCare indBstry' (ts importance is not entirely derived from its Bse as a primary development langBage DBt also DecaBse of its Bse as an interface langBage to some of the neCer .visBal1 langBages and of coBrse DecaBse of its relationship Cith CHH' Midd87 &7978 1 5eing a Middle level langBage it comDines elements of high level langBages Cith the fBnctionality of assemDly langBage' C sBpports data types and operations on data types in mBch the same Cay as higher level langBages as Cell as alloCing direct manipBlation of DitsI DytesI Cords and addresses as is possiDle Cith loC level langBages' Por3a:i8i36 1 0ith the availaDility of compilers for almost all operating systems and hardCare platforms it is easy to Crite code on one system Chich can De easily ported to another as long as a feC simple gBidelines are folloCed' +87;i:i8i36 1 6Bpporting its position as the mainstream development langBage C can De interfaced readily to other programming langBages' Ma887a:87 1 CI Bnlike some other langBagesI offers little restriction to the programmer Cith regard to data types one type may De coerced to another type as the sitBation dictates' ,oCever this feature can lead to sloppy coding Bnless the programmer is fBlly aCare of Chat rBles are Deing Dent and Chy' S<77d 1 +he availaDility of varioBs optimising compilers alloC eEtremely efficient code to De generated aBtomatically'

&

!# T=7 >H788o ?or8d@ Program


A C program consists of one or more fBnctions or code modBles' +hese are essentially groBps of instrBctions that are to De eEecBted as a Bnit in a given order and that can De referenced Dy a BniJBe name' -ach C program mBst contain a main() fBnction' +his is the first fBnction called Chen the program starts to rBn' *ote that Chile FmainF is not a C keyCord and hence not reserved it shoBld De Bsed only in this conteEt' A C program is traditionally arranged in the folloCing order DBt not strictly as a rBle' Function prototypes and global data declarations The main() function Function definitions Consider first a simple C program Chich simply prints a line of teEt to the compBter screen' +his is traditionally the first C program yoB Cill see and is commonly called the .,ello 0orld1 program for oDvioBs reasons' #include <stdio.h> void main() { /* This is how comments are implemented in C to comment out a block o te!t */ // or like this or a sin"le line comment print ( #$ello %orld&n# ) ' ( As yoB can see this program consists of KBst one fBnction the mandatory main fBnction' +he parenthesesI = >I after the Cord main indicate a fBnction Chile the cBrly DracesI L MI are Bsed to denote a Dlock of code in this case the seJBence of instrBctions that make Bp the fBnction' Comments are contained Cithin a #@ ''' @# pair in the case of a Dlock comment or a doBDle forCard slashI ##I may De Bsed to comment oBt the remains of a single line of test' +he line print (#$ello %orld&n # ) '

is the only C statement in the program and mBst De terminated Dy a semi colon' +he statement calls a fBnction called printf Chich caBses its argBmentI the string of teEt Cithin the JBotation marksI to De printed to the screen' +he characters Nn are not printed as these characters are interpreted as special characters Dy the printf fBnction in this case printing oBt a neCline on the screen' +hese characters are called escape sequences in C and caBse special actions to occBr and are preceded alCays Dy the Dackslash characterI N ' All C compiler inclBde a liDrary of standard C fBnctions sBch as printf Chich alloC the programmer to carry oBt roBtine tasks sBch as (#OI maths operationsI etc' DBt Chich are not part of the C langBageI the compiled C code merely Deing provided Cith the compiler in a standard form' ,eader files mBst De inclBded Chich contain prototypes for the standard liDrary fBnctions and declarations for the varioBs variaDles or constants needed' +hese are normally denoted Dy a 'h eEtension and are processed aBtomatically Dy a program called the Preprocessor prior to the actBal compilation of the C program' 3

+he line

#include <stdio.h>

instrBcts the preprocessor to inclBde the file stdio'h into the program Defore compilation so that the definitions for the standard inpBt#oBtpBt fBnctions inclBding printf Cill De present for the compiler' +he angle Draces denote that the compiler shoBld look in the defaBlt .(*C/UD-1 directory for this file' A pair of doBDle JBotes indicate that the compiler shoBld search in the specified path e'g' #include )d*&m+ ile.h, NB 1 C is case sensitive i'e' print () and -rint () CoBld De regarded as tCo different fBnctions'

!) T=7 C Programming En9ironm7n3


2rogram development is noCadays carried oBt in specifically designed softCare systems or CorkDenches Cith editingI compilationI linkingI deDBgging and eEecBtion facilities DBilt in' (n this coBrse Ce Cill De making Bse of a Microsoft system DBt the featBres foBnd in this are to De foBnd in one form or another in almost all modern systems' +he first phase of development involves the creation and editing of a file containing the appropriate C instrBctions Chich Cill De stored Bsing a file eEtension of !c normally to invoke the C compilerI e'g' fname'c' +he neEt step is to take the C program and to compile it into oDKect code or machine langBage code' +he C compiler inclBdes the aforementioned preprocessor Chich is called aBtomatically Defore the code translation takes place' +his preprocessor acts on special commands or directives from the programmer to manipBlate the teEt of the C code Defore compilation commences' +hese directives might involve inclBding other soBrce files in the file to De compiledI replacing special symDols Cith specific replacement teEtI etc' Once this is done the C code is translated into oDKect code and stored in a file Cith the eEtension .objI e'g' name.ob. ' +he final phase in DBilding the eEecBtaDle program is called linking' After the compilation stage the C code has Deen translated into machine recognisaDle code DBt is in a someChat Bnconnected state' +he program invariaDly contains references to standard liDrary fBnctions or fBnctions contained in other liDraries or modBles Chich mBst De connected to the C program at link time' +his simply involves linking the machine code for these fBnctions Cith the programOs oDKect code to complete the DBild process and prodBce an eEecBtaDle file Cith an eEtension .exe e'g' name.e!e. +he eEecBtaDle program can De loaded and rBn from Cithin the programming environment itself or may De rBn from the host environment directly' (f it eEecBtes as eEpected that is the end of the task' ,oCever if this does not happen it may reJBire the Bse of the deDBgger to isolate any logical proDlems' +he deDBgger alloCs Bs to step throBgh the code instrBction Dy instrBction or Bp to predefined Dreak points and to look at the valBes of variaDles in the code in order to estaDlish Chere errors are introdBced'

Chapter %

%aria:875, Da3a T6<75, I(O and O<7ra3or5


(n order to De BsefBl a program mBst De aDle to represent real life JBantities or data e'g' a personOs nameI ageI heightI Dank DalanceI etc' +his data Cill De stored in memory locations called variaDles that Ce Cill name oBrselves' ,oCever so that the data may De represented as aptly as possiDle the variaDles Cill have to De of different types to sBit their data' For eEample Chile an integer can represent the age of a person reasonaDly Cell it ConOt De aDle to represent the poBnds and pence in a Dank Dalance or the name of an individBal JBite so Cell'

#! Ba5ic Da3a T6<75


+here are five Dasic data types charI intI floatI doBDleI and void' All other data types in C are Dased on these' *ote that the siPe of an int depends on the standard siPe of an integer on a particBlar operating system' c=ar in3 48oa3 dou:87 9oid ! Dyte = 9 Dits > Cith range !%9 to !%8 !6 Dit O6 Q % Dytes Cith range "%869 to "%868 "% Dit O6 Q & Dytes Cith range %I!&8I&9"I6&9 to %I!&8I&9"I6&8 & Dytes Cith range !$ "9 to !$"9 Cith 8 digits of precision 9 Dytes Cith range !$ "$9 to !$"$9 Cith !3 digits of precision generic pointerI Bsed to indicate no fBnction parameters etc'

Modifying Basic Types


-Ecept for type void the meaning of the aDove Dasic types may De altered Chen comDined Cith the folloCing keyCords' si"ned unsi"ned lon" short +he signed and unsigned modifiers may De applied to types char and int and Cill simply change the range of possiDle valBes' For eEample an unsigned char has a range of $ to %33I all positiveI as opposed to a signed char Chich has a range of !%9 to !%8' An unsigned integer on a !6 Dit system has a range of $ to 633"3 as opposed to a signed int Chich has a range of "%869 to "%868' *ote hoCever that the defaBlt for type int or char is signed so that the type signed char is alCays eJBivalent to type char and the type signed int is alCays eJBivalent to int' +he long modifier may De applied to type int and doBDle only' A long int Cill reJBire & Dytes of storage no matter Chat operating system is in Bse and has a range of %I!&8I&9"I6&9 to %I!&8I&9"I6&8' A long double Cill reJBire !$ Dytes of storage and Cill De aDle to maintain Bp to !< digits of precision' +he short modifier may De applied only to type int and Cill give a % Dyte integer independent of the operating system in Bse' 8

NB 1 *ote that the keyCord int may De omitted CithoBt error so that the type unsigned is the same as type unsigned int I the type long is eJBivalent to the type long int, and the type short is eJBivalent to the type short int .

#!# %aria:875
A variaDle is a named piece of memory Chich is Bsed to hold a valBe Chich may De modified Dy the program' A variaDle thBs has three attriDBtes that are of interest to Bs Q its 36<7, its 9a8u7 and its addr755! +he variaDleOs type informs Bs Chat type and range of valBes it can represent and hoC mBch memory is Bsed to store that valBe' +he variaDleOs address informs Bs Chere in memory the variaDle is located =Chich Cill Decome increasingly important Chen Ce discBss pointers later on>' All C variaDles mBst De declared as folloCs Q type variable-list ; For -Eample Q int i ' char a/ b/ ch ' 4ariaDles are declared in three general areas in a C program' 0hen declared inside fBnctions as folloCs they are termed 8oca8 variaDles and are visiDle =or accessiDle> Cithin the fBnction = or code Dlock > only' void main() { int i/ . ' ... ( A local variaDle is created i'e' allocated memory for storage Bpon entry into the code Dlock in Chich it is declared and is destroyed i'e' its memory is released on eEit' +his means that valBes cannot De stored in these variaDles for Bse in any sBDseJBent calls to the fBnction ' 0hen declared oBtside fBnctions they are termed g8o:a8 variaDles and are visiDle throBghoBt the file or have file scope' +hese variaDles are created at program start Bp and can De Bsed for the lifetime of the program' int i ' void main() { ... ( 0hen declared Cithin the Draces of a fBnction they are termed the formal parameters of the fBnction as Ce Cill see later on' int unc0( int a/ char b ) '

Variable Names
*ames of variaDles and fBnctions in C are called identifiers and are case sensitive' +he first character of an identifier mBst De either a letter or an Bnderscore Chile the remaining characters may De lettersI nBmDersI or Bnderscores' (dentifiers in C can De Bp to "! characters in length' 9

Initialising Variables
0hen variaDles are declared in a program it KBst means that an appropriate amoBnt of memory is allocated to them for their eEclBsive Bse' +his memory hoCever is no3 ini3ia8i57d to Pero or to any other valBe aBtomatically and so Cill contain random valBes Bnless specifically initialised Defore Bse' ynta! 1A type var-name = constant ; For -Eample Q char ch 1 2a2 ' double d 1 03.3434 ' int i/ . 1 35 ' /* note in this case */

i is not initialised

torage Classes
+here are foBr storage class modifiers Bsed in C Chich determine an identifierOs storage dBration and scope' auto static re"ister e!tern An identifierOs storage dBration is the period dBring Chich that identifier eEists in memory' 6ome identifiers eEist for a short time onlyI some are repeatedly created and destroyed and some eEist for the entire dBration of the program' An identifierOs scope specifies Chat sections of code it is accessiDle from' +he aBto storage class is implicitly the defaBlt storage class Bsed and simply specifies a normal local variaDle Chich is visiDle Cithin its oCn code Dlock only and Chich is created and destroyed aBtomatically Bpon entry and eEit respectively from the code Dlock' +he register storage class also specifies a normal local variaDle DBt it also reJBests that the compiler store a variaDle so that it may De accessed as JBickly as possiDleI possiDly from a C2U register' +he static storage class caBses a local variaDle to Decome permanent Cithin its oCn code Dlock i'e' it retains its memory space and hence its valBe DetCeen fBnction calls' 0hen applied to gloDal variaDles the static modifier caBses them to De visiDle only Cithin the physical soBrce file that contains them i'e' to have file scope' 0hereas the eEtern modifier Chich is the implicit defaBlt for gloDal variaDles enaDles them to De accessed in more than one soBrce file' For eEample in the case Chere there are tCo C soBrce code files to De compiled together to give one eEecBtaDle and Chere one specific gloDal variaDle needs to De Bsed Dy Doth the eEtern class alloCs the programmer to inform the compiler of the eEistence of this gloDal variaDle in Doth files'

Constants
Constants are fiEed valBes that cannot De altered Dy the program and can De nBmDersI characters or strings' 6ome -Eamples Q char * 2a2/ 262/ 272 <

int * 05/ 055/ 8055 unsi"ned * 5/ 399 loat * 03.34:9;/ 80.9747;9e05/ 0.4:7;9:<804 double * 0:44.4:94:9:9:9:/ 0.49:9;:9;:9;:9;<8355 lon" * ;994;/ 3333333 strin" * )$ello %orld&n, NB 1 Floating point constants defaBlt to type doBDle' For eEample the folloCing code segment Cill caBse the compiler to issBe a Carning pertaining to floating point conversion in the case of =val DBt not in the case of d=val '' loat =val ' double d=val ' =val 1 034.4:9 ' d=val 1 034.4:9 ' ,oCever the valBe may De coerced to type float Dy the Bse of a modifier as folloCs Q 1 034.4:9 F ' (nteger constants may also De forced to De a certain type as folloCs Q 055> 888 unsi"ned 055? 888 lon" (nteger constants may De represented as either decimal Chich is the defaBltI as heEadecimal Chen preceded Dy F$EFI e'g' $E%AI or as octal Chen preceded Dy FOFI e'g' O%8' Character constants are normally represented DetCeen single JBotesI e'g' GaGI GDGI etc' ,oCever they may also De represented Bsing their A6C(( =or decimal> valBes e'g' <8 is the A6C(( valBe for the letter GaGI and so the folloCing tCo statements are eJBivalent' =6ee AppendiE A for a listing of the first !%9 A6C(( codes'> char ch 1 @7 ' char ch 1 2a2 ' +here are also a nBmDer of special character constants sometimes called Escape Sequences, Chich are preceded Dy the Dackslash character GNGI and have special meanings in C' Nn Nt ND NG NF N$ NEdd neCline taD Dackspace single JBote doBDle JBote nBll character represent as heEadecimal constant

#!) Con5o87 In<u3 ( Ou3<u3


+his section introdBces some of the more common inpBt and oBtpBt fBnctions provided in the C standard liDrary'

printf()
+he printf=> fBnction is Bsed for formatted oBtpBt and Bses a control string Chich is made Bp of a series of format specifiers to govern hoC it prints oBt the valBes of the variaDles or constants reJBired' +he more common format specifiers are given DeloC

!$

Rc Rd Ri RB Rld RlB For -Eample Q

character signed integer signed integer Bnsigned integer signed long Bnsigned long

Rf floating point Rlf doBDle floating point Re eEponential notation Rs string RE Bnsigned heEadecimal Ro Bnsigned octal RR prints a R sign

int i ' print ( #Ad#/ i ) '

+he print () fBnction takes a variaDle nBmDer of argBments' (n the aDove eEample tCo argBments are reJBiredI the format string and the variaDle i. +he valBe of i is sBDstitBted for the format specifier Rd Chich simply specifies hoC the valBe is to De displayedI in this case as a signed integer' 6ome fBrther eEamples Q int i 1 05/ . 1 35 ' char ch 1 2a2 ' double 1 34:30.34:9 ' print ( #Ad B Ad#/ i/ . ) ' /* values are substituted rom the variable list in order as reCuired */ print ( #Ac#/ ch ) ' print ( #As#/ #$ello %orld&n# ) ' print ( #The value o is * Al #/ ) '/*Dutput as * 34:30.34:9 */ print ( # in e!ponential orm * Ae#/ ) ' /* Dutput as * 3.4:3034:9eB: Field Width Specifiers Field Cidth specifiers are Bsed in the control string to format the nBmDers or characters oBtpBt appropriately ' ynta! "# BC3o3a8 Did3= <rin37dEC!d7cima8 <8ac75 <rin37dE4orma3 5<7ci4i7r Chere sJBare Draces indicate optional argBments' For -Eample Q int i 1 09 ' loat 1 04.497; ' print ( #A4d#/ i ) ' space print ( #A;.3 #/ width

/* prints #=09 # where = indicates a

character */ ) ' /* prints #=04.4;# which has a total

o ; and displa+s 3 decimal places */ print ( )A*.* ,/ ;/3/ ) ' /* prints #=04.4;# as above. $ere * is used as replacement character or ield widths */

!!

+here are also a nBmDer of flags that can De Bsed in conKBnction Cith field Cidth specifiers to modify the oBtpBt format' +hese are placed directly after the R sign' A =minBs sign> caBses the oBtpBt to De left KBstified Cithin the specified fieldI a H =plBs sign> displays a plBs sign preceding positive valBes and a minBs preceding negative valBesI and a $ =Pero> caBses a field to De padded Bsing Peros rather than space characters'

scanf()
+his fBnction is similar to the printf fBnction eEcept that it is Bsed for formatted inpBt' +he format specifiers have the same meaning as for print () and the space character or the neCline character are normally Bsed as delimiters DetCeen different inpBts' For -Eample Q int i/ d ' char c ' loat ' scan ( #Ad#/ Ei ) ' scan ( #Ad Ac A #/ Ed/ Ec/ E */ scan ( #Ad*Ac#/ Ei/ Ec ) ' */ ) ' /* e.". t+pe #05=!=0.34: RET# /* e.". t+pe #05*! RET#

+he : character is the address of operator in CI it retBrns the address in memory of the variaDle it acts on' =Aside Q +his is DecaBse C fBnctions are nominally call Dy valBe' +hBs in order to change the valBe of a calling parameter Ce mBst tell the fBnction eEactly Chere the variaDle resides in memory and so alloC the fBnction to alter it directly rather than to Bselessly alter a copy of it' > *ote that Chile the space and neCline characters are normally Bsed as delimiters DetCeen inpBt fields the actBal delimiters specified in the format string of the scanf statement mBst De reprodBced at the keyDoard faithfBlly as in the case of the last sample call' (f this is not done the program can prodBce someChat erratic resBltsS +he scanf fBnction has a retBrn valBe Chich represents the nBmDer of fields it Cas aDle to convert sBccessfBlly' For -Eample Q num 1 scan ( )Ac Ad,/ Ech/ Ei )'

+his scanf call reJBires tCo fieldsI a character and an integerI to De read in so the valBe placed in num after the call shoBld De % if this Cas sBccessfBl' ,oCever if the inpBt Cas .a Dc1 then the first character field Cill De read correctly as TaO DBt the integer field Cill not De converted correctly as the fBnction cannot reconcile .Dc1 as an integer' +hBs the fBnction Cill retBrn ! indicating that one field Cas sBccessfBlly converted' +hBs to De safe the retBrn valBe of the scanf fBnction shoBld De checked alCays and some appropriate action taken if the valBe is incorrect'

getchar() and putchar()


+hese fBnctions are Bsed to inpBt and oBtpBt single characters' +he getchar() fBnction reads the A6C(( valBe of a character inpBt at the keyDoard and displays the character Chile putchar() displays a character on the standard oBtpBt device i'e' the screen' For -Eample Q char ch0/ ch3 ' ch0 1 "etchar() ' !%

ch3 1 2a2 ' putchar( ch3 ) ' NB 1 +he inpBt fBnctions descriDed aDoveI scan () and "etchar() are termed DBffered inpBt fBnctions' +his means that Chatever the Bser types at the keyDoard is first stored in a data DBffer and is not actBally read into the program Bntil either the DBffer fills Bp and has to De flBshed or Bntil the Bser flBshes the DBffer Dy hitting RET ChereBpon the reJBired data is read into the program' +he important thing to rememDer Cith DBffered inpBt is that no matter hoC mBch data is taken into the DBffer Chen it is flBshed the program KBst reads as mBch data as it needs from the start of the DBffer alloCing Chatever else that may De in the DBffer to De discarded' For -Eample Q char ch0/ ch3' print ch0 1 ch3 1 print ( #<nter two characters * # ) ' "etchar() ' "etchar() ' ( #&n The characters are Ac and Ac&n#/ ch0/ ch3 ) '

(n the aDove code segment if the inpBt is FaDcdefRETF the first tCo characters are read into the variaDles all the others Deing discardedI DBt control does not retBrn to the program Bntil the RET is hit and the DBffer flBshed' (f the inpBt Cas FaRETF then a CoBld De placed in ch! and RET in ch%'

_flushall()
+he = lushall fBnction Crites the contents of all oBtpBt DBffers to the screen and clears the contents of all inpBt DBffers' +he neEt inpBt operation =if there is one> then reads neC data from the inpBt device into the DBffers' +his fBnction shoBld De Bsed alCays in conKBnction Cith the DBffered inpBt fBnctions to clear oBt BnCanted characters from the DBffer a437r 7ac= inpBt call'

getch() and getche()


+hese fBnctions perform the same operation as getchar=> eEcept that they are BnDBffered inpBt fBnctions i'e' it is not necessary to type RET to caBse the valBes to De read into the program they are read in immediately the key is pressed' getche=> echoes the character hit to the screen Chile getch=> does not' For eEample Q char ch ' ch 1 "etch() '

#!" O<7ra3or5
One of the most important featBres of C is that it has a very rich set of DBilt in operators inclBding arithmeticI relationalI logicalI and DitCise operators'

$ssignment %perator
int ! ' ! 1 35 ' 6ome common notation Q lvalBe rvalBe left hand side of an assignment operation right hand side of an assignment operation !"

+ype Conversions Q the valBe of the right hand side of an assignment is converted to the type of the lvalBe' +his may sometimes yield compiler Carnings if information is lost in the conversion' For -Eample Q int ! ' char ch ' loat ' ch 1 ! ' /* ch is assi"ned lower F bits o !/ the remainin" bits are discarded so we have a possible in ormation loss */ ! 1 ' /* ! is assi"ned non ractional part o onl+ within int ran"e/ in ormation loss possible */ 1 ! ' /* value o ! is converted to loatin" point */ MBltiple assignments are possiDle to any degree in CI the assignment operator has right to left associativity Chich means that the rightmost eEpression is evalBated first' For -Eample Q ! 1 + 1 G 1 055 '

(n this case the eEpression G 1 055 is carried oBt first' +his caBses the valBe !$$ to De placed in P Cith the valBe of the Chole eEpression Deing !$$ also' +his eEpression valBe is then taken and assigned Dy the neEt assignment operator on the left i'e' ! 1 + 1 ( G 1 055 ) U

$rithmetic %perators
H R @ # same rBles as mathematics Cith @ and # Deing evalBated Defore H and ' modBlBs # remainder operator

For -Eample Q int a 1 9/ b 1 3/ ! ' loat c 1 9.5/ d 1 3.5/ ! 1 a / b ' 1 c / d ' ! 1 9 A 3 ' // // //

'

inte"er division/ ! 1 3. loatin" point division/ 1 3.9. remainder operator/ ! 1 0. B and

! 1 7 B 4 * ; / 3 8 0 '// !109/* and / evaluated ahead o 8'

*ote that parentheses may De Bsed to clarify or modify the evalBation of eEpressions of any type in C in the same Cay as in normal arithmetic' ! 1 7 B ( 4 * ; / 3 ) 8 0 ' // clari ies order o evaluation without penalt+ ! 1 ( 7 B 4 ) * ; / ( 3 8 0 ) ' // chan"es order o evaluation/ ! 1 ;5 now.

Increment and &ecrement %perators


+here are tCo special Bnary operators in CI (ncrement HHI and Decrement variaDle they act on to De incremented or decremented Dy ! respectively' !& I Chich caBse the

For -Eample Q

!BB '

/* eCuivalent to

! 1 ! B 0 '

*/

HH and can De Bsed in prefiE or postfiE notation' (n prefiE notation the valBe of the variaDle is either incremented or decremented and is then read Chile in postfiE notation the valBe of the variaDle is read first and is then incremented or decremented' For -Eample Q int i/ . 1 3 ' i 1 BB . ' /* pre i! i 1 .BB ' /* post i! *8 *8 i has value 4/ . has value 4 */ i has value 4/ . has value : */

pecial $ssignment %perators


Many C operators can De comDined Cith the assignment operator as shorthand notation For -Eample Q ! 1 ! B 05 ' can De replaced Dy ! B1 05 ' 6imilarly for 81/ *1/ /1/ A1 I etc'

+hese shorthand operators improve the speed of eEecBtion as they reJBire the eEpressionI the variaDle E in the aDove eEampleI to De evalBated once rather than tCice'

'elational %perators
+he fBll set of relational operators are provided in shorthand notation > For -Eample Q >1 i < <1 11 H1

( ! 11 3 ) print ( )! is eCual to 3&n, ) '

(ogical %perators
:: VV S /ogical A*D /ogical OR /ogical *O+

For -Eample Q i ( ! >1 5 EE ! < 05 ) print ( ) ! is "reater than or eCual to Gero and less than ten.&n, ) ' NB 1 +here is no 5oolean type in C so +RU- and FA/6- are deemed to have the folloCing meanings' FA/6valBe Pero +RUany non Pero valBe DBt ! in the case of in DBilt relational operations For -Eample Q !3

%W! %W" iX%W! U

+RU- so eEpression has valBe ! FA/6- so eEpression has valBe $ relation is +RU- has valBe !I i is assigned valBe !

NB 1 -very C eEpression has a valBe' +ypically Ce regard eEpressions like % H " as the only eEpressions Cith actBal nBmeric valBes' ,oCever the relation % W ! is an eEpression Chich evalBates to +RU- so it has a valBe ! in C' /ikeCise if Ce have an eEpression E X !$ this has a valBe Chich in this case is !$ the valBe actBally assigned' NB 1 5eCare of the folloCing common soBrce of error' (f Ce Cant to test if a variaDle has a particBlar valBe Ce CoBld Crite for eEample i ( ! 11 05 ) I

5Bt if this is inadvertently Critten as i ( ! 1 05 ) I

this Cill give no compilation error to Carn Bs DBt Cill compile and assign a valBe !$ to E Chen the condition is tested' As this valBe is non Pero the if condition is deemed trBe no matter Chat valBe E had originally' ODvioBsly this is possiDly a serioBs logical flaC in a program'

Bit)ise %perators
+hese are special operators that act on c=ar or in3 argum7n35 on86' +hey alloC the programmer to get closer to the machine level Dy operating at Dit level in their argBments' : Y WW 5itCise A*D 5itCise ;OR 6hift Right V Z [[ 5itCise OR Ones Complement 6hift left

Recall that type char is one Dyte in siPe' +his means it is made Bp of 9 distinct Dits or Dinary digits normally designated as illBstrated DeloC Cith 5it $ Deing the /east 6ignificant 5it =/65> and 5it 8 Deing the Most 6ignificant 5it =M65>' +he valBe represented DeloC is !" in decimal' 5it 8 5it 6 5it 3 5it & 5it " 5it % 5it ! 5it $ $ $ $ $ ! ! $ ! An integer on a !6 Dit O6 is tCo Dytes in siPe and so 5it !3 Cill De the M65 Chile on a "% Dit system the integer is foBr Dytes in siPe Cith 5it "! as the M65' Bitwise AND, & RU&E 1 (f any tCo Dits in the same Dit position are set then the resBltant Dit in that position is set otherCise it is Pero' For -Eample Q

E 1
Bitwise OR, |

0500 5505 5500 0000 5500 5505

(07F) (;4) (95)

RU&E 1 (f either Dit in corresponding positions are set the resBltant Dit in that position is set' For -Eample Q

0500 5505 5555 0555


!6

(07F) (;4)

1
Bitwise XOR, ^

0500 0505

(0F;)

RU&E 1 (f the Dits in corresponding positions are different then the resBltant Dit is set' For -Eample Q

K 1

0500 5505 5500 0055 0555 0005

(07F) (;4) (0:3)

Shift Operat ors, < < and > > RU&E 1 +hese move all Dits in the operand left or right Dy a specified nBmDer of places' ynta! Q For -Eample Q i'e' variable << number of places variable >> number of places 3 << 3 1 F

0000 0010 Decomes 0000 1000


NB 1 shift left Dy one place mBltiplies Dy % shift right Dy one place divides Dy %

Ones Complem e n t RU&E 1 Reverses the state of each Dit' For -Eample Q

1101 0011 Decomes 0010 1100 NB 1 0ith all of the aDove DitCise operators Ce mBst Cork Cith decimalI octalI or heEadecimal valBes as Dinary is not sBpported directly in C'
+he DitCise operators are most commonly Bsed in system level programming Chere individBal Dits of an integer Cill represent certain real life entities Chich are either on or offI one or Pero' +he programmer Cill need to De aDle to manipBlate individBal Dits directly in these sitBations' A mask variaDle Chich alloCs Bs to ignore certain Dit positions and concentrate the operation only on those of specific interest to Bs is almost alCays Bsed in these sitBations' +he valBe given to the mask variaDle depends on the operator Deing Bsed and the resBlt reJBired' For -Eample Q +o clear Dit 8 of a char variaDle' char ch 1 F@ ' char mask 1 037 ' ch 1 ch E mask '// or // an+ value // 5000 0000 ch E1 mask '

For -Eample Q +o set Dit ! of an integer variaDle' int i 1 34: ' int mask 1 3 ' // an+ value // a 0 in bit position 3 !8

i J1 mask '

Implicit * +!plicit Type Con,ersions


*ormally in miEed type eEpressions all operands are converted 37m<orari86 Bp to the type of the largest operand in the eEpression' *ormally this aBtomatic or implicit casting of operands folloCs the folloCing gBidelines in ascending order' long doBDle doBDle float Bnsigned long long Bnsigned int signed int For -Eample Q int i ' loat 0/ 0 1 3 '

3 B i '

6ince f% is a floating point variaDle the valBe contained in the integer variaDle is temporarily converted or cast to a floating point variaDle also to standardise the addition operation in this case' ,oCever it is important to realise that no permanent modification is made to the integer variaDle' +!plicit casting coerces the eEpression to De of specific type and is carried oBt Dy means of the ca53 o<7ra3or Chich has the folloCing syntaE' ynta! " ( type expression

For -Eample if Ce have an integer EI and Ce Cish to Bse floating point division in the eEpression E#% Ce might do the folloCing ( loat ) ! / 3

Chich caBses E to De temporarily cast to a floating point valBe and then implicit casting caBses the Chole operation to De floating point division' +he same resBlts coBld De achieved Dy stating the operation as ! / 3.5

Chich essentially does the same thing DBt the former is more oDvioBs and descriptive of Chat is happening' NB 1 (t shoBld De noted that all of these casting operationsI Doth implicit and eEplicitI reJBire processor time' +herefore for optimBm efficiency the nBmDer of conversions shoBld De kept to a minimBm'

!9

i-eof %perator
+he siPeof operator gives the amoBnt of storageI in DytesI associated Cith a variaDle or a type =inclBding aggregate types as Ce Cill see later on>' +he eEpression is either an identifier or a type cast eEpression =a type specifier enclosed in parentheses>' ynta! " sizeof ( expression )

For -Eample Q int ! / siGe ' siGe 1 siGeo ( ! ) ' print ()The inte"er ! reCuires Ad b+tes on this machine,/ siGe)' print ( )Loubles ( double ) ) ' take up Ad b+tes on this machine,/ siGeo

!<

.recedence of %perators
0hen several operations are comDined into one C eEpression the compiler has to rely on a strict set of precedence rBles to decide Chich operation Cill take preference' +he precedence of C operators is given DeloC' Pr7c7d7nc7 ,ighest O<7ra3or = > \ ] W ' S Z HH H=Bnary> =Bnary> =type> @ : siPeof @ # R H [[ WW [ [X W WX XX SX : Y V :: VV ^Q X HX X @X #X RX :X YX VX [[X WWX I A55ocia3i9i36 left to right right to left left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right right to left right to left left to right

/oCest

Operators at the top of the taDle have highest precedence and Chen comDined Cith other operators at the same eEpression level Cill De evalBated first' For eEample take the eEpression 3 B 05 * 9 ' ,ere @ and H are Deing applied at the same level in the eEpression DBt Chich comes first ^ +he ansCer lies in the precedence taDle Chere the @ is at a higher level than the H and so Cill De applied first' 0hen tCo operators Cith the same precedence level are applied at the same eEpression level the associativity of the operators comes into play' For eEample in the eEpression 3 B 4 8 : ' the H and operators are at the same precedence level DBt associate from left to right and so the addition Cill De performed first' ,oCever in the eEpression ! 1 + 1 3 ' as Ce have noted already the assignment operator associates from right to left and so the rightmost assignment is first performed' NB 1 As Ce have seen already parentheses can De Bsed to sBpersede the precedence rBles and force evalBation along the lines Ce reJBire' For eEample to force the addition in # F 2 G , H to De carried oBt first Ce CoBld Crite it as I# F 2J G ,H

%$

#!, T6<7 O97r48oD . Und7r48oD


0hen the valBe to De stored in a variaDle of a particBlar type is larger than the range of valBes that type can hold Ce have Chat is termed type overfloC' /ikeCise Chen the valBe is smaller than the range of valBes the type can hold Ce have type BnderfloC' OverfloC and BnderfloC are only a proDlem Chen dealing Cith integer arithmetic' +his is DecaBse C simply ignores the sitBation and continBes on as if nothing had happened' 0ith signed integer arithmetic adding tCo large positive nBmDersI the resBlt of Chich Cill De larger than the largest positive signed intI Cill lead to a negative valBe Deing retBrned as the sign Dit Cill De overCritten Cith data' +he sitBation is not JBite so Dad Cith Bnsigned integer arithmetic' ,ere all valBes are forced to De Cithin range Chich Cill of coBrse caBse proDlems if yoB donOt eEpect overfloC to occBr' Adding ! to the largest Bnsigned integer Cill give $' +he BnfortBnate aspect of the matter hoCever is that Ce cannot check for overfloC Bntil it has occBrred' +here are a nBmDer of Cays to do this' For eEample Chen performing integer addition yoB might check the resBlt Dy sBDtracting one of the operands from the resBlt to see if yoB get the other' On the other hand yoB might sBDtract one operand from the largest integer to see if the resBlt is greater than the second operand' (f it is yoB knoC yoBr operation Cill sBcceed' ,oCever the maKor flaC Cith these methods is that Ce are redBcing the overall efficiency of the program Cith eEtra operations' (n general the optimBm method for dealing Cith sitBations Chere overfloC or BnderfloC is possiDle is to Bse type long over the other integer types and inspect the resBlts' Operations Bsing long operands are in general sloCer than those Bsing int operands DBt if overfloC is a proDlem it is still a Detter solBtion than those mentioned aDove' Floating point overfloC is not a proDlem as the system itself is informed Chen it occBrs Chich caBses yoBr program to terminate Cith a rBn time error' (f this happens yoB need to promote the variaDles involved in the offending operation to the largest possiDle and try again' NB 1 +he C standard liDrary inclBdes a nBmDer of eEception handling fBnctions to alloC yoB to intercept these sitBations in yoBr program'

#!/ E;7rci575
! 0rite a program to check the siPes of the main C data types on yoBr machine' #! 0rite a program to illBstrate Chether the printf=> standard liDrary fBnction trBncates or roBnds Chen printing oBt a floating point nBmDer' )! 0rite a program to check Chat the folloCing code segment oBtpBts and eEplain the resBlts' char c ' print (#siGeo ( c ) 1 Ad&n#/ siGeo ( c ) ) ' print (#siGeo ( 2a2 ) 1 Ad&n#/ siGeo ( 2a2 ) ) ' print (#siGeo ( c 1 2a2 ) 1 Ad&n#/ siGeo ( c12a2 ) ) ' "! 0rite a program Chich reads a character from the keyDoard and Crites oBt its A6C(( representation'

%!

*oC Crite a program Chich reads in an integer from the keyDoard and print oBt its character representation' Make certain yoB carry oBt appropriate DoBnds # error checking' ,! Use the getchar=> fBnction to read in a single character and oBtpBt it to the screen e'g' puts(#<nter a character#)' c 1 "etchar() ' print (#The character was Ac&n#/c)' Add another c 1 "etchar() statement immediately after the eEisting one and eEplain Chat happens' Repeat the aDove Bsing the "etch() fBnction in place of "etchar() ' /! DescriDe the oBtpBt from each of the folloCing statements' i. print ( )A805d&n,/ 05555 ) ' ii. print ( )AF.4 &n,/ 34.34: ) ' iii. print ( )AB*.*l &n,/ 05/ 4/ 034:.34: ) ' iv. print ( )A!&n,/ 0; ) ' v. print ( )A05.4<,/ 34:.;94:4 ) ' $! 0rite doCn appropriate C statements to do the folloCing' i' 2rint a long intI &$$$$$/I left KBstified in a !$ digit field padding it oBt Cith Peros if possiDle' ii' Read a time of the form ==1mm155 storing the parts of the time in integer variaDles hourI minuteI and second' 6kip the colons in the inpBt field' iii' 2rint oBt the folloCing seJBence of characters .B, K and L r7Muir7 5<7cia8 3r7a3m7n31 ' iv' Read the valBe !%"&3689<'$!%"&3&3689<eH3 into a floating pointI a doBDle and a long doBDle variaDle and print all three oBt again Cith the maEimBm precision possiDle' *! 0hat valBe does E contain after each of the folloCing Chere E is of type float' i. ! 1 7 B 4 * ; / 3 8 0 ' ii. ! 1 3 A 3 B 3 * 3 8 3 / 3 ' iii. ! 1 ( 4 * @ * ( 4 B ( : * 9 / 4 ) ) ) ' iv. ! 1 03.5 B 3 / 9 * 05.5 ' v. ! 1 3 / 9 B 05.5 * 4 8 3.9 ' vi. ! 1 09 > 05 EE 9 < 3 ' -! 0rite a program to read Fahrenheit temperatBres and print them in CelsiBs' +he formBla is C X =3#<>=F "%>' Use variaDles of type doBDle in yoBr program' 2! 0rite a program that reads in the radiBs of a circle and prints the circleOs diameterI circBmference and area' Use the valBe "'!&!3< for .pi1'

%%

Chapter "

S3a37m7n35
)! E;<r755ion5 and S3a37m7n35
As mentioned at the oBtset every C program consists of one or more fBnctions Chich are KBst groBps of instrBctions that are to De eEecBted in a given order' +hese individBal instrBctions are termed statements in C' 0e have already seen some simple eEamples of C statements Chen introdBcing the set of C operators' For eEample ! 1 5 ' is a simple statement that initialises a variaDle E to Pero Bsing the assignment operator' +he statement is made Bp of tCo parts Q the assignment operation and the terminating semi colon' +he assignment operation here is termed an e!pression in C' (n general an eEpression consists of one of COs operators acting on one or more operands' +o convert an eEpression into a C statement reJBires the addition of a terminating semi colon' A fBnction call is also termed an eEpression' For eEample in the hello orld program the statement print ( )$ello %orld&n, ) ' again consists of an eEpression and a terminating semi colon Chere the eEpression here is a call to the printf standard liDrary fBnction' 4arioBs eEpressions can De strBng together to make more complicated statements DBt again are only terminated Dy a single semi colon' For eEample ! 1 3 B ( 4 * 9 ) 8 34 ' is a single statement that involves foBr different eEpressions' 0hen designing most programs Ce Cill reJBire to DBild Bp seJBences of statements' +hese collections of statements are called bloc/s and are encased DetCeen pairs of cBrly Draces' 0e have already encoBntered these statement Dlocks in the case of the main fBnction in the hello orld program Chere the Dody of the fBnction Cas encased in a pair of cBrly Draces' 0e Cill also come across statement Dlocks in the neEt feC sections Chen Ce discBss some of the statements that alloC Bs control over the eEecBtion of the simple statements' +here are tCo types of control statements Q iteration statements that alloC Bs to repeat one or more simple statements a certain nBmDer of times and decision statements that alloC Bs to choose to eEecBte one seJBence of instrBctions over one or more others depending on certain circBmstances' Control statements are often regarded as compoBnd statements in that they are normally comDined Cith simpler statements Chich carry oBt the operations reJBired' ,oCever it shoBld De noted that each control statement is still KBst a single statement from the compilerOs point of vieC'

)!# I37ra3ion S3a37m7n35


%"

for statement
+he for statement is most often Bsed in sitBations Chere the programmer knoCs in advance hoC many times a particBlar set of statements are to De repeated' +he for statement is sometimes termed a coBnted loop' ynta! " for ( !initialisation" ; !con#ition" ; !increment" !statement bo#y" ; ini3ia8i5a3ion Q this is BsBally an assignment to set a loop coBnter variaDle for eEample' condi3ion Q determines Chen loop Cill terminate' incr7m7n3 Q defines hoC the loop control variaDle Cill change each time the loop is eEecBted' 53a37m7n3 :od6 Q can De a single statementI no statement or a Dlock of statements' +he for statement eEecBtes as folloCs Q
initialisation

test condition TRUE

FALSE

continue with next iteration statement body

increment

end of statement

NB 1 +he sJBare Draces aDove are to denote optional sections in the syntaE DBt are not part of the syntaE' +he semi colons mBst De present in the syntaE' For -Eample Q 2rogram to print oBt all nBmDers from ! to !$$' #include <stdio.h> void main() { int ! ' or ( ! 1 0' ! <1 055' !BB ) print ( #Ad&n#/ ! ) ' ( CBrly Draces are Bsed in C to denote code Dlocks Chether in a fBnction as in main=> or as the Dody of a loop' For -Eample Q +o print oBt all nBmDers from ! to !$$ and calcBlate their sBm' #include <stdio.h> void main() %&

{ int !/ sum 1 5 ' or ( ! 1 0' ! <1 055' !BB ) { print ( #Ad&n#/ ! ) ' sum B1 ! ' ( print ( )&n&nMum is Ad&n,/ sum ) ' (

Multiple Initialisations
C has a special operator called the comma o<7ra3or Chich alloCs separate eEpressions to De tied together into one statement' For eEample it may De tidier to initialise tCo variaDles in a for loop as folloCs Q or ( ! 1 5/ sum 1 5' ! <1 055' !BB ) { print ( #Ad&n#/ !) ' sum B1 ! ' ( Any of the foBr sections associated Cith a for loop may De omitted DBt the semi colons mBst De present alCays' For -Eample Q or ( ! 1 5' print ( ... ! 1 5 ' or ( ' ! < print ( ! < 05' ) #Ad&n#/ !BB ) ' 05' !BB ) #Ad&n#/ ! ) '

An infinite loop may De created as folloCs or ( ' ' ) statement bod+ ' or indeed Dy having a faBlty terminating condition' 6ometimes a for statement may not even have a Dody to eEecBte as in the folloCing eEample Chere Ce KBst Cant to create a time delay' or ( t 1 5' t < bi"=num ' tBB ) or Ce coBld reCrite the eEample given aDove as folloCs or ( ! 1 0' ! <1 055' print ( #Ad&n#/ !BB ) ) ' +he initialisationI condition and increment sections of the for statement can contain any valid C eEpressions' or ( ! 1 03 * : ' ! < 4: / 3 * :7 ' ! B1 05 ) print ( )Ad )/ ! ) ' '

%3

(t is possiDle to DBild a nested strBctBre of for loopsI for eEample the folloCing creates a large time delay Bsing KBst integer variaDles' unsi"ned int !/ + ' or ( ! 1 5' ! < ;9949' !BB ) or ( + 1 5' + < ;9949' +BB ) ' For -Eample Q 2rogram to prodBce the folloCing taDle of valBes ! % " & 3 % " & 3 6 " & 3 6 8 & 3 6 8 9 3 6 8 9 <

#include <stdio.h> void main() { int ./ k ' or ( . 1 0' . <1 9' .BB ) { or ( k 1 . ' k < . B 9' kBB ) { print ( #Ad #/ k ) ' ( print ( )&n, ) ' ( (

)hile statement
+he )hile statement is typically Bsed in sitBations Chere it is not knoCn in advance hoC many iterations are reJBired' ynta! " $%ile ( con#ition statement bo#y ;

test condition TRUE

FALSE

continue with next iteration statement body

end of statement

%6

For -Eample Q 2rogram to sBm all integers from !$$ doCn to !' #include <stdio.h> void main() { int sum 1 5/ i 1 055 ' while ( i ) sum B1 i88 '// note the use o print ( )Mum is Ad &n,/ sum ) ' ( Chere it shoBld De recalled that any non Pero valBe is deemed +RU- in the condition section of the statement' A for loop is of coBrse the more natBral choice Chere the nBmDer of loop iterations is knoCn Deforehand Chereas a Chile loop caters for BneEpected sitBations more easily' For eEample if Ce Cant to continBe reading inpBt from the keyDoard Bntil the letter G_G is hit Ce might do the folloCing' char ch 1 2&52 '/* initialise variable to ensure it is not 2N2 */ while ( ch H1 2N2 ) ch 1 "etche() ' or more sBccinctly while ( ( ch 1 "etche() ) H1 2N2 ) ' (t is of coBrse also possiDle to have nested Chile loops' For -Eample Q 2rogram to gBess a letter' #include <stdio.h> void main() { char ch/ letter 1 2c2 char inish 1 O&5P ' post i! decrement operatorH

'

// secret letter is OcP

while ( inish H1 O+P JJ inish H1 OQP ) { puts( #Ruess m+ letter 88 onl+ 0 o 3; H# )' while( (ch1"etchar() ) H1 letter )// note use o parentheses { print ( #Ac is wron" 88 tr+ a"ain&n#/ ch ) ' = lushall() ' // pur"es S/D bu er ( print ( #DT +ou "ot it &n ?etPs start a"ain.&n# ) ' letter B1 4 '// Chan"e letter addin" 4 onto UMCSS value o letter // e.". OcP B 4 1 O P print ( )&n&nLo +ou want to continue (Q/V) W ))' inish 1 "etchar() ' = lushall() ' ( (

do )hile
%8

+he terminating condition in the for and Chile loops is alCays tested Defore the Dody of the loop is eEecBted so of coBrse the Dody of the loop may not De eEecBted at all' (n the do )hile statement on the other hand the statement Dody is alCays eEecBted at least once as the condition is tested at the end of the Dody of the loop' ynta! " #o & statement bo#y ; ' $%ile ( con#ition

statement body continue with next iteration

TRUE

test condition FALSE

end of statement

For -Eample Q +o read in a nBmDer from the keyDoard Bntil a valBe in the range ! to !$ is entered' int i ' do { scan ( #Ad&n#/ Ei ) ' = lushall() ' ( while ( i < 0 EE i > 05 ) ' (n this case Ce knoC at least one nBmDer is reJBired to De read so the do Chile might De the natBral choice over a normal Chile loop'

brea/ statement
0hen a brea/ statement is encoBntered inside a ChileI forI do#Chile or sCitch statement the statement is immediately terminated and eEecBtion resBmes at the neEt statement folloCing the statement' For -Eample Q ''' or ( ! 1 0 ' ! <1 05 { i ( ! > : ) break ' ' !BB )

print ( )Ad ) / ! ) ' ( print ( #Ve!t e!ecuted&n# )'//Dutput <!ecuted, '''

* )0

Ve!t

continue statement
%9

+he continue statement terminates the cBrrent iteration of a ChileI for or do#Chile statement and resBmes eEecBtion Dack at the Deginning of the loop Dody Cith the neEt iteration' For -Eample Q ''' or ( ! 1 0' ! <1 9' !BB ) { i ( ! 11 4 ) continue ' print ( )Ad )/ ! ) ' ( print ( )Xinished ?oop&n, ) ' ?oop, ''' // Dutput * )0 3 : 9 Xinished

)!) D7ci5ion S3a37m7n35 if statement


+he if statement is the most general method for alloCing conditional eEecBtion in C' ynta! " if else statement bo#y H or 0ust " if ( con#ition statement bo#y ; ( con#ition statement bo#y ;

(n the first more general form of the statement one of tCo code Dlocks are to De eEecBted' (f the condition evalBates to +RU- the first statement Dody is eEecBted otherCise for all other sitBations the second statement Dody is eEecBted' (n the second form of the statement the statement Dody is eEecBted if the condition evalBates to +RU-' *o action is taken otherCise' For -Eample Q 2rogram to perform integer division avoiding the division Dy Pero case' #include <stdio.h> void main() { int numerator/ denominator ' print ( #<nter two inte"ers as denominator *# )' scan ( #Ad/ Ad#/ Enumerator/ Edenominator i ollows ) ' numerator/

( denominator H1 5 ) print ( #Ad / Ad 1 Ad &n#/ numerator/ denominator/ numerator / denominator )' else print ( #Snvalid operation 8 unable to divide b+ Gero &n, )' As Cith all other control statements the statement Dody can also involve mBltiple statementsI again contained Cithin cBrly Draces'

%<

-Eample Q 2rogram to coBnt the nBmDer of occBrrences of the letter GaG in an inpBt stream of characters terminated Cith a carriage retBrn' #include <stdio.h> void main() { int count 1 5/ total 1 5 ' char ch ' while ( { i { ( ch 11 2a2 ) )&n Yetrieved letter OaP number Ad&n,/ count BB ' print ( count ) ' ( total BB ' = lushall() ' ( ( ch 1 "etchar() ) H1 04 ) // 04 is UMCSS value //carria"e return or

print ( #&n&n Ad letters a t+ped in a total o count/ total ) ' (

Ad letters.#/

Nested if statements
if else statements like all other decision or iteration statements in C can De nested to Chatever eEtent is reJBired' Care shoBld De taken hoCever to ensBre that the if and else parts of the statement are matched correctly the rBle to folloC is that the else statement matches the most recent Bnmatched if statement' For -Eample Q i ( ! > 5 i ( ! > puts ( else puts 05#)'

) 05 ) # ! is "reater than Gero and also "reater than 05 #)' (#! is "reater than Gero but less than or eCual to

+he else claBse matches the most recent Bnmatched if claBseI if = E W !$ >' For more clarity the aDove section coBld De reCritten as folloCs Bsing cBrly Draces Cith no eEecBtion penalty Q i { i ( ! > 5 )

( ! > 05 ) puts ( # ! is "reater than Gero and also "reater than 05 #)' else puts ( #! is "reater than Gero but less than or eCual to 05 #)' (

if - else - if ladder
"$

0hen a programming sitBation reJBires the choice of one case from many different cases sBccessive if statements can De tied together forming Chat is sometimes called an if else if ladder' ynta! " if ( con#ition() statement() ; else if ( con#ition(* statement(* ; else if ( con#ition(+ statement(+ ; ... else if ( con#ition(n statement(n ; else statement(#efault ; -ssentially Chat Ce have here is a complete if else statement hanging onto each else statement Corking from the Dottom Bp' For -Eample Q Another gBessing game' void main() { int secret 1 050/ "uess/ count 1 5 ' print ( )&n Tr+ and "uess m+ secret number.&n&n, ) ' while ( 0 ) // in inite loop until we break out o { print ( )&n Zake +our "uess* , ) ' scan ( )Ad,/ E"uess ) ' count BB ' i it

( "uess < secret ) print ( )&nU little low. Tr+ a"ain., ) ' else i ( "uess > secret ) print ( )&nU little hi"h. Tr+ a"ain., ) ' else { print ( )&nDk +ou "ot it and onl+ on attempt Ad.,/ count )' break ' ( ( ( NB 1 CaBtion is advisaDle Chen coding the if else if ladder as it tends to De prone to error dBe to mismatched if else claBses'

"!

Conditional %perator "# ?"


+his is a special shorthand operator in C and replaces the folloCing segment i ( condition ) e!pr=0 ' else e!pr=3 ' Cith the more elegant condition W e!pr=0 * e!pr=3 ' +he ^Q operator is a ternary operator in that it reJBires three argBments' One of the advantages of the ^Q operator is that it redBces simple conditions to one simple line of code Chich can De throCn BnoDtrBsively into a larger section of code' For -Eample Q to get the maEimBm of tCo integersI E and yI storing the larger in maE' ma! 1 ! >1 + W ! * + '

+he alternative to this coBld De as folloCs i ( ! > 1 + ) ma! 1 ! ' else ma! 1 + ' giving the same resBlt DBt the former is a little Dit more sBccinct'

The s)itch tatement


+his is a mBlti Dranch statement similar to the if easier to code' ynta! " else ladder =Cith limitations> DBt clearer and

s$itc% ( expression & case constant) , statement) ; brea- ; case constant* , statement* ; brea- ; ... #efault , ' statement ;

+he valBe of eEpression is tested for eJBality against the valBes of each of the constants specified in the ca57 statements in the order Critten Bntil a match is foBnd' +he statements associated Cith that case statement are then eEecBted Bntil a Dreak statement or the end of the sCitch statement is encoBntered' 0hen a Dreak statement is encoBntered eEecBtion KBmps to the statement immediately folloCing the sCitch statement'

"%

+he defaBlt section is optional if it is not inclBded the defaBlt is that nothing happens and eEecBtion simply falls throBgh the end of the sCitch statement' +he sCitch statement hoCever is limited Dy the folloCing Can only test for eJBality Cith in37g7r con53an35 in case statements' *o tCo case statement constants may De the same' Character constants are aBtomatically converted to integer' For -Eample Q 2rogram to simBlate a Dasic calcBlator' #include <stdio.h> void main() { double num0/ num3/ result ' char op ' while ( 0 ) { print ( # <nter number operator number&n# ) ' scan (#A Ac A #/ Enum0/ Eop/ Enum3 ) ' = lushall() ' switch ( op ) { case 2B2 * result 1 num0 B num3 ' break ' case 282 * result 1 num0 8 num3 ' break ' case O*P * result 1 num0 * num3 ' break ' case O/P * i ( num3 H1 5.5 ) { result 1 num0 / num3 ' break ' ( // else we allow to all throu"h or error messa"e de ault * print (#<YYDY 88 Snvalid operation or division b+ 5.5# ) '

( print ( #A Ac A 1 A &n#/ num0/ op/ num3/ result) ' ( /* while statement */ ( NB 1 +he Dreak statement need not De inclBded at the end of the case statement Dody if it is logically correct for eEecBtion to fall throBgh to the neEt case statement =as in the case of division Dy $'$> or to the end of the sCitch statement =as in the case of defaBlt Q >'

)!" E44ici7nc6 Con5id7ra3ion5


(n practical programming the more elaDorate algorithms may not alCays De the most efficient method of designing a program' (n fact in many sitBations the simple straightforCard method of solving a proDlem = Chich may De disregarded as Deing too simplistic > is JBite often the most ""

efficient' +his is definitely trBe Chen program development time is taken into consideration DBt is also trBe in terms of the efficiency of the actBal code prodBced' *evertheless JBite apart from algorithmic considerationsI there are a nBmDer of areas Ce can focBs on in the code itself to improve efficiency' One of the most important efficiency indicators is the time it takes for a program to rBn' +he first step in eliminating slBggishness from a program is to identify Chich parts of the program take the most time to rBn and then to try and improve these areas' +here are many profiling tools availaDle Chich Cill help to estaDlish these areas Dy timing a typical rBn of the program and displaying the time spent in each line of code and the nBmDer of times a each line of code is eEecBted in the program' A small improvement in the efficiency of a single line of code that is called many times can prodBce dramatic overall improvements' Most soBrces of inefficiency resBlt from the inadvertent Bse of time eEpensive operations or featBres of the langBage' 0hile modern compilers contain many advanced optimising featBres to make a program rBn faster in general the more sloppy the code the less improvements can De made Dy these optimisations' +herefore it is important to try and eliminate as mBch inefficiency as possiDle Dy adopting some simple gBidelines into oBr programming practices'

1nnecessary Type Con,ersions


(n many sitBations the fact that C is Ceakly typed is an advantage to the programmer DBt any implicit conversions alloCed in a piece of code take a certain amoBnt of time and in some cases are not needed at all if the programmer is carefBl' Most Bnnecessary conversions occBr in assignmentsI arithmetic eEpressions and parameter passing' Consider the folloCing code segment Chich simply compBtes the sBm of a Bser inpBt list of integers and their average valBe' double avera"e/ sum 1 5.5 ' short value/ i ' ... or ( i15' i < 0555' i BB ) { scan ( )Ad,/ Evalue ) ' sum 1 sum B value ' ( avera"e 1 sum / 0555 ' ! +he conversion from valBeI of type short intI to the same type as sBmI type doBDleI occBrs !$$$ times in the for loop so the inherent inefficiency in that one line is repeated !$$$ times Chich makes it sBDstantial' (f Ce redefine the variaDle sBm to De of type short Ce Cill eliminate these conversions completely' ,oCever as the range of valBes possiDle for a short are JBite small Ce may encoBnter overfloC proDlems so Ce might define sBm to De of type long instead' +he conversion from short to long Cill noC De implicit in the statement DBt it is more efficient to convert from short to long than it is from short to doBDle' #! 5ecaBse of oBr modifications aDove the statement avera"e 1 sum / 0555 ' noC involves integer division Chich is not Chat Ce reJBire here' = *ote hoCever that an implicit conversion of !$$$ from int to long occBrs here Chich may De simply avoided as folloCs Q avera"e 1 sum / 0555? ' Cith no time penalty Chatsoever as it is carried oBt at compile time'> "&

+o remedy the sitBation Ce simply do the folloCing Q avera"e 1 sum / 0555.5 ' )! +he statement sum 1 sum B value ' also involves another soBrce of inefficiency' +he variaDle sBm is loaded tCice in the statement Bnnecessarily' (f the shorthand operator HX Cere Bsed instead Ce Cill eliminate this' sum B1 value '

1nnecessary $rithmetic
(n general the 8oD753 87978 ari3=m73ic is more efficient especially in mBltiplication and division Chich are inherently eEpensive operations' For -Eample Q double d ' int i ' d 1 i * 3.5 ' +his operation reJBires that the variaDle i is converted to doBDle and the mBltiplication Bsed is then floating point mBltiplication' (f Ce instead Crite the statement as d 1 i * 3 ' Ce Cill have integer mBltiplication and the resBlt is converted to doBDle Defore Deing assigned to d' +his is mBch more efficient than the previoBs and Cill give the same resBlt = as long as the mBltiplication does not overfloC >' Again very little Cill De saved in a single sBch operation DBt Chen one of many the saving may amoBnt to something for eEample the eEpression 3.5 * . * k * l * m Chere KI kI l and m are integers might involve foBr floating point mBltiplications rather than foBr integer mBltiplications Chen coded Cith efficiency in mind' +he Bse of the Tto the poCer of T fBnctionI poC=> in CI is another common eEample of Bnnecessary arithmetic' CompBting the valBe of nBm% or nBm" for eEample shoBld never De done in a program Bsing the poC fBnction especially if nBm is an integer' +his is DecaBse there is an overhead in actBally calling the poC fBnction and retBrning a valBe from it and there is an overhead if a type conversion has to De made in passing the parameters to poC=> or assigning the retBrn valBe from the fBnction' (nstead straightforCard mBltiplication shoBld De Bsed i'e' num * num rather than pow( num/ 3 ) '

"3

0hen large poCers are involved it does make sense to Bse the poC fBnction DBt again the sitBation shoBld De evalBated on its oCn merit' For eEample if Ce Cant to print a taDle of nBmn Chere n X ! ''' <<' (f Ce do the folloCing double num ' int k ' or ( k 1 0' k <055' kBB ) print ()Al to Ad 1 Al &n,/ num/ k/ pow( num/ k ))' Ce Cill end Bp Cith approEimately n X &<3$ mBltiplications plBs << fBnction calls' 0hereas if Ce had Bsed double sum 1 num ' or ( k 1 3' k <1 055' kBB ) { print ( )Al to Ad 1 Al &n,/ num/ k/ sum ) ' sum *1 num ' ( Ce Cill reJBire KBst = n ! > i'e' <9 mBltiplications in total' COs 5it Cise operators may also De Bsed to improve efficiency in certain sitBations' CompBting the valBe of %n can De done most efficiently Bsing the left shift operator i'e' 0 << n Determining Chether a valBe is odd or even coBld De done Bsing i ( num A 3 ) print ( )odd, ) ' else print ( )even, ) ' DBt it is more efficient to Bse i ( num E 0 ) print ( )odd, ) ' else print ( )even, ) '

)!, E;7rci575
! 0rite a program Chich prints oBt the A6C(( and heE valBes of all characters inpBt at the keyDoard terminating only Chen the character `JG or `_G is entered' #! 0rite a program to keep coBnt of the occBrrence of a Bser specified character in a stream of characters of knoCn length = e'g' 3$ characters > inpBt from the keyDoard' Compare this to the total nBmDer of characters inpBt Chen ignoring all DBt alphaDetic characters' *oteQ +he A6C(( valBes of GAG'''GaG are 63'''<$ and GaG'''GPG are <8'''!%%' )! 0rite a program to find the roots of a Bser specified JBadratic eJBation' Recall the roots of aE% + DE + c = $ are "6

D D% &ac %a
+he Bser shoBld De informed if the specified JBadratic is valid or not and shoBld De informed hoC many roots it hasI if it has eJBal or approEimately eJBal roots =D% XX &ac>I if the roots are real =D% &ac W $> or if the roots are imaginary =D % &ac [ $>' (n the case of imaginary roots the valBe shoBld De presented in the form = E H i y >' *ote that C has a standard liDrary fBnction sJrt= >I Chich retBrns the sJBare root of its operandI and Chose prototype can De foBnd Doth in the help system' NB 1 +he floating point nBmDer system as represented Dy the compBter is .gappy1' *ot all real nBmDers can De represented as there is only a limited amoBnt of memory given toCards their storage' +ype float for eEample can only represent seven significant digits so that for eEample $'!%"&368 and $'!%"&369 are deemed consecBtive floating point nBmDers' ,oCever in reality there are an infinite nBmDer of real nBmDers DetCeen these tCo nBmDers' +hBs Chen testing for eJBalityI e'g' testing if D% XX &acI one shoBld test for approEimate eJBality i'e' Ce shoBld test if D% &ac [ $'$$$$! Chere Ce are Dasically saying that accBracy to five decimal places Cill sBffice' "! 0rite a program that alloCs the Bser to read a Bser specified nBmDer of doBDle precision floating point nBmDers from the keyDoard' 7oBr program shoBld calcBlate the sBm and the average of the nBmDers inpBt' +ry and ensBre that any erroneoBs inpBt is refBsed Dy yoBr programI e'g' inadvertently entering a non nBmeric character etc' ,! 0rite a program to print oBt all the FiDonacci nBmDers Bsing 5=or3 integer variaDles Bntil the nBmDers Decome too large to De stored in a short integer variaDle i'e' Bntil overfloC occBrs' a' Use a for loop constrBction' D' Use a Chile loop constrBction' 0hich constrBction is most sBitaDle ^ *oteQ FiDonacci nBmDers are =!I!I%I"I3I9I!"I''' ,! 0rite a program Chich simBlates the action of a simple calcBlator' +he program shoBld take as inpBt tCo integer nBmDers then a character Chich is one of HI I@I#IR' +he nBmDers shoBld De then processed according to the operator inpBt and the resBlt printed oBt' 7oBr program shoBld correctly intercept any possiDle erroneoBs sitBations sBch as invalid operationsI integer overfloCI and division Dy Pero'

"8

Chapter &

+unc3ion5
As Ce have previoBsly stated fBnctions are essentially KBst groBps of statements that are to De eEecBted as a Bnit in a given order and that can De referenced Dy a BniJBe name' +he only Cay to eEecBte these statements is Dy invoking them or calling them Bsing the fBnctionOs name' +raditional program design methodology typically involves a top#do)n or strBctBred approach to developing softCare solBtions' +he main task is first divided into a nBmDer simpler sBD tasks' (f these sBD tasks are still too compleE they are sBDdivided fBrther into simpler sBD tasksI and so on Bntil the sBD tasks Decome simple enoBgh to De programmed easily' FBnctions are the highest level of the DBilding Dlocks given to Bs in C and correspond to the sBD tasks or logical Bnits referred to aDove' +he identification of fBnctions in program design is an important step and Cill in general De a continBoBs process sBDKect to modification as more Decomes knoCn aDoBt the programming proDlem in progress' 0e have already seen many C fBnctions sBch as main= > I printf=>I etc' the common trait they share Deing the Draces that indicate they are C fBnctions' ynta! " return(type function(name ( & bo#y of function ; ' parameter(list

+he aDove is termed the 4unc3ion d74ini3ion in C parlance' Many fBnctions Cill prodBce a resBlt or retBrn some information to the point at Chich it is called' +hese fBnctions specify the type of this JBantity via the return2type section of the fBnction definition' (f the retBrn type is !oid it indicates the fBnction retBrns nothing' +he function2name may De any valid C identifier and mBst De BniJBe in a particBlar program' (f a fBnction reJBires information from the point in the program from Chich it is called this may De passed to it Dy means of the parameter2list' +he parameter list mBst identify the names and types of all of the parameters to the fBnction individBally' (f the fBnction takes no parameters the Draces can De left empty or Bse the keyCord void to indicate that sitBation more clearly'

"! +unc3ion Pro3o36<7 I d7c8ara3ionJ


0hen Criting programs in C it is normal practice to Crite the main=> fBnction first and to position all Bser fBnctions after it or indeed in another file' +hBs if a Bser fBnction is called directly in main=> the compiler Cill not knoC anything aDoBt it at this point i'e' if it takes parameters etc' +his means Ce need to give the compiler this information Dy providing a fBnction prototype or declaration Defore the fBnction is called' ynta! " type(spec function(name( type(par). type(par*. etc. ;

+his declaration simply informs the compiler Chat type the fBnction retBrns and Chat type and hoC many parameters it takes' *ames may or may not De given to the parameters at this time' For -Eample Q A more complicated .,ello 0orld1 program' "9

#include <stdio.h> void hello( void ) ' void main( void ) { hello () ' (

/* standard S/D

unction protot+pes */ */

/* protot+pe

//

unction call

void hello ( ) // unction de inition { print ( #$ello %orld &n# ) ' (

"!# +unc3ion D74ini3ion . &oca8 %aria:875


A fBnction definition actBally defines Chat the fBnction does and is essentially a discrete Dlock of code Chich cannot De accessed Dy any statement in any other fBnction eEcept Dy formally calling the fBnction' +hBs any variaDles declared and Bsed in a fBnction are private or local to that fBnction and cannot De accessed Dy any other fBnction' For -Eample Q #include <stdio.h> void hello( void ) ' void main( { hello () ' ( )

void hello ( ) { int i ' /*

local

or automatic variable

*/

or ( i15' i<05' iBB ) print ( #$ello %orld &n# )' ( +he variaDle i in the hello=> fBnction is private to the hello fBnction i'e' it can only De accessed Dy code in the hello=> fBnction' /ocal variaDles are classed as aBtomatic variaDles DecaBse each time a fBnction is called the variaDle is aBtomatically created and is destroyed Chen the fBnction retBrns control to the calling fBnction' 5y created Ce mean that memory is set aside to store the variaDleOs valBe and Dy destroyed Ce mean that the memory reJBired is released' +hBs a local variaDle cannot hold a valBe DetCeen consecBtive calls to the fBnction'

"<

tatic (ocal Variables


+he keyCord static can De Bsed to force a local variaDle to retain its valBe DetCeen fBnction calls' For -Eample Q #include <stdio.h> void hello( void ) ' void main () { int i ' or ( i 1 5' i < 05' iBB ) hello ( ) ' ( void hello( ) { static int i 1 0 ' print ( #$ello %orld call number Ad&n#/ i BB )' ( +he static int i is created and initialised to ! Chen the fBnction is first called and only then' +he variaDle retains its last valBe dBring sBDseJBent calls to the fBnction and is only destroyed Chen the program terminates' NB 1 +he variaDles i in main=> and i in hello=> are completely different variaDles even thoBgh they have the same name DecaBse they are private to the fBnction in Chich they are declared' +he compiler distingBishes DetCeen them Dy giving them their oCn BniJBe internal names'

"!) Sco<7 Ru875


+he scope of an identifier is the area of the program in Chich the identifier can De accessed' (dentifiers declared inside a code Dlock are said to have Dlock scope' +he Dlock scope ends at the terminating M of the code Dlock' /ocal variaDles for eEample are visiDleI i'e' can De accessedI from Cithin the fBnctionI i'e' code DlockI in Chich they are declared' Any Dlock can contain variaDle declarations De it the Dody of a loop statementI if statementI etc' or simply a Dlock of code marked off Dy a cBrly Drace pair' 0hen these Dlocks are nested and an oBter and inner Dlock contain variaDles Cith the same name then the variaDle in the oBter Dlock is inaccessiDle Bntil the inner Dlock terminates' )loDal variaDles are variaDles Chich are declared oBtside all fBnctions and Chich are visiDle to all fBnctions from that point on' +hese are said to have file scope' All fBnctions are at the same level in C i'e' cannot define a fBnction Cithin a fBnction in C' +hBs Cithin the same soBrce file all fBnctions have file scope i'e' all fBnctions are visiDle or can De called Dy each other = assBming they have Deen prototyped properly Defore they are called >'

"!" R73urning a %a8u7


+he r73urn statement is Bsed to retBrn a valBe to the calling fBnction if necessary'

&$

ynta! "

return expression ;

(f a fBnction has a retBrn type of type void the eEpression section can De omitted completely or indeed the Chole retBrn statement can De omitted and the closing cBrly Drace of the fBnction Cill caBse eEecBtion to retBrn appropriately to the calling fBnction' For -Eample Q #include <stdio.h> int hello( void ) ' int main( ) { int count/ ch 1 O&5P' while ( ch H1 2C2 ) { count 1 hello( ) ' ch 1 "etchar() ' = lushall() ' ( print ( #hello was called Ad times&n#/ i ) ' return 5 ' ( int hello( ) { static int i 1 0 ' print ( #$ello %orld &n# ) ' // hello() keeps track o how called return ( iBB ) ' back to its caller ( // and passes that in ormation man+ times it was

NB 1 +he retBrn valBe of the fBnction need not alCays De Bsed Chen calling it' (n the aDove eEample if Ce are not interested in knoC hoC often hello=> has Deen called Ce simply ignore that information and invoke the fBnction Cith hello() ' NB 1 0hen the main=> fBnction retBrns a valBeI it retBrns it to the operating system' aero is commonly retBrned to indicate sBccessfBl normal termination of a program to the operating system and other valBes coBld De Bsed to indicate aDnormal termination of the program' +his valBe may De Bsed in Datch processing or in deDBgging the program'

"!, +unc3ion Argum7n35


+he types of all fBnction argBments shoBld De declared in the fBnction prototype as Cell as in the fBnction definition'

&!

NB 1 (n C argBments are passed to fBnctions Bsing the call"by"!alue scheme' +his means that the compiler copies the valBe of the argBment passed Dy the calling fBnction into the formal parameter list of the called fBnction' +hBs if Ce change the valBes of the formal parameters Cithin the called fBnction Ce Cill have no effect on the calling argBments' +he formal parameters of a fBnction are thBs local variaDles of the fBnction and are created Bpon entry and destroyed on eEit' For -Eample Q 2rogram to add tCo nBmDers' #include <stdio.h> protot+pe 88 need to indicate

int add( int/ int ) ' /* t+pes onl+ */ void main ( ) { int !/ + '

puts ( #<nter two inte"ers #) ' scan ( #Ad Ad#/ E!/ E+) ' print ( #Ad B Ad 1 Ad&n# / !/ +/ add(!/+) ) ' ( int add ( int a/ int b ) { int result ' result 1 a B b ' return result ' ( // parentheses used or clarit+ here

NB 1 (n the formal parameter list of a fBnction the parameters mBst De individBally typed' +he add=> fBnction here has three local variaDlesI the tCo formal parameters and the variaDle resBlt' +here is no connection DetCeen the calling argBmentsI E and yI and the formal parametersI a and DI other than that the formal parameters are initialised Cith the valBes in the calling argBments Chen the fBnction is invoked' +he sitBation is depicted DeloC to emphasise the independence of the varioBs variaDles'
main( x y !alue co"ied !alue co"ied add( a b result

NB 1 +he information floC is in one direction only'

&%

For -Eample Q 2rogram that attempts to sCap the valBes of tCo nBmDers' #include <stdio.h> void swap( int/ int ) ' void main( ) { int a/ b ' print ( #<nter two numbers# ) ' scan ( # Ad Ad #/ Ea/ Eb ) ' print ( #a 1 Ad ' b 1 Ad &n#/ a/ b ) ' swap( a/ b ) ' print ( #a 1 Ad ' ( b 1 Ad &n#/ a/ b ) '

void swap( int / int )//This is ori"inal orm o declarator int num0/ num3 '// which +ou ma+ see in older te!ts and code { int temp ' temp 1 num3 ' num3 1 num0 ' num0 1 temp ' ( 6ince C Bses call Dy valBe to pass parameters Chat Ce have actBally done in this program is to sCap the valBes of the formal parameters DBt Ce have not changed the valBes in main=>' Also since Ce can only retBrn one valBe via the retBrn statement Ce mBst find some other means to alter the valBes in the calling fBnction' +he solBtion is to Bse call Dy reference Chere the addresses of the calling argBments are passed to the fBnction parameter list and the parameters are pointers Chich Ce Cill encoBnter later on' For eEample Chen Ce Bse the scanf=> standard liDrary fBnction to read valBes from the keyDoard Ce Bse the : operator to give the address of the variaDles into Chich Ce Cant the valBes placed'

"!/ R7cur5ion
A recBrsive fBnction is a fBnction that calls itself either directly or indirectly throBgh another fBnction' RecBrsive fBnction calling is often the simplest method to encode specific types of sitBations Chere the operation to De encoded can De eventBally simplified into a series of more Dasic operations of the same type as the original compleE operation' +his is especially trBe of certain types of mathematical fBnctions' For eEample to evalBate the factorial of a nBmDerI n nS X n @ n ! @ n % @ ''' @ " @ % @ !' 0e can simplify this operation into nS X n @ =n !>S

&"

Chere the original proDlem has Deen redBced in compleEity slightly' 0e continBe this process Bntil Ce get the proDlem doCn to a task that may De solved directlyI in this case as far as evalBating the factorial of ! Chich is simply !' 6o a recBrsive fBnction to evalBate the factorial of a nBmDer Cill simply keep calling itself Bntil the argBment is !' All of the previoBs =n !> recBrsive calls Cill still De active Caiting Bntil the simplest proDlem is solved Defore the more compleE intermediate steps can De DBilt Dack Bp giving the final solBtion' For -Eample Q 2rogram to evalBate the factorial of a nBmDer Bsing recBrsion' #include <stdio.h> short actorial( short ) ' void main() { short i ' print ()<nter an inte"er and i will tr+ to calculate its actorial * ) ) ' scan ( )Ad,/ Ei ) ' print ( )&n&nThe actorial o Ad/ AdH is Ad&n,/ i/ i/ actorial( i ) ) ' ( short actorial( short num ) { i ( num <1 0 ) return 0 ' else return ( num * actorial( num 8 0 ) ) ' ( +his program Cill not Cork very Cell as is DecaBse the valBes of factorials groC very large very JBickly' For eEample the valBe of 9S is &$"%$ Chich is too large to De held in a short so integer overfloC Cill occBr Chen the valBe entered is greater than 8' Can yoB offer a solBtion to this ^ 0hile admittedly simple to encode in certain sitBations programs Cith recBrsive fBnctions can De sloCer than those CithoBt DecaBse there is a time delay in actBally calling the fBnction and passing parameters to it' +here is also a memory penalty involved' (f a large nBmDer of recBrsive calls are needed this means that there are that many fBnctions active at that time Chich may eEhaBst the machineOs memory resoBrces' -ach one of these fBnction calls has to maintain its oCn set of parameters on the program stack'

"!$ Nd74in7 dir7c3i97


+his is a preprocessor command Chich is Bsed to replace any teEt Cithin a C program Cith a more informative pseBdonym' For -Eample Q #de ine -S 4.0:09@

0hen the preprocessor is called it replaces each instance of the phrase 2( Cith the correct replacement string Chich is then compiled' +he advantage of Bsing this is that if Ce Cish to change the valBe of 2( at any stage Ce need only change it in this one place rather than at each point the valBe is Bsed'

Macros
&&

Macros make Bse of the ?define directive to replace a chBnk of C code to perform the same task as a fBnction DBt Cill eEecBte mBch faster since the overhead of a fBnction call Cill not De involved' ,oCever the actBal code involved is replaced at each call to the macro so the program Cill De larger than Cith a fBnction' For -Eample Q Macro to print an error message' #de ine <YYDY print ( #&n <rror &n# )

void main( ) { ... i ( i > 0555 ) <YYDY ' /* correct IC statement */ (

note must add ' in this case to make

Macros can also De defined so that they may take argBments' For -Eample Q #de ine -Y( l ) print ( #AF.3 #/ l )

void main() { loat num 1 05.34: ' -Y( num ) ' ( 0hat the compiler actBally sees is Q printf= FR9'%f FI nBm > U 0hile admittedly advantageoBs and neat in certain sitBations care mBst De taken Chen coding macros as they are notorioBs for introdBcing BnCanted side effects into programs' For -Eample Q ( \ ) ) void main( ) { int i 1 35/ . 1 :5 / k ' k 1 ZU[( iBB/ .BB ) ' print ( # i 1 Ad/ . 1 Ad&n#/ i/ . )' ... ( +he aDove program might De eEpected to oBtpBt the folloCing i 1 30/ . 1 :0 Chereas in fact it prodBces the folloCing i 1 30/ . 1 :3 Chere the larger valBe is incremented tCice' +his is DecaBse the macro MA; is actBally translated into the folloCing Dy the compiler #de ine ZU[(U/ \) ( ( U ) > ( \ ) W ( U ) *

&3

( ( iBB ) > ( .BB ) W ( iBB ) * ( .BB ) ) so that the larger parameter is incremented tCice in error since parameter passing to macros is essentially teEt replacement'

"!* E44ici7nc6 Con5id7ra3ion5


As Ce have mentioned previoBsly the Bse of fBnctions involves an overhead in passing parameters to them and oDtaining a retBrn valBe from them' For this reason they can sloC doCn yoBr program if Bsed eEcessively' +he alternative to this is to Bse macros in place of fBnctions' +his eliminates the penalty inherent in the fBnction call DBt does make the program larger' +herefore in general macros shoBld only De Bsed in place of small TCoBld DeO fBnctions' +he penalty involved in the fBnction call itself is also the reason Chy iterative methods are preferred over recBrsive methods in nBmerical programming'

&6

"!- E;7rci575
! 0rite a program that can convert temperatBres from the Fahrenheit scale to CelsiBs and Dack' +he relationship is C X =3#<>=F "%>' 7oBr program shoBld read a temperatBre and Chich scale is Bsed and convert it to the otherI printing oBt the resBlts' 0rite one or more fBnctions to carry oBt the actBal conversion' #! 0rite a program that reads in the radiBs of a circle and prints the circleOs diameterI circBmference and area' 0rite fBnctions for appropriate logical tasks in yoBr program' 7oB shoBld ?define all appropriate constants in yoBr program' )! 0rite and test a fBnction to convert an Bnsigned integer to Dinary notation' Use the siPeof operator to make the program machine independent i'e' portaDle' "! 0rite and test tCo fBnctionsI one that packs tCo character variaDles into one integer variaDle and another Chich Bnpacks them again to check the resBlt' ,! 0rite and test a circBlar shift left fBnction for one Dyte Bnsigned variaDles i'e' Bnsigned characters' e'g' !$$!!!$$ circBlar shift left Dy % yields $!!!$$!$'

/! An integer is said to De prime if it is divisiDle only Dy one and itself' 0rite a fBnction Chich determines Chether an integer is prime or not' +o test yoBr fBnction Crite a program that prints oBt all prime nBmDers DetCeen ! and !$I$$$' $! 0rite and test a fBnction to read in a signed integer from the standard inpBt device' 7oBr fBnction shoBld not De alloCed to Bse the scanf fBnction' +he fBnction shoBld have the prototype int "etint( void ) ' and shoBld De aDle to accommodate the presence of a minBs signI a plBs sign or no sign = i'e' positive Dy defaBlt >' *ote that the A6C(( valBes of the digits $ < are consecBtiveI &9 38 and that if Ce Cish to convert the digit T"O for eEample to an integer Ce simply sBDtract the A6C(( valBe of digit T$O from its A6C(( valBe i'e' T"O T$O X 3! &9 X "' *! 0rite and test a fBnction to get a floating point nBmDer from the standard inpBt device' +he fBnction shoBld have the prototype loat "et loat( void ) ' and shoBld De aDle to accommodate normal floating point notation and eEponential notation' 7oB shoBld make Bse of the "etint() fBnction in eEercise 3' to read in the varioBs components of the floating point nBmDer' -! 0rite and test a fBnction double power ( double !/ int n )'

to calcBlate the valBe of E raised to the poCer of n' =a> Use yoBr oCn calcBlations' =D> Use the standard liDrary fBnction pow() = for more information Bse help system > paying particBlar attention to type compatiDilities' 2! 0rite a recBrsive fBnction to calcBlate and print oBt all the FiDonacci valBes Bp to and inclBding the nth ' Recall that the FiDonacci series is !I !I %I "I 3I 9I !"I ''' '+o test yoBr program &8

alloC the Bser to enter the valBe of n and then print oBt the series' +he program shoBld rBn continBoBsly Bntil it is eEplicitly terminated Dy the Bser' ! Programming A55ignm7n3 1 NonA8in7ar EMua3ion5! 7oBr Dasic task in this assignment is to Crite a C program Chich Cill alloC the Bser to solve the folloCing non linear eJBation

f = # > =sin

%# # + ! =$ 3

to an accBracy of !$ 3 Bsing Doth the 5isection method and *eCtonGs method' (n order to De aDle to solve eJBations Bsing these methods yoB Cill need to provide yoBr program Cith sBitaDle initial estimates to the actBal rootI an interval over Chich the sign of f=E> changes in the case of the 5isection method and an initial estimate E $ Chere fG= E$ > is not very small in the case of *eCtonGs method' +o help the Bser to provide sBch estimates yoBr program shoBld first taDBlate the fBnction f=E>I repeatedly Bntil the Bser is satisfiedI over a Bser specified interval \ E !I E%] and Bsing a Bser specified taDBlation step' +his shoBld alloC the Bser to Degin Dy taDBlating the fBnction over a large interval Cith a coarse taDBlation step and to fine doCn the interval and step Bntil he # she can determine the DehavioBr of f=E> in or aDoBt the actBal root' Once the Bser is satisfied Cith the taDBlation yoBr program shoBld read in the appropriate initial estimates from the Bser and test their validity and then solve the eJBation Bsing Doth methods' Finally yoBr program shoBld compare the nBmDer of iterations reJBired to compBte the root Bsing Doth methods and print oBt the valBe of the root' 7oB shoBld Dreak yoBr program Bp into appropriate 8ogica8 fBnctions and try to intercept all erroneoBs sitBations as soon as possiDle and take appropriate action' No37 1 +he eEact solBtion to the aDove eJBation is !'3<396<"3<'

&9

Chapter 3

Arra65 . S3ring5
An array is a collection of variaDles of the same type that are referenced Dy a common name' 6pecific elements or variaDles in the array are accessed Dy means of an indeE into the array' (n C all arrays consist of contigBoBs memory locations' +he loCest address corresponds to the first element in the array Chile the largest address corresponds to the last element in the array' C sBpports Doth single and mBlti dimensional arrays'

,! Sing87 Dim7n5ion Arra65


ynta! " 36<7 9arOnam7C 5iP7 E H Chere type is the type of each element in the arrayI varbname is any valid C identifierI and siPe is the nBmDer of elements in the array Chich has to De a constant valBe' NB 1 In C a88 arra65 u57 P7ro a5 3=7 ind7; 3o 3=7 4ir53 787m7n3 in 3=7 arra6' For -Eample Q int arra+] 9 ^ '

Chich Ce might illBstrate as folloCs for a "% Dit system Chere each int reJBires & Dytes' array\$] array\!] array\%] array\"] array\&] !% "&3 "&% "$$$$ %"&33 locn !$$$ locn !$$& locn !$$9 locn !$!% locn !$!6

NB 1 +he valid indices for array aDove are $ '' &I i'e' $ '' nBmDer of elements ! For -Eample Q +o load an array Cith valBes $ '' << int !]055^ ' int i ' or ( i 1 5' i < 055' iBB ) !]i^ 1 i ' Arrays shoBld De vieCed as KBst collections of variaDles so Ce can treat the individBal elements in the same Cay as any other variaDles' For eEample Ce can oDtain the address of each one as folloCs to read valBes into the array or ( i 1 5' i < 055' iBB ) { print ( #<nter element Ad#/ i B 0 ) ' scan ( #Ad&n#/ E!]i^ ) ' ( NB 1 *ote the Bse of the printf statement here' As arrays are normally vieCed as starting Cith indeE ! the Bser Cill feel happier Bsing this so it is good policy to Bse it in .pBDlic1' &<

+o determine to siPe of an array at rBn time the siPeof operator is Bsed' +his retBrns the siPe in Dytes of its argBment' +he name of the array is given as the operand siGe=o =arra+ 1 siGeo ( arra+=name ) '

NB 1 C carries oBt no DoBndary checking on array access so the programmer has to ensBre he#she is Cithin the DoBnds of the array Chen accessing it' (f the program tries to access an array element oBtside of the DoBnds of the array C Cill try and accommodate the operation' For eEample if a program tries to access element array\3] aDove Chich does not eEist the system Cill give access to the location Chere element array\3] shoBld De i'e' 3 E & Dytes from the Deginning of the array' array\$] array\!] array\%] array\"] array\&] array\3] !% "&3 "&% "$$$$ %"&33 !%" locn !$$$ locn !$$& locn !$$9 locn !$!% locn !$!6 locn !$%$

+his piece of memory does not Delong to the array and is likely to De in Bse Dy some other variaDle in the program' (f Ce are KBst reading a valBe from this location the sitBation isnOt so drastic oBr logic KBst goes hayCire' ,oCever if Ce are Criting to this memory location Ce Cill De changing valBes Delonging to another section of the program Chich can De catastrophic'

Initialising $rrays
Arrays can De initialised at time of declaration in the folloCing manner' t+pe arra+] siGe ^ 1 { value list (' For -Eample Q int i]9^ 1 {0/ 3/ 4/ :/ 9 ( '

i]5^ 1 0/ i]0^ 1 3/ etc. +he siPe specification in the declaration may De omitted Chich caBses the compiler to coBnt the nBmDer of elements in the valBe list and allocate appropriate storage' For -Eample Q int i] ^ 1 { 0/ 3/ 4/ :/ 9 ( '

,!# S3ring5
(n C a string is defined as a character array Chich is terminated Dy a special characterI the nBll character GN$GI as there is no string type as sBch in C' +hBs the string or character array mBst alCays De defined to De one character longer than is needed in order to cater for the GN$G'

3$

For -Eample Q string to hold 3 characters char s];^ ' GN$G A string constant is simply a list of characters Cithin doBDle JBotes e'g' F,elloF Cith the GN$G character Deing aBtomatically appended at the end Dy the compiler' A string may De initialised as simply as folloCs char s];^ 1 #$ello# ' G,G as opposed to GeG GlG GlG GoG GN$G

char s];^ 1 { 2$2/ 2e2/ 2l2/ 2l2/ 2o2/ 2&52 ( '

Again the siPe specification may De omitted alloCing the compiler to determine the siPe reJBired'

Manipulating trings
0e can print oBt the contents of a string Bsing printf=> as Ce have seen already or Dy Bsing pBts=>' print ( #As#/ s ) ' puts( s ) ' 6trings can De read in Bsing scanf=> scan ( #As#/ s ) ' Chere Ce do not reJBire the familiar : as 3=7 nam7 o4 an arra6 Di3=ou3 an6 ind7; or 5Muar7 :rac75 i5 a85o 3=7 addr755 o4 3=7 arra6' A string can also De read in Bsing gets=> "ets ( s ) ' +here is also a Cide range of string manipBlation fBnctions inclBded in the C 6tandard /iDrary Chich are prototyped in [string'hW Chich yoB shoBld familiarise yoBrself Cith' For -Eample Q char s0]35^ 1 )Mtrin"0,/ int i ' strcp+( s0/ s3 ) ' /* s3]35^ 1 )Mtrin"3, ' copies s3 into s0. */

i 1 strcmp( s0/s3 ) ' /* compares s0 and s3. St returns Gero i s0 same as s3/80 i s0 < s3/ and B0 i s0 > s3 */ i 1 strlen( s0 ) ' strcat ( s0/ s3 ) ' /* returns the len"th o s0 */ s0 */

/* Concatenates s3 onto end o

,!) Mu83idim7n5iona8 Arra65


3!

MBltidimensional arrays of any dimension are possiDle in C DBt in practice only tCo or three dimensional arrays are CorkaDle' +he most common mBltidimensional array is a tCo dimensional array for eEample the compBter displayI Doard gamesI a mathematical matriE etc' ynta! " type name ! ro$s " ! columns " ;

For -Eample Q %D array of dimension % ; "' int d] 3 ^ ] 4 ^ ' d]5^]5^ d]0^]5^ d]5^]0^ d]0^]0^ d]5^]3^ d]0^]3^

A tCo dimensional array is actBally an array of arraysI in the aDove case an array of tCo integer arrays =the roCs> each Cith three elementsI and is stored roC Cise in memory' For -Eample Q 2rogram to fill in a %D array Cith nBmDers ! to 6 and to print it oBt roC Cise' #include <stdio.h> void main( ) { int i/ ./ num]3^]4^ ' or ( i 1 5' i < 3' iBB ) or ( . 1 5' . < 4' . BB ) num]i^].^ 1 i * 4 B . B 0 ' or ( i 1 5' i < 3' iBB ) { or ( . 1 5' . < 4' . BB ) print (#Ad #/num]i^].^ print (#&n# )' ( ( For -Eample Q 2rogram to taDBlate sin(!) from E X $ to !$ radians in steps of $'! radians' #include <stdio.h> #include <math.h> void main() { int i ' double ! ' double table]055^]3^ '// we will need 055 data points or // the above ran"e and step siGe and // will store both ! and (!) or ( ! 1 5.5/ i 1 5' ! < 05.5' ! B1 5.0/ iBB ) { table]i^]5^ 1 ! ' table]i^]0^ 1 sin( ! ) ' print ()&n Min( Al ) 1 Al ,/ table]i^]5^/ table]i^ ]0^ )' ( ( +o initialise a mBltidimensional array all DBt the leftmost indeE mBst De specified so that the compiler can indeE the array properly' For -Eample Q 3%

) '

int d] ^ ] 4 ^ 1 { 0/ 3/ 4/ :/ 9/ ; ( ' ,oCever it is more BsefBl to enclose the individBal roC valBes in cBrly Draces for clarity as folloCs' int d] ^ ] 4 ^ 1 { {0/ 3/ 4(/ {:/ 9/ ;( ( '

,!" Arra65 o4 S3ring5


An array of strings is in fact a tCo dimensional array of characters DBt it is more BsefBl to vieC this as an array of individBal single dimension character arrays or strings' For -Eample Q char str=arra+] 05 ^ ] 45 ^ '

Chere the roC indeE is Bsed to access the individBal roC strings and Chere the colBmn indeE is the siPe of each stringI thBs strbarray is an array of !$ strings each Cith a maEimBm siPe of %< characters leaving one eEtra for the terminating nBll character' For -Eample Q 2rogram to read strings into strbarray and print them oBt character Dy character' #include <stdio.h> char str=arra+]05^]45^ ' void main() { int i/ . ' puts(#<nter ten strin"s&n#) ' or ( i 1 5 ' i < 05' iBB ) // read in as strin"s so a sin"le or // loop su ices { print ( # Ad * #/ i B 0) ' "ets( str=arra+]i^ ) ' ( or ( i 1 5' i < 05' iBB )//printed out as individual chars so a { // nested or loop structure is reCuired or ( .15' str=arra+]i^].^ H1 2&52 ' .BB ) putchar ( str=arra+]i^].^ ) ' putchar( 2&n2 ) ' ( (

3"

,!, Arra65 a5 argum7n35 3o 4unc3ion5 I D J


(n C it is impossiDle to pass an entire array as an argBment to a fBnction instead the address of the array is passed as a parameter to the fBnction' =(n time Ce Cill regard this as a pointer>' +he name of an array CithoBt any indeE is the address of the first element of the array and hence of the Chole array as it is stored contigBoBsly' ,oCever Ce need to knoC the siPe of the array in the fBnction either Dy passing an eEtra parameter or Dy Bsing the siPeof operator'' For -Eample Q void main() { int arra+]35^ ' unc0( arra+ ) '/* passes pointer to arra+ to ( 6ince Ce are passing the address of the array the fBnction Cill De aDle to manipBlate the actBal data of the array in main=>' +his is call Dy reference as Ce are not making a copy of the data DBt are instead passing its address to the fBnction' +hBs the called fBnction is manipBlating the same data space as the calling fBnction'
main( func1

unc0 */

array data at address 1000

refers to data at address 1000 no data here

(n the fBnction receiving the array the formal parameters can De declared in one of three almost eJBivalent Cays as folloCs Q As a siPed array Q unc0 ( int !]05^ ) { ... ( As an BnsiPed array Q unc0 ( int !] ^ ) { ... ( As an actBal pointer unc0 ( int *! ) { ... ( All three methods are identical DecaBse each tells Bs that in this case the address of an array of integers is to De eEpected' *ote hoCever that in cases % and " aDove Chere Ce specify the formal parameter as an BnsiPed array or simply as a pointer Ce cannot determine the siPe of the array passed in Bsing the siPeof operator as the compiler does not knoC Chat dimensions the array has at this point' (nstead siPeof retBrns the siPe of the pointer itselfI tCo in the case of near pointers in a !6 Dit system DBt foBr in "% Dit systems' For -Eample Q 2rogram to calcBlate the average valBe of an array of doBDles' #include <stdio.h> 3&

void read=arra+( double arra+] ^/ int siGe ) ' double mean( double arra+] ^/ int siGe ) ' void main() { double data] 055 ^ ' double avera"e ' read=arra+( data/ 055 ) ' avera"e 1 mean( data/ 055 ) ' ( void read=arra+( double arra+] ^/ int siGe ) { int i ' or ( i 1 5' i<055' iBB ) { print ( )&n<nter data value Ad * i B 0 )' scan ( )Al ,/ Earra+]i^ ' = lushall() ' ( ( double mean( double arra+] ^/ int siGe ) { double total 1 5.5 ' int count 1 siGe ' while ( count88 ) // siGe is a local variable which we can // use at will total B1 arra+] count ^ ' return ( total / siGe ) ' ( For -Eample Q 2rogram to test if a Bser inpBt string is a palindrome or not' #include <stdio.h> int palin( char arra+] ^ ) ' arra+ is a palindrome returns 0 i */ void main( ) { char str]055^ ' puts( #<nter test strin"# ) ' "ets( str ) ' i ( palin( str ) ) print ( #As is a palindrome&n#/ str ) ' else print ( #As is not a palindrome&n#) ' ( /* Xunction to determine i it is a palindrome/ 5 otherwise

33

int palin ( char arra+] ^ ) { int i 1 5/ . 1 5 ' while ( arra+].BB^ ) ' /* "et len"th o strin" i.e. increment . while arra+].^ H1 2&52 */ . 81 3 ' /* move back two 88 "one one be+ond 2&52 */ ' i < . ' iBB/ .88 ) ( arra+] i ^ H1 arra+] . ^ return 5 ' /* return value 5 i palindrome */ i return 0 ' ( or (

not a

/* otherwise it is a palindrome */

An alternative Cay of Criting the palin=> fBnction might De as folloCs Bsing string manipBlation fBnctions = mBst add ?inclBde [string'hW to top of file in this case>' int palin( char arra+] ^ ) { char temp]45^ ' strcp+( temp/ arra+ ) '/* make a workin" cop+ o strrev( temp ) ' i /* reverse strin" */ i return 0 ' else return 5 ' ( /* compare strin"s _ same strcmp returns 5 */ strin" */

( H strcmp( temp/ arra+ ) )

,!/ Pa55ing Mu83idim7n5iona8 Arra65


FBnction calls Cith mBlti dimensional arrays Cill De the same as Cith single dimension arrays as Ce Cill still only pass the address of the first element of the array' ,oCever to declare the formal parameters to the fBnction Ce need to specify all DBt one of the dimensions of the array so that it may De indeEed properly in the fBnction' For -Eample Q %D array of doBDles Q Call fBnc! Cith E a parameter Q Declaration in fBnc! Q ( double !]05^]35^ ' unc0( ! ) ' unc0( double +] ^]35^ ) { '''

+he compiler mBst at least De informed hoC many colBmns the matriE has to indeE it correctly' For eEample to access element y\3]\"] of the array in memory the compiler might do the folloCing element Vo 1 9 * 35 B 4 1 054. 36

NB 1 MBlti dimensional arrays are stored roC Cise so +]9^]4^ is the &th element in the 6th roC' 6ince Ce are dealing Cith an array of doBDles this means it mBst access the memory location !$" ; 9 Dytes from the Deginning of the array' +hBs the compiler needs to knoC hoC many elements are in each roC of the %D array aDove' (n general the compiler needs to knoC all dimensions eEcept the leftmost at the very least' For -Eample Q 2rogram to add tCo % E % matrices' #include < stdio.h> void mat=read( int mat]3^]3^ ) ' // %rite these or //+ourselves void mat=print( int mat]3^]3^ ) ' two unctions

void mat=add( int mat0] ^]3^/ int mat3] ^]3^/ int mat4] ^]3^ ) ' void main() { int mat=a]3^]3^/ mat=b]3^]3^/ mat=res]3^]3^ ' puts( )<nter Zatri! a row8wise *8&n, )' mat=read( mat=a ) ' puts( )&nZatri! a is *8&n, ) ' mat=print( mat=a ) ' puts( )<nter Zatri! b row8wise, )' mat=read( mat=b ) ' puts( )&nZatri! b is *8&n, ) ' mat=print( mat=b ) ' mat=add( mat=a/ mat=b/ mat=res ) ' puts( )The resultant matri! is&n, ) ' mat=print( mat=res ) ' ( void mat=add( int mat0] ^]3^/ int mat3] ^]3^/ int mat4] ^]3^ ) { int ./ k ' or ( . 1 5' . < 3' .BB ) or ( k 1 5' k < 3' kBB ) mat=res].^]k^ 1 mat0].^]k^ B mat3].^]k^ (

'

38

,!$ E;7rci575
! 0rite a program that alloCs the Bser to read a Bser specified nBmDer of doBDle precision floating point nBmDers from the keyDoardI storing them in an array of maEimBm siPe !$$ say' 7oBr program shoBld then calcBlate the sBm and the average of the nBmDers inpBt' #! Modify yoBr program in eEercise ! so that the maEimBm and minimBm valBes in the data are foBnd and are ignored Chen calcBlating the average valBe' )! 0rite a program that alloCs the elements of a Bser inpBt array of doBDles to De reversed so that first Decomes last etc' Use a separate sCap fBnction to carry oBt the sCitching of elements' "! 0rite a program that reads an array of Bp to %$ integers from the keyDoard and prodBces a histogram of the valBes as indicated DeloC' G G G G G G / G G G G G G G $

G G G G G G G G G G ) # "

G G G G G G G G " )

A tCo dimensional array of characters shoBld De Bsed to prodBce the histogramI filling it Cith asterisks appropriate to the data valBes and then KBst printing oBt the array' 6ome scaling Cill De reJBired if the valBes are alloCed to eEceed the nBmDer of asterisks that can fit on the screen vertically' ,! 0rite a program to accept tCo strings from the keyDoardI compare them and then print oBt Chether or not they are the same' /IaJ! 0rite a fBnction to test Chether or not a Cord is a palindrome e'g' MADAM' I:J! Modify the fBnction in %=a> so that Chite space characters are ignored i'e' so that MADAM (M ADAM for eEample is deemed a palindrome' $! 0rite and test a fBnction that inserts a character anyChere in a string' +he fBnction shoBld take the general form strins= char @stringI char characterI int position > *otes Q !' Recall Microsoft C sBpports a Droad range of string handling fBnctions sBch as strlen=>I strcpy=>I etc' %' 7oBr fBnction shoBld provide sBfficient error checking to prevent erroneoBs operation e'g' yoBr fBnction shoBld check that the desired position actBally eEists' "' 7oBr fBnction need not consider memory # space reJBirements placing the onBs on the Bser to make sBre sBfficient space is availaDle in the operands' Modify the strins= > fBnction Critten aDove so that it alloCs a string of characters rather than an individBal character to De inserted at the designated position' 9' 0rite a program that mBltiplies tCo % ; % matrices and prints oBt the resBltant matriE' +he program shoBld read in the individBal matrices and display them in standard format for the Bser to 39

check them' +he Bser shoBld De alloCed to correct#alter any one element of the matriE at a time and check the revised matriE Bntil satisfied' +he resBlts of the operation shoBld De displayed along Cith the tCo component matrices' Recall that

a! a%

D ! c! ' D% c%

d ! a ! c ! + D !c % = d % a % c! + D % c %

a !d ! + D !d % a %d! + D%d %

-! A real polynomial p=E> of degree n is given Dy

p= #> = a$ + a!# + a% # % ++an # n


Chere the coefficients an are real nBmDers' 0rite a fBnction double eval ( double p]^/ double !/ int n )'

Chich calcBlates the valBe of a polynomial of degree n at a valBe E Bsing the coefficients in the array p\]' 7oBr program shoBld read in the valBes of the coefficients a n and store them in an array and present the resBlts of the calcBlation' =a> Use straightforCard calcBlations to compBte the valBe' =D> -mploy ,ornerGs RBle to calcBlate the valBe' Recall ,ornerGs RBle for a three degree polynomial for eEample is p=E> X a$ H E= a ! H E= a% H E= a" >>>

Compare the efficiency oDtained Bsing Doth methods' 2! Programming A55ignm7n3 1 TicATacATo7 0rite a C program Chich alloCs the Bser to play the compBter in a game of tic tac toe =noBghts and crosses >' +he program shoBld Bse a tCo dimensional array to represent the "E" Doard matriE and alloC the varioBs positions on the Doard to De referenced as co ordinates sBch as =$I$> for the Bpper left corner and =%I%> for the loCer right corner' 7oBr program might inclBde fBnctions to do the folloCing Q !' %' "' &' 3' (nitialise the playing area appropriately' Display the cBrrent state of the game' )et the playerGs move' )et the compBterGs move' Check if there is a Cinner'

+he character GOG shoBld De Bsed to indicate a compBter occBpied position and the character G;G to indicate that of a player' +he space character might De Bsed to indicate an BnoccBpied location' (n displaying the cBrrent state of the Doard simple formatted teEt oBtpBt Cill sBffice = clearing the screen DetCeen move Bpdates etc'> as opposed to providing DO6 graphics sBpport' +he tic tac toe progr a m shoBld incorpor a t e the folloCing thre e Bser specified options in a single pack a g e ' 3<

Option !Q +he comp B t e r Cill De limite d to playing a very simpl e dBll ga m e ' 0hen it is the comp B t e r G s tBrn to mov e it simply scan s the Doard ma triE and fills the first Bnocc B pi e d position encoB n t e r e d ' (f it cannot find an Bnocc Bpi e d location it report s a draCn ga m e ' Option %Q +he comp B t e r plays a fBll ga m e ie' it checks first if it can Cin the ga me Cith its cBrre nt move ' +his failing it checks if it can prev e n t the player from Cinning Cith his#her neEt mov e' Other Cis e it fills the first availaDl e Bnocc B pi e d position' Option "Q +he progr a m alloCs tCo player s to play eac h other =CithoBt any help or hintsS>' +he program shoBld rBn continBoBsly alloCing the player to eEit Bsing a special Fhot keyF dBring a game and shoBld alloC the player to choose Cho moves first'

6$

Chapter 6

Poin37r5
2ointers are CithoBt a doBDt one of the most important mechanisms in C' +hey are the means Dy Chich Ce implement call by reference fBnction callsI they are closely related to arrays and strings in CI they are fBndamental to Btilising CGs dynamic memory allocation featBresI and they can lead to faster and more efficient code Chen Bsed correctly' A pointer is a ,ariable that is Bsed to store a memory address' Most commonly the address is the location of another variaDle in memory' (f one variaDle holds the address of another then it is said to point to the second variaDle' Address !$$$ !$$& !$$9 !$!% !$!6 4alBe !$!% %" 4ariaDle ivarbptr ivar

(n the aDove illBstration i!ar is a variaDle of type int Cith a valBe %" and stored at memory location !$!%' i!ar$ptr is a variaDle of type pointer to int Chich has a valBe of !$!% and is stored at memory location !$$&' +hBs ivarbptr is said to point to the variaDle ivar and alloCs Bs to refer indirectly to it in memory' NB 1 (t shoBld De rememDered that ivarbptr is a variaDle itself Cith a specific piece of memory associated Cith itI in this "% Dit case foBr Dytes at address !$$& Chich is Bsed to store an address'

/! Poin37r %aria:875
2ointers like all other variaDles in C mBst De declared as sBch prior to Bse' ynta! " type /ptr ;

Chich indicates that ptr is a pointer to a variaDle of type type' For eEample int *ptr '

declares a pointer ptr to variaDles of type int' NB 1 +he type of the pointer variaDle ptr is int *. +he declaration of a pointer variaDle normally sets aside KBst tCo or foBr Dytes of storage for the pointer Chatever it is defined to point to' (n !6 Dit systems tCo Dyte pointers are termed near pointers and are Bsed in small memory model programs Chere all addresses are KBst segment offset addresses and !6 Dits in length' (n larger memory model programs addresses inclBde segment and offset addresses and are "% Dits long and thBs pointers are & Dytes in siPe and are termed far pointers' (n "% Dit systems Ce have a flat address system Chere every part of memory is accessiDle Bsing "% Dit pointers'

/!# Poin37r O<7ra3or5 G and .


6!

. is a Bnary operator that retBrns the addr755 of its operand Chich mBst De a variaDle' For -Eample Q int *m ' int count1039/ inte"ers */ m 1 Ecount '

'/*

is

pointer

to

int/

count/

are

+he address of the variaDle coBnt is placed in the pointer variaDle m' +he @ operator is the complement of the address operator : and is normally termed the indirection operator' /ike the : operator it is a Bnary operator and it retBrns the 9a8u7 of the variaDle located at the address its operand stores' For -Eample Q i 1 *m '

assigns the valBe Chich is located at the memory location Chose address is stored in mI to the integer i' 6o essentially in this case Ce have assigned the valBe of the variaDle coBnt to the variaDle i' +he final sitBation is illBstrated DeloC'
indirection

coBnt

i !%3 !$$$ !%3 !8%& !$$$ !9%&

One of the most freJBent caBses of error Chen dealing Cith pointers is Bsing an Bninitialised pointer' 2ointers shoBld De initialised Chen they are declared or in an assignment statement' /ike any variaDle if yoB do not specifically assign a valBe to a pointer variaDle it may contain any valBe' +his is eEtremely dangeroBs Chen dealing Cith pointers DecaBse the pointer may point to any arDitrary location in memoryI possiDly to an BnBsed location DBt also possiDly to a memory location that is Bsed Dy the operating system' (f yoBr program tries to change the valBe at this address it may caBse the Chole system to crash' +herefore it is important to initialise all pointers Defore Bse either eEplicitly in yoBr program or Chen defining the pointer' A pointer may also De initialised to $ = Pero > or *U// Chich means it is pointing at nothing' +his Cill caBse a rBn time error if the pointer is inadvertently Bsed in this state' (t is BsefBl to De aDle to test if a pointer has a nBll valBe or not as a means of determining if it is pointing at something BsefBl in a program' NB 1 *U// is ?defined in [stdio'hW' For -Eample Q int var0/ var3 ' int *ptr0/ *ptr3 1 Evar3 ' int *ptr4 1 V>?? ' ... ptr0 1 Evar0 '

ptr0 and ptr3 are noC pointing to data locations Cithin the program so Ce are free to manipBlate them at Cill i'e' Ce are free to manipBlate the piece of memory they point to'

/!) Ca88 :6 R747r7nc7


6%

Recall Chen Ce Canted to sCap tCo valBes Bsing a fBnction Ce Cere BnaDle to actBally sCap the calling parameters as the call Dy valBe standard Cas employed' +he solBtion to the proDlem is to Bse call Dy reference Chich is implemented in C Dy Bsing pointers as is illBstrated in the folloCing eEample' #include <stdio.h> void swap( int */ int void main( ) { int a/ b ' print ( #<nter two numbers# ) ' scan ( # Ad Ad #/ Ea/ Eb ) ' print ( #a 1 Ad ' b 1 Ad &n#/ a/ b ) ' swap( Ea/ Eb ) ' print ( #a 1 Ad ' b 1 Ad &n#/ a/ b ) ' ( void swap ( int *ptr0/ int *ptr3 ) { int temp ' temp 1 *ptr3 ' *ptr3 1 *ptr0 ' *ptr0 1 temp ' ( +he swap() fBnction is noC Critten to take integer pointers as parameters and so is called in main() as swap( Ea/ Eb ) ' Chere the addresses of the variaDles are passed and copied into the pointer variaDles in the parameter list of sCap=>' +hese pointers mBst De de referenced to manipBlate the valBesI and it is valBes in the the same memory locations as in main=> Ce are sCapping Bnlike the previoBs version of sCap Chere Ce Cere only sCapping local data valBes' (n oBr earlier call Dy valBe version of the program Ce called the fBnction from main=> as swap(a,b) % and the valBes of these tCo calling argBments Cere copied into the formal argBments of fBnction sCap' (n oBr call Dy reference version aDove oBr formal argBments are pointers to int and it is the addresses contained in these pointersI =i'e' the pointer valBes>I that are copied here into the formal argBments of the fBnction' ,oCever Chen Ce de reference these pointers Ce are accessing the valBes in the main=> fBnction as their addresses do not change' * ) '

6"

/!" Poin37r5 and Arra65


+here is a very close relationship DetCeen pointer and array notation in C' As Ce have seen already the name of an array = or string > is actBally the address in memory of the array and so it is essentially a constant pointer' For -Eample Q char str]F5^/ *ptr ' ptr 1 str '/* causes ptr to point to start o strin" str ptr 1 Estr]5^ ' /* this per orms the same as above */ (t is illegal hoCever to do the folloCing str 1 ptr ' /* ille0al */ */

as str is a constant pointer and so its valBe i'e' the address it holds cannot De changed' (nstead of Bsing the normal method of accessing array elements Bsing an indeE Ce can Bse pointers in mBch the same Cay to access them as folloCs' char str]F5^/ *ptr / ch' ptr 1 str ' *ptr 1 2a2 ' ch 1 *( ptr B 0 ) +hBs // position the pointer appropriatel+ // access irst element i.e. str]5^ ' // access second element i.e. str]0^

GI arra6 F ind7; J is eJBivalent to arra6Cind7;E'

*ote that the parentheses are necessary aDove as the precedence of @ is higher than that of H' +he eEpression ch 1 *ptr B 0 ' for eEample says to access the character pointed to Dy ptr = str\$] in aDove eEample Cith valBe TaO> and to add the valBe ! to it' +his caBses the A6C(( valBe of TaO to De incremented Dy ! so that the valBe assigned to the variaDle ch is TDO' (n fact so close is the relationship DetCeen the tCo forms that Ce can do the folloCing int !]05^/ *ptr ' ptr 1 ! ' ptr]:^ 1 05 ' pointer */ /* accesses element 9 o arra+ b+ indexing a

/!, Poin37r Ari3=m73ic


2ointer variaDles can De manipBlated in certain limited Cays' Many of the manipBlations are most BsefBl Chen dealing Cith arrays Chich are stored in contigBoBs memory locations' AnoCing the layoBt of memory enaDles Bs to traverse it Bsing a pointer and not get completely lost' A55ignm7n3 int count/ *p0/ *p3 ' 6&

p0 1 Ecount ' directl+ p3 1 p0 ' an address

//

assi"n

the

address

variable

// assi"n the value o

another pointer variable/

Addi3ion ( Su:3rac3ion +he valBe a pointer holds is KBst the address of a variaDle in memoryI Chich is normally a foBr Dyte entity' (t is possiDle to modify this address Dy integer addition and sBDtraction if necessary' Consider the folloCing Ce assBme a "% Dit system and hence "% Dit integers' int int 053 ptr *ptr ' arra+]4^ 1 { 055/ 050/ ( ' 1 arra+ ' ptr array\$] array\!] array\%] Address !$$$ %$$9 %$!% %$!6 4alBe %$$9 !$$ !$! !$%

0e noC have the pointer variaDle ptr pointing at the start of array Chich is stored at memory location %$$9 in oBr illBstration' 6ince Ce knoC that element array\!] is stored at address %$!% directly after element array\$] Ce coBld perform the folloCing to access its valBe Bsing the pointer' ptr B1 0 ' +his sBrprisingly Cill caBse ptr to hold the valBe !$!% Chich is the address of array\!]I so Ce can access the valBe of element array\!]' +he reason for this is that ptr is defined to De a pointer to type intI Chich are foBr Dytes in siPe on a "% Dit system' 0hen Ce add ! to ptr Chat Ce Cant to happen is to point to the n7;3 in37g7r in memory' 6ince an integer reJBires foBr Dytes of storage the compiler increments ptr Dy &' /ikeCise a pointer to type char CoBld De incremented Dy !I a pointer to float Dy &I etc' 6imilarly Ce can carry oBt integer sBDtraction to move the pointer DackCards in memory' ptr 1 ptr 8 0 ' ptr 81 05 ' +he shorthand operators HH and can also De Bsed Cith pointers' (n oBr continBing eEample Cith integers the statement ptr33 4 Cill caBse the address in ptr to De incremented Dy & and so point to the neEt integer in memory and similarly ptr## 4 Cill caBse the address in ptr to De decremented Dy & and point to the previoBs integer in memory' NB 1 +Co pointer variaDles may not De added together = it does not make any logical sense >' char *p0/ *p3 ' p0 1 p0 B p3 ' /* ille0al operation */ +Co pointers may hoCever De sBDtracted as folloCs' int *p0/ *p3/ arra+]4^/ count ' p0 1 arra+ ' p3 1 Earra+]3^ ' count 1 p3 8 p0 ' /* le"al */ +he resBlt of sBch an operation is not hoCever a pointerI it is the nBmDer of elements of the Dase type of the pointer that lie DetCeen the tCo pointers in memory' Com<ari5on5 63

0e can compare pointers Bsing the relational operators XXI [I and W to estaDlish Chether tCo pointers point to the same locationI to a loCer location in memoryI or to a higher location in memory' +hese operations are again Bsed in conKBnction Cith arrays Chen dealing Cith sorting algorithms etc' For -Eample Q 0riting oBr oCn version of the pBts=> standard liDrary fBnction' ! Using array notation void puts( const char s] ^ ) /* const ke+word makes strin" contents read onl+ */ { int i ' or ( i 1 5' s]i^ ' iBB ) putchar( s]i^ ) ' putchar( 2&n2 ) ' ( #! Using pointer notation void puts( const char *s ) // char *const s would make pointer unalterable { while ( *s ) putchar( *sBB ) ' putchar( 2&n2 ) ' ( As yoB can see Dy comparing the tCo versions aDove the second version Bsing pointers is a mBch simpler version of the fBnction' *o eEtra variaDles are reJBired and it is more efficient as Ce Cill see DecaBse of its Bse of pointer indirection' For -Eample Q 2alindrome program Bsing pointers' ?inclBde [stdio'hW int palin= char @ > U void main= > L char str\"$]I c U pBts= F-nter test stringF > U gets= str > U if = palin= str > > printf= FRs is a palindromeNnFI str > U else printf= FRs is not a palindromeNnF> U M int palin = char @str > L char @ptr U ptr X str U Chile = @ptr > 66 #@ FBnction to determine if array is a palindrome' retBrns ! if it is a palindromeI $ otherCise @#

ptrHH U ptr U

#@ get length of string i'e' increment ptr Chile @ptr SX GN$G @# #@ move Dack on7 from GN$G @#

Chile = str [ ptr > if = @strHH SX @ptr > retBrn $ U retBrn ! U M

#@ retBrn valBe $ if not a palindrome @#

#@ otherCise it is a palindrome @#

trings and pointers


CGs standard liDrary string handling fBnctions Bse pointers to manipBlate the strings' For eEample the prototype for the strcmp=> fBnction foBnd in [string'hW is int strcmp= const char @string!I const char @string% > U Chere const is a C keyCord Chich locks the variaDle it is associated Cith and prevents any inadvertent changes to it Cithin the fBnction' 6trings can De initialised Bsing pointer or array notation as folloCs char @str X F,elloNnF U char string\] X F,elloNnF U in Doth cases the compiler allocates KBst sBfficient storage for Doth strings'

/!/ Arra65 o4 Poin37r5


(t is possiDle to declare arrays of pointers in C the same as any other GtypeG' For eEample int @E\!$] U declares an array of ten integer pointers' +o make one of the pointers point to a variaDle one might do the folloCing' E\ % ] X :var U +o access the valBe pointed to Dy E\ % ] Ce CoBld do the folloCing @E\ % ] Chich simply de references the pointer E\ % ] Bsing the @ operator' 2assing this array to a fBnction can De done Dy treating it the same as a normal array Chich happens to De an array of elements of type int @' For -Eample Q void display= int @J\ ]I int siPe > L int t U for = tX$U t [ siPeU tHH > printf= FRd FI @J\t] > U M 68

*ote that J is actBally a pointer to an array of pointers as Ce Cill see later on Cith mBltiple indirection' A common Bse of pointer arrays is to hold arrays of strings' For -Eample Q A fBnction to print error messages' void serror= int nBm > L static char @err\] X L FCannot Open FileNnFI FRead -rrorNnFI F0rite -rrorNnF M U pBts= err\nBm] >U M *ote that Bsing an array of pointers to char initialised as aDove conserves space as no Dlank filling characters are reJBired as CoBld De if Ce Bsed char err\"]\"$] X L ''' M U

/!$ Command &in7 Argum7n35


Command line argBments alloC Bs to pass information into the program as it is rBn' For eEample the simple operating system command type Bses command line argBments as folloCs cQWtype teEt'dat Chere the name of the file to De printed is taken into the type program and the contents of the file then printed oBt' (n C there are tCo in DBilt argBments to the main=> fBnction commonly called argc and arg9 Chich are Bsed to process command line argBments' void main= int argcI char @argv\ ] > L ''' M argc is Bsed to hold the total nBmDer of argBments Bsed on the command line Chich is alCays at least one DecaBse the program name is considered the first command line argBment' arg, is a pointer to an array of pointers to strings Chere each element in argv points to a command line argBment' For eEample argv\$] points to the first stringI the program name' For -Eample Q 2rogram to print a name = saved in name'c > Bsing command line argBments' ?inclBde [stdio'hW void main= int argcI char @argv\ ] > L if = argc SX % > L pBts= FMissing parameter' Usage Q name yoBrnameF > U eEit= ! >U M printf= F,ello RsFI argv\!] > U M 69

+o rBn the program one might type cQNWname tom For -Eample Q 2rogram to coBnt doCn from a given valBeI the coBntdoCn Deing displayed if the argBment FdisplayF is given' ?inclBde [stdio'hW ?inclBde [stdliD'hW ?inclBde [ctype'hW ?inclBde [string'hW void main= int argcI char @argv\ ] > L int dispI coBnt U if = argc [ % > L pBts=FMissing ArgBments Usage Q progname coBnt \display]F >U eEit=!> U M if = argc W % :: Sstrcmp= argv\%]I FdisplayF > > disp X ! U else disp X $ U for = coBnt X atoi= argv\!] > U coBnt U coBnt > if = disp > printf= FRdNnFI coBnt > U printf= .doneNn1 > U M NB 1 C has a Droad range of fBnctions to convert strings into the standard data types and vice versa' For eEample atoi=> converts a string to an integer aDove rememDer all command line argBments are KBst character strings'

/!* D6namic M7mor6 A88oca3ion


+his is the means Dy Chich a program can oDtain and release memory at rBn time' +his is very important in the case of programs Chich Bse large data items e'g' dataDases Chich may need to allocate variaDle amoBnts of memory or Chich might have finished Cith a particBlar data Dlock and Cant to release the memory Bsed to store it for other Bses' +he fBnctions ma88ocIJ and 4r77IJ form the core of CGs dynamic memory allocation and are prototyped in [malloc'hW' malloc=> allocates memory from the heap i'e' BnBsed memory Chile availaDle and free=> releases memory Dack to the heap' +he folloCing is the prototype for the malloc=> fBnction void @ malloc= siPebt nBmbDytes > U malloc=> allocates nBmbDytes Dytes of storage and retBrns a pointer to type void to the Dlock of memory if sBccessfBlI Chich can De cast to Chatever type is reJBired' (f malloc=> is BnaDle to allocate the reJBested amoBnt of memory it retBrns a *U// pointer' 6<

For eEample to allocate memory for !$$ characters Ce might do the folloCing ?inclBde [malloc'hW void main=> L char @p U if = S= p X malloc= siPeof= char > @ !$$ > > L pBts= FOBt of memoryF > U eEit=!> U M M +he retBrn type void @ is aBtomatically cast to the type of the lvalBe type DBt to make it more eEplicit Ce CoBld do the folloCing if = S= =char @ >p X malloc= siPeof= char > @ !$$ > > L pBts= FOBt of memoryF > U eEit=!> U M +o free the Dlock of memory allocated Ce do the folloCing free = p > U *ote Q +here are a nBmDer of memory allocation fBnctions inclBded in the standard liDrary inclBding calloc= >I bfmalloc= > etc' Care mBst De taken to ensBre that memory allocated Cith a particBlar allocation fBnction is released Cith its appropriate deallocation fBnctionI e'g' memory allocated Cith malloc=> is freed only Cith free=> '

/!- Mu83i<87 Indir7c3ion AA Poin37r5 3o Poin37r5


(t is possiDle in C to have a pointer point to another pointer that points to a target valBe' +his is termed mBltiple indirection in this case doBDle indirection' MBltiple indirection can De carried oBt to Chatever eEtent is desired DBt can get convolBted if carried to eEtremes' (n the normal sitBationI single indirectionI a pointer variaDle CoBld hold the address in memory of an appropriate variaDleI Chich coBld then De accessed indirectly Dy de referencing the pointer Bsing the @ operator' (n the case of doBDle indirectionI Ce have the sitBation Chere a variaDle may De pointed to Dy a pointer as Cith single indirectionI DBt that this pointer may also De pointed to Dy another pointer' 6o Ce have the sitBation Chere Ce mBst de reference this latter pointer tCice to actBally access the variaDle Ce are interested in' De referencing the pointer to a pointer once gives Bs a normal singly indirected pointerI de referencing the pointer to a pointer secondly alloCs Bs to access the actBal data variaDle' +he sitBation is depicted in the diagram DeloC'

8$

single indirection

single indirection

doBDlebptr address % address !

singlebptr address " address %


doBDle indirection

variaDle address "

valBe

+o declare a pointer to a pointer Ce inclBde another indirection operator float @ @ ptr U Chich in this case defines a pointer to a pointer to type float ' +he folloCing illBstrates some valid operations Bsing doBDle indirection' int E X !$I @pI @@J U p X :E U J X :p U @@J X %$ U ## de reference tCice to access valBe p X @J U ## de reference J once to get a pointer to int c int array!\] X L !I%I"I&I3I6 I8 I9I<I!$M U int array%\] X L!$I%$I"$I&$I3$M U int @pointers\%] U ## an array of pointers to type int int @@ptr U ## a doBDly indirected pointer ptr X pointers U @ptrHH X array! U @ptr X array% U @@ptr X !$$ U ## initialise pointer to array of pointers ## noC Ce simply de reference the pointer to a pointer ## once and move it on like any pointer

## ptr is pointing at pointers\!] Chich in tBrn is pointing ## at array% so array%\$] is assigned !$$ For -Eample Q Allocation and initialisation of an m E n matriE Bsing doBDle indirection 0hat Ce reJBire here is to allocate an n E n matriE as a collection of discrete roCs rather than KBst as one Dlock of memory' +his format has advantages over a single Dlock allocation in certain sitBations' +he strBctBre Ce end Bp Cith is illBstrated DeloC' arrays of n doBDlesI the roCs pointer pointer to doBDle ptrbroCs to array of m pointers to roCs

8!

?inclBde [stdio'hW ?inclBde [malloc'hW void main= void > L doBDle @@ptrbroCsI @@BserbptrI @elembptr U int mI nI iI K U printf= .NnNn-nter the nBmDer of roCs and colBmns reJBired =mI n> Q . > U scanf= .RdI Rd1I :mI :n > U bflBshall=> U ptrbroCs X = doBDle @@> malloc= m @ siPeof = doBDle @ > > U Bserbptr X ptrbroCs U for = i X $U i [ m U iHH > L @Bserbptr X =doBDle @> malloc= n @ siPeof= doBDle > > U elembptr X @Bserbptr U for = K X $U K [ n U KHH > @elembptrHH X !'$ U BserbptrHH U M Bserbptr X ptrbroCs U for = i X $U i [ nU iHH > free= @Bserbptr HH > U free= ptrbroCs > U M ## free a roC and move onto neEt ## free pointers to roCs ## move onto neEt roC pointer ## after Bse Ce need to clean Bp in reverse order ## space for roC pointers ## and then roC elements

/! 2 Poin37r5 3o +unc3ion5
A fBnction even thoBgh not a variaDle still has a physical address in memory and this address may De assigned to a pointer' 0hen a fBnction is called it essentially caBses an eEecBtion KBmp in the program to the location in memory Chere the instrBctions contained in the fBnction are stored so it is possiDle to call a fBnction Bsing a pointer to a fBnction' +he address of a fBnction is oDtained Dy KBst Bsing the fBnction name CithoBt any parenthesesI parameters or retBrn type in mBch the same Cay as the name of an array is the address of the array' A pointer to a fBnction is declared as folloCs ynta! " r73O36<7 I G 4<3r J I <aram737r 8i53 J H

Chere fptr is declared to De a pointer to a fBnction Chich takes parameters of the form indicated in the parameter list and retBrns a valBe of type retbtype' +he parentheses aroBnd & fptr are reJBired DecaBse CithoBt them the declaration retbtype @ fptr= parameter list > U KBst declares a fBnction fptr Chich retBrns a pointer to type retbtype S 8%

+o assign a fBnction to a pointer Ce might simply do the folloCing int =@fptr>= > U fptr X getchar U #@ standard liDrary fBnction @# +o call the fBnction Bsing a pointer Ce can do either of the folloCing ch X =@fptr>= > U ch X fptr= > U -Eample Q 2rogram to compare tCo strings Bsing a comparison fBnction passed as a parameter' ?inclBde [stdio'hW ?inclBde [string'hW void check= char @aI char @DI int = @ cmp > = > >U void main= > L char s!\9$]I s%\9$] U int =@p>= > U p X strcmp U gets=s!> U gets= s% >U check= s!I s%I p > U M void check = char @aI char @DI int =@ cmp>= > > L if = S cmp= aI D > > pBts= FeJBalF > U else pBts= Fnot eJBalF> U M *ote that even thoBgh Ce do not specify parameters to the fBnction pointer in the prototype or declarator of the fBnction Ce mBst specify them Chen actBally calling the fBnction' *ote also that instead of Bsing an eEplicitly declared pointer variaDle to call the reJBired fBnction in main=> Ce coBld make the call as folloCs check= s!I s%I strcmp > U Chere Ce essentially pass a constant pointer to strcmp= >' For -Eample Q 2rogram that may check for either nBmeric or alphaDetic eJBality' ?inclBde [stdio'hW ?inclBde [ctype'hW ?inclBde [stdliD'hW ?inclBde [string'hW void check= char @aI char @DI int = @ cmp > = > >U int nBmcmp= char @I char @ > U 8"

void main= > L char s!\9$]I s%\9$] U gets=s!> U gets= s% >U if = isalpha= @s! > ## shoBld have a more rigoroBs test here check= s!I s%I strcmp > U else check= s!I s%I nBmcmp > U M void check = char @aI char @DI int =@ cmp>= > > L if = S cmp= aI D > > pBts= FeJBalF > U else pBts= Fnot eJBalF> U M int nBmcmp= char @aI char @D > L if = atoi= a > XX atoi= D > > retBrn $ U else retBrn ! U M

/!

E44ici7nc6 Con5id7ra3ion5

0hen Bsed correctly pointers can lead to more efficient code in sitBations Chere seJBential operations on contigBoBs Dlocks of memory are reJBired' For eEample Chen accessing each element of an array seJBentially' +he inefficient Cay to do this is for = k X $U k [ !$$U kHH > array\ k ] X $'$ U 0hen done this Cay the compiler has to indeE into the array for each iteration of the loop' +his involves reading the cBrrent valBe of the indeEI kI mBltiplying this Dy the siPeof= doBDle > and Bsing this valBe as an offset from the start of the array' +he eEact same thing occBrs if Ce Bse a pointer incorrectly as folloCs ptr X array U for = k X $U k [ !$$U kHH > @= ptr H k > X $'$ U Chereas the most efficient solBtion is of coBrse to do the folloCing Chere the pointer itself is moved Dy the appropriate amoBnt' ptr X array U for = k X $U k [ !$$U kHH > @ptrHH X $'$ U (n this case Ce KBst incBr the addition of siPeof= doBDle > onto the address contained in the pointer variaDle for each iteration' 8&

83

/! # E;7rci575
! 0rite yoBr oCn fBnctions to carry oBt some of the standard string manipBlation tasks inclBded in the standard liDraryI e'g'' strcpy=>I strcat=>I strlen=>I strstr= >' Use the same prototypes as the standard fBnctions DBt Bse slightly different fBnction names in order to De aDle to test the fBnctions in parallel Cith the originals' #! +here is a logical DBg in the folloCing program' Compile rBn and deDBg the program and see if yoB can find it' ?inclBde [stdio'hW ?inclBde [string'hW void main=> L char @p! I s\9$] U p! X s U do L gets= s > U Chile= @p! > printf=FRdFI@p!HH > U M Chile=strcmp=sI FdoneF> > U M )! +he folloCing program section contains a logical error' RBn the program and eEplain Chat happens' ?inclBde [stdio'hW ?inclBde [string'hW void main=> L char @p! X FaDcFI @p% X Fpacific seaF U printf=FRs Rs RsNnFIp!I p%I strcat=p!I p%> >U M "! Use a simple DBDDle sort algorithm to sort an array of characters into alphaDetical order' +he DBDDle sort algorithm is as folloCs' 6tarting at the Deginning of the array eEamine the first pair of adKacent elements and eEchange their valBes if not in the correct order' *eEt move on Dy one element to the neEt pair of valBes the pairs Cill overlap Cith the previoBs pair so that the second element of the first pair Decomes the first element of the second pair' -Eamine the ordering of this pair as Defore' After the first pass of the DBDDle sort over the complete array the last array element is in the correct positionI after the second pass the second last is in positionI etc' +hBs after each pass the Bnsorted portion of the array contains one less element' +his procedBre shoBld De repeated Bntil either a complete pass in Chich no sCaps are reJBired is made or in the Corst case Bntil one less than the total nBmDer of elements nBmDer of passes have Deen made' ,! 0rite a program Chich sets Bp an array of pointers to char Chich are initialised to days of the Ceek say' 0rite and test a fBnction Chich takes an integer parameter to print oBt the corresponding day ' 86

e'g''

6BndayI %

MondayI etc'

+he fBnction shoBld print oBt an invalid message if an incorrect nBmDer is passed to it' /! 0rite and test a program to sort a list of Cords into alphaDetical order' +he standard liDrary string handling fBnctions may De Bsed' A maEimBm nBmDer of Cords to De sorted and a maEimBm length of each Cord shoBld De specified in the interest of memory reJBirements e'g' limit the nBmDer of Cords to 3 and the length of each Cord to !$ ' $! 0rite and test a fBnction Chich can perform Bnsigned integer addition Cith Bp to 3$ digits of precision maintained' For -Eample Q <!%"&!%"&!%"&!%"&!%"&!%"&!%"&!%"&!%"& H !!%"&!%"&!%"&!%"&!%"&!%"&!%"&!%"&!%"& bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb !$%&69%&69%&69%&69%&69%&69%&69%&69%&69 +he program shoBld read in the tCo operands and present the resBlt of the operation as Cell as the tCo operands' *ote Q +here is no C data type Chich can maintain Bp to 3$ digits of precision' *! 0rite a simple fBnction e'g' to add tCo nBmDers and define a pointer to this fBnction to call the fBnction' -! 0rite a program Chich Cill calcBlate and print oBt the valBes of varioBs trigonometric operations from $ rad to %@2( rad at intervals of 2(#&' +he trigonometric operations sBpported = sinI cosI tan I etc'> shoBld De entered as command line parameters' e'g' AQNWtrigprog sin A single generic fBnction shoBld De Bsed to compBte and print oBt the valBes of the operation reJBested taking a pointer to the appropriate standard liDrary fBnction as a parameter' 2rototypes for the C standard liDrary maths fBnctions are inclBded in [math'hW' 2! 0rite a program Chich Cill sort an array of integers Bsing the standard liDrary Jsort=> fBnction' +he Jsort=> fBnction reJBires a pointer to a Bser sBpplied comparison fBnction as a parameter Chich might have the folloCing prototype int comp= int @p!I int @p% > U A retBrn valBe of $ indicates eJBalityI a retBrn valBe of ! indicates element @p! W element @p%I and a retBrn valBe of ! indicates element @p! [ element @p%'

88

! Programming A55ignm7n3 1 Ba57 Con97r5ion Program 7oBr task in this assignment is to Crite a C program Chich converts an un5ign7d 5=or3 in a specified nBmDer DaseI Dase!I to another nBmDer DaseI Dase%' +he nBmDer to De converted is to De entered into the program as an ASCII 53ring and the tCo DasesI Dase! and Dase%I as integers in Dase !$' +he program mBst then convert the nBmDer in Dase! to Dase% and oBtpBt the resBlts for the BserI continBing Bntil an -OF is encoBntered = see later >' For -Eample Q the folloCing inpBt shoBld caBse an oBtpBt statement like that presented DeloC' !% !$ % !% in Dase !$ is !!$$ in Dase % Only Dase valBes in the range % check !$ inclBsive are to De alloCed in the programI so yoB shoBld

!' that Dase! and Dase% are appropriate Dase valBes and %' that the nBmDer string entered does not contain any invalid digitsI i'e' digits oBtside the range for Dase! =or indeed any alphaDetic charactersI DBt it may skip leading Chite space characters > Defore attempting any conversions' (n either case yoBr program shoBld ignore the valBes completely and Crite oBt an appropriate error message to the oBtpBt and then continBe Cith the program' +o convert a nBmDer in Dase! to Dase% it may De simpler to carry oBt the operation in tCo steps as folloCs !' Convert nBmDer string in Dase! to nBmDer in Dase !$ and check that it is in range for Bnsigned short' %' Convert Dase !$ nBmDer to Dase% nBmDer string' +o carry oBt these tCo tasks yoB shoBld provide tCo fBnctions Cith the folloCing prototypes Bnsigned short convertb!$= char @ptrI Bnsigned short DasebD > U char @convertbD= Bnsigned short nBmb!$I Bnsigned short DasebD >U +he convertb!$= > fBnction takes a pointer to an A6C(( string Chich contains a nBmDer in DasebD and shoBld retBrn this nBmDer as a Dase !$ Bnsigned integer' For -Eample Q %" in Dase & X % E &! H " E &$ X 9 H " X !! in Dase !$' 7oBr fBnction shoBld check that the valBe does not eEceed the valBe for an Bnsigned short and retBrn an error valBe if it does' = 6Bggestion Q Make $ 633"& valid valBes and Bse 633"3 as an error retBrn'> +he fBnction convertbD= > takes a valid integer in Dase !$ as its first parameter and converts it to a nBmDer in DasebDI Chich yoB mBst represent as an A6C(( string' 7oBr fBnction shoBld retBrn a pointer to a string containing the nBmDer in DasebDI Chich shoBld De tailored doCn so that the Dare minimBm of space is Bsed = i'e' dynamically allocated once the nBmDer has Deen converted >' +his pointer may De freed in the calling fBnction once it has finished Cith the nBmDer string in JBestion' For -Eample Q Convert !% Dase !$ to Dase % as folloCs

89

!!$$ in Dase %

% !% = 6 Rem $ % 6 = " Rem $ % " = ! Rem ! % ! = $ Rem !


7oBr program shoBld De Critten so that it accepts a nBmDer of optional command line argBments as folloCs progname \soBrcebfile] \ destinationbfile]

(f no command line argBments are present the program shoBld read its inpBt from stdinI the keyDoard and Crite the resBlts to stdoBtI the monitor' (f one command line argBment is present it means that the program is to take its inpBt from the file specified if possiDle Chere it is arranged as folloCs !% !$ % %& 3 8 and Crite the resBlts to the standard oBtpBt' /astly if tCo argBments are given the program is to read its inpBt from the specified file and Crite the resBlts to the specified destination file' (n all cases yoBr program is to continBe reading inpBt from the inpBt device in JBestion Bntil an -OF is encoBntered = or Bntil a conversion error occBrs >' *ote that -OF may De prodBced at the keyDoard Dy CtrlHa' No37 1 7oB may not Bse any of the folloCing family of fBnctions in yoBr program for any reason Bnless yoB implement yoBr oCn versions of them' atoi= >I atol= >I itoa= >I ltoa= >I etc'

File (#O is not covered Bntil Chapter 9 so this section shoBld De pBt aside Bntil later' 8<

#! Programming A55ignm7n3 1 Ta:u8a3ion Program! 7oBr main task in this assignment is to Crite and test a fBnction in3 G3a:u8a37I in3 Gda3a, in3 num9a85 J H +his fBnction takes as its parameters a pointer to an array of integers and the nBmDer of integers in this array and shoBld taDBlate the valBes in the array storing the resBlts in a second array and retBrning it as the fBnctions retBrn valBe' 7oBr main program is to first read in a Bser specified nBmDer of integers from the keyDoard and store them in a dynamically allocated array and then call the taDBlate fBnction' +he taDBlate fBnction mBst first determine the range of the data Deing passed to it i'e' the maEimBm and minimBm valBes it contains and then allocate a Dlock of memory covering this range' For eEample if the data set Cas L 6I !$I 6I 9I 8 M then min X 6 and maE X !$ so Ce need to allocate a Dlock of = maE min H ! > X 3 integers to contain all valBes in the range' +he first element in the array is for the valBe 6I the second for 8I etc' 0e also need to store the maE and min range valBes Chich tells Bs hoC many data valBes are in the array' +o do this Ce modify the aDove representation so that Ce allocate tCo eEtra elements to store the range' +he first element in the array is deemed to De for the minimBmI the second for the maEimBm and the remainder for the data as Defore' +his neC Dlock of data is neEt initialised to Pero i'e' no instances of any of the valBes in the range are present in the data' +he data CoBld look as folloCs Cith oBr aDove eEample' min 6 maE !$ ? 6Os $ ? 8Os $ ? 9Os $ ? <Os $ ? !$Os $

+he fBnction shoBld noC look at the data set and increment the coBnt associated Cith all the elements in it appropriately' +he data set shoBld noC look like the folloCing and Cill De retBrned to the main program Chere the resBlts Cill De displayed' min 6 maE !$ ? 6Os % ? 8Os ! ? 9Os ! ? <Os $ ? !$Os !

7oBr program is also reJBired to accept one eEtra command line argBment' (f this can De opened as a file the resBlts of the taDBlation are to De printed to it otherCise they are to De printed to stdoBt'

9$

)! Programming A55ignm7n3 1 Po86nomia8 Par57r +he Dasic reJBir e m e n t of this assign m e n t is to Crite a C progr a m Chich can resolve a simple polyno mi al into a vector of its comp o n e n t s and to mak e Bse of this form to imple m e n t differe nti a tion of the eJB a tion' +he eJB a tion pars e r shoBld De imple m e n t e d as a fBnction Chich is pas s e d an A6C(( char a c t e r string Chich is Bse d to repr e s e n t a polyno mi al of degr e e n Chich has the gen e r al form

a n # n + a n +! # n +! + a ! # ! + a $ + a! # + a % # % + a n ! # n ! + a n # n
Cher e E is the dep e n d a n t variaDl eI a n are the coefficient s of the polyno mi al =Chich ma y De limite d to signe d integ e r valBe s>' +he char a c t e r string repr e s e n t a t i o n ma y De of any degr e e I nI and the compo n e n t s ma y De in any rando m order and ma y eve n De repe a t e d ' Use the TYO char a c t e r to repr e s e n t to the po er of. +he char a c t e r string ma y also inclBde Chite spac e char a c t e r s for read a DilityI na m e l y the spac e char a c t e r I Chich do not conve y any infor ma tion DBt Chich none t h e l e s s mBs t De proc e s s e d Deing part of the string' 6ome eEa mpl e s of valid eJB a tion s are given DeloC Cher e GbG repr e s e n t s the spac e char a c t e r ' ! H E H %E Y % H 3E Y & %E Y & H "E !% 6 H %E Y " %E H & E & E Y % H E Y ! H %E Y " Eb Yb%b H b%bEb Y b " +he eJB a tion pars e r mBs t resolve the polyno mi al into a vector repr e s e n t a ti o nI ie' it mBs t est a Dlis h a valBe for the coefficient of eac h compo n e n t of the polyno mi al' +his infor ma tio n or vector shoBld De store d in a single dime n sion integ e r arra y Cher e the indeE into the arra y repr e s e n t s a specific compo n e n t of the vector' 4ector\$] repr e s e n t s the coefficient of E Y $ I 4ector\!] repr e s e n t s the coefficient of E Y ! I and so on Bp to the degr e e of the polyno mi al' +he siPe of the vector arra y shoBld vectorI me m o r y Deing allocat e d polyno mi al has Dee n est a Dlis h e d ' CoBld reJBir e an arra y of thre e coefficient s' De KBst sBfficient to stor e the reJBir e d dyna mi c ally once the degr e e of the For eEa m pl e a polyno mi al of degr e e % ele m e n t s to store all the compo n e n t

For testing pBrpos e s yoBr progr a m shoBld first of all take in a polyno mi al in the form of a char a c t e r string as inpBtI resolve this into a vector Bsing the pars e r fBnctionI and then pas s this vector to a fBnction Chich shoBld differe nti a t e the vector = or eJB a tion > and stor e the resBlt in a differe nt vector of appropria t e dime n sio n' +he resBlts of eac h oper a tion shoBld De displa ye d in taDBl ar illBstr a t e d in the folloCing eEa mpl e Cher e the eJB a tion inpBt Cas "E Y % E H &' Coefficient s Q -JBation Q & EY$ ! EY! " 9! EY% 3 EY" form as 3E Y " H

-JBationG Q

!3

+he resBlts of the oper a tion shoBld also De stor e d to a Bser specified teEt file in the sa m e taDBl ar form as aDove ' (n the cas e Cher e the file specified alre a d y eEists and has a nBmD e r of valid entrie sI the neC entry to De add e d shoBld De sep a r a t e d Dy a Dlank line from the other s for rea d a Dility'

9%

Chapter 8

S3ruc3ur75 . Union5
$! S3ruc3ur75
A strBctBre is a cBstomised Bser defined data type in C' (t is Dy definition a collection of variaDles of any type that are referenced Bnder one nameI providing a convenient means of keeping related information together' Som7 37rmino8og6 1A strBctBre definition Q the template Bsed to create strBctBre variaDles' strBctBre elements Q the memDer variaDles of the strBctBre type

&efining tructures
ynta! " 53ruc3 3ag Q 36<7 9arO H 36<7 9arO# H !!! 36<7 9arOn H R H

+he keyCord 53ruc3 tells the compiler Ce are dealing Cith a strBctBre and mBst De present Chenever Ce refer to the neC typeI 3ag is an identifier Chich is the name given to the cBstomised FtypeF' A variaDle of this neC type can noC De defined as folloCs for eEample' *ote that the keyCord strBct has to De Bsed in conKBnction Cith oBr oCn name for the strBctBreI tag' strBct tag variaDle U For -Eample Q strBct R-CORD L int recbno U char name\"$] U char toCn\&$] U char coBntry\ %$ ] MU strBct R-CORD person U +he compiler Cill aBtomatically allocate enoBgh storage to accommodate all the elements' +o find oBt hoC mBch storage is reJBired one might do the folloCing siPe X siPeof = person > U or siPe X siPeof= strBct R-CORD > U NB 1 +he name of a strBctBre is not the address of the strBctBre as Cith array names'

$ccessing tructure +lements


For eEample define a compleE type strBctBre as folloCs' 9"

strBct compleE L doBDle real U doBDle imaginary U M cplE U

## *ote that a variaDle may also De ## defined at strBctBre definition time

+he elements of the strBctBre are accessed Bsing the do3 o<7ra3orI ! I as folloCs cplE'real X !$'$ U cplE'imag X %$'%" U scanf = FRlfFI :cplE'real > U or if Ce Cant to access strBct R-CORD already defined pBts= person'name > U or character Dy character person'name\i] X GaG U +hBs Ce treat strBctBre elements eEactly as normal variaDles and vieC the dot operator as KBst another appendage like the indirection operator or an array indeE'

Initialising tructures
6trBctBre elements or fields can De initialised to specific valBes as folloCs Q strBct id L char name\"$] U int idbno U MU strBct id stBdent X L FdohnFI &36" M U

tructure $ssignment
+he name of a strBctBre variaDle can De Bsed on its oCn to reference the complete strBctBre' 6o instead of having to assign all strBctBre element valBes separatelyI a single assignment statement may De Bsed to assign the valBes of one strBctBre to another strBctBre of the same type' For -Eample Q strBct L int aI D U M E X L!I % MI y U yXEU ## assigns valBes of all fields in E to fields in y

Creating more Comple! tructures )ith tructures


Once again emphasising that strBctBres are KBst like any other type in C Ce can create arrays of strBctBresI nest strBctBresI pass strBctBres as argBments to fBnctionsI etc' For eEample Ce can nest strBctBres as folloCs creating a strBctBre employeeblog that has another strBctBre as one of its memDers' 9&

strBct time L int hoBr U int min U int sec U MU strBct employeeblog L char name\"$] U strBct time startI finish U M employeeb! U +o access the hoBr field of time in the variaDle employeeb! KBst apply the dot operator tCice employeeb!'start'hoBr X < U +ypically a company Cill need to keep track of more than one employee so that an array of employee$log CoBld De BsefBl' strBct employeeblog Corkers\!$$] U +o access specific employees Ce simply indeE Bsing sJBare Draces as normalI e'g' Corkers\!$]' +o access specific memDers of this strBctBre Ce simply apply the dot operator on top of the indeE' Corkers\!$]'finish'hoBr X !$ U 0hen strBctBres or arrays of strBctBres are not gloDal they mBst De passed to fBnctions as parameters sBDKect to the BsBal rBles' For eEample fBnction!= employeeb! > U implements a call to fBnction! Chich might De prototyped as folloCs void fBnction!= strBct employeeblog emp > U *ote hoCever that a fBll local copy of the strBctBre passed is made so if a large strBctBre is involved memory the overhead to simply copy the parameter Cill De high so Ce shoBld employ call Dy reference instead as Ce Cill see in the neEt section' 2assing an array of strBctBres to a fBnction also folloCs the normal rBles DBt note that in this case as it is impossiDle to pass an array Dy valBe no heavy initialisation penalty is paid Ce essentially have call Dy reference' For eEample fBnction%= Corkers > U passes an array of strBctBres to function' Chere the fBnction is prototyped as folloCs' fBnction%= strBct employeeblog staff\ ] > U

93

tructure .ointers
As Ce have said already Ce need call Dy reference calls Chich are mBch more efficient than normal call Dy valBe calls Chen passing strBctBres as parameters' +his applies even if Ce do not intend the fBnction to change the strBctBre argBment' A strBctBre pointer is declared in the same Cay as any pointer for eEample strBct address L char name\%$] U char street\%$] U MU strBct address person U strBct address @addrbptr U declares a pointer addrbptr to data type struct address' +o point to the variaDle person declared aDove Ce simply Crite addrbptr X :person U Chich assigns the address of person to addrbptr' +o access the elements Bsing a pointer Ce need a neC operator called the arroC operatorI WI Chich can De Bsed on86 Cith strBctBre pointers' For eEample pBts= addrbptr W name > U For -Eample Q 2rogram Bsing a strBctBre to store time valBes' ?inclBde [stdio'hW strBct timebvar L int hoBrsI minBtesI seconds U MU void display = const strBct timebvar @ > U void main=> L strBct timebvar time U time'hoBrs X !% U time'minBtes X $ U time'seconds X $ U display= :time > U M void display= const strBct timebvar @t > L printf= FR%dQR%dUR%dNnFI t W hoBrsI t W minBtesI t W seconds > U M *ote that even thoBgh Ce are not changing any valBes in the strBctBre variaDle Ce still employ call Dy reference for speed and efficiency' +o clarify this sitBation the const keyCord has Deen employed'

#@ note strBctBre pointer and const @#

&ynamic allocation of structures


+he memory allocation fBnctions may also De Bsed to allocate memory for Bser defined types sBch as strBctBres' All malloc=> Dasically needs to knoC is hoC mBch memory to reserve' 96

For -Eample Q strBct coordinate L int EI yI P U MU strBct coordinate @ptr U ptr X =strBct coordinate @ > malloc= siPeof = strBct coordinate > > U

$!# Bi3AA+i78d5
5it fields are Dased directly on strBctBres Cith the additional featBre of alloCing the programmer to specify the siPe of each of the elements in Dits to keep storage reJBirements at a minimBm' ,oCever Dit field elements are restricted to De of type int = signed or Bnsigned >' For -Eample Q strBct clock L Bnsigned hoBr Q 3 U Bnsigned minBtes Q 6 U Bnsigned seconds Q 6 U M time U +his time strBctBre reJBires !8 Dits to store the information noC so the storage reJBirement is roBnded Bp to " Dytes' Using the normal strBctBre format and "% Dit integer elements Ce CoBld reJBire !% Dytes so Ce achieve a sBDstantial saving' 5it fields can De Bsed instead of the DitCise operators in system level programmingI for eEample to analyse the individBal Dits of valBes read from a hardCare port Ce might define the folloCing Dit field' strBct statBs L Bnsigned Dit$ Q ! U Bnsigned Dit! Q ! U ''' Bnsigned Dit!3 Q ! U MU (f Ce are interested in Dit !3 only Ce need only do the folloCing strBct statBs L Bnsigned Q !3 U Bnsigned Dit!3 Q ! U MU #@ skip over first !3 Dits Cith a Fnon memDerF @#

+here are tCo fBrther restrictions on the Bse of Dit fields Cannot take the address of a Dit field variaDle Cannot create an array of Dit field variaDles Can yoB sBggest reasons for this ^

$!) Union5
A Bnion is data type Chere the data area is shared Dy tCo or more memDers generally of different type at different times' For -Eample Q 98

union uO3ag Q 5=or3 i9a8 H 48oa3 49a8 H c=ar c9a8 H R u9a8 H +he siPe of Bval Cill De the siPe reJBired to store the largest single memDerI & Dytes in this case to accommodate the floating point memDer' Union memDers are accessed in the same Cay as strBctBre memDers and Bnion pointers are valid' Bval'ival X !$ U Bval'cval X GcG U 0hen the Bnion is accessed as a character Ce are only Bsing the Dottom Dyte of storageI Chen it is accessed as a short integer the Dottom tCo Dytes etc' (t is Bp to the programmer to ensBre that the element accessed contains a meaningfBl valBe' A Bnion might De Bsed in conKBnction Cith the Dit field struct status in the previoBs section to implement Dinary conversions in C' For -Eample Q Bnion conversion L Bnsigned short nBm U strBct statBs Dits U M nBmDer U 0e can load nBmDer Cith an integer scanf= FRBFI :nBmDer'nBm >U 6ince the integer and Dit field elements of the Bnion share the same storage if Ce noC access the Bnion as the Dit field variaDle bits Ce can interpret the Dinary representation of nBm directly' i'e' if = Bvar'Dits'Dit!3 > pBtchar= G!G > U else pBtchar=G$G> U ''' if = Bvar'Dits'Dit$ > pBtchar= G!G > U else pBtchar=G$G> U

Admittedly rather inefficient and inelegant DBt effective'

$!" Enum7ra3ion5
99

An enBmeration is a Bser defined data type Chose valBes consist of a set of named integer constantsI and are Bsed for the sole pBrpose of making program code more readaDle' ynta!" 7num 3ag Q 9a8u7O8i53 R C 7numO9ar E H

Chere tag is the name of the enBmeration typeI valBeblist is a list of valid valBes for the enBmerationI and Chere enBmbvar is an actBal variaDle of this type' For -Eample Q enBm coloBrs L redI greenI DlBeI orange M shade U ## valBes red $I green !I DlBe %I orange " enBm day L sBn X !I monI tBeI Ced X %!I thBrI friI sat M U enBm day Ceekday U ## valBes are !I %I "I %!I %%I %"I %& 4ariaDles declared as enBmerated types are treated eEactly as normal variaDles in Bse and are converted to integers in any eEpressions in Chich they are Bsed' For -Eample Q int i U shade X red U i X shade U shade X " U ## assign a valBe to shade enBm variaDle ## assign valBe of enBm to an int ## assign 9a8id int to an enBmI treat Cith care

$!, T=7 36<7d74 S76Dord


C makes Bse of the 36<7d74 keyCord to alloC neC data type nam75 to De defined' *o neC type is createdI an eEisting type Cill noC simply De recognised Dy another name as Cell' +he eEisting type can De one of the in DBilt types or a Bser defined type' ynta! " 36<7d74 36<7 nam7 H

Chere type is any C data type and name is the neC name for this type' For -Eample Q typedef int (*+-)-R U (*+-)-R i U typedef doBDle @ doBDlebptr U doBDlebptr ptr U ## can noC declare a variaDle of type T(*+-)-RO ## no need of @ here as it is part of the type

typedef strBct coords L int EI y U M Eycoord U ## Eycoord is noC a type name in C Eycoord coordbvar U +he Bse of typedef makes program code easier to read and Chen Bsed intelligently can facilitate the porting of code to a different platform and the modification of code' For eEample in a first attempt at a particBlar program Ce might decide that floating point variaDles Cill fill oBr needs' At a later date Ce decide that all floating point variaDles really shoBld De of type doBDle so Ce have to change them all' +his proDlem is trivial if Ce had Bsed a typedef as folloCs Q typedef float F/OA+(*) U 9<

+o remedy the sitBation Ce modify the Bser defined type as folloCs typedef doBDle F/OA+(*) U

$!/ &inT7d &i535


0hen Ce have needed to represent collections of data Bp Bntil noC Ce have typically Bsed data strBctBres sBch as arrays Chose dimensions Cere fiEed at compile time or Chich Cere dynamically allocated as reJBired' +hese arrays coBld have Deen arrays of Dasic data typesI e'g' doBDlesI or coBld have Deen arrays of strBctBres Chen more compleE data needed to De represented' ,oCever this method of representing dataI Chile perfectly adeJBate in many sitBationsI is limited and can De very inefficient Chen Ce are dealing Cith sitBations Chere the data collection has to De modified at rBn time' For eEample if Ce are dealing Cith an ordered list of records and Ce need to insert a neC recordI for dohn sayI in the correct position in the list Ce might have to go throBgh the folloCing steps' !' -Epand the memory space allocated to the array to take one more record' Alan 5en 6am +om

%' Determine the correct position in the array at Chich to insert the element e position "' "' Reposition the data so that the appropriate position is left BnBsed' Alan 5en 6am +om

&' (nsert the neC element into the list' Alan 5en dohn 6am +om

0hatever oBr internal representation of the dataI steps !I% : & Cill have to De carried oBt in one form or another' ,oCever step " can De avoided if Ce represent the data in an alternate fashion' (f Ce can represent oBr data as a chain of inter connected records as illBstrated DeloC Chere each record has its oCn memory space and knoCs Chich record comes Defore and after it Ce have a mBch more fleEiDle strBctBre'

<$

$ohn

'ew Lin%s

Alan

#en

Sam

Tom

#rea% Existin& Lin%

*oC Chen Ce Cant to insert a neC record in position Ce still mBst allocate the appropriate amoBnt of memory to store it =note in this case it is a discrete Dlock> and Ce still mBst figBre oBt Chich position it Delongs in DBt Ce no longer have to manipBlate the position of the other records in memory' +hese Cill noC stay eEactly Chere they are DBt Ce Cill have to inform the records Defore and after the position at Chich Ce Cish to insert that they Cill De pointing to a different record' Using the normal terminology Ce say Ce have a list of nodes linked together Dy pointer links' +o insert a neC item into the list Ce Dreak an eEisting link and create tCo neC links incorporating the neC node into the list'

Nodes or elf#'eferential tructures


A strBctBre that contains a pointer memDer that points to a strBctBre of the same type as itself is said to De a self referential strBctBre' For eEample Q strBct node L char name\%$] U strBct node @neEtnode U MU +his defines a neC typeI 53ruc3 nod7I Chich has a pointer memDerI ne#tnode, Chich points to a strBctBre of the same type as itself' +his node pointer alloCs this cBrrent node to De linked to another and so a list of linked nodes can De DBilt Bp' *ote that even thoBgh the strBctBre is not fBlly defined Chen the ne#tnode field is specified the compiler does not have a proDlem as all it needs to knoC is that there is sBch a type' +he aDove definition of strBct node alloCs Bs to DBild a singly linked list i'e' each node only knoCs Chere the node folloCing it is located' A nBll pointer is Bsed to indicate the end of a linked list strBctBre' +he diagram DeloC illBstrates hoC this node strBctBre CoBld De Bsed to represent oBr linked list aDove' -ach node contains tCo fields the actBal data and a pointer link to the neEt node' +he final node in the list contains a nBll pointer link as indicated Dy the slash in the diagram'

Alan

#en

Sam

Tom

Connecting the Nodes


<!

+he Dasic DBilding Dlock in a linked list is KBst a C strBctBre so Ce can initialise it in the same Cay as any other strBctBre' For eEample in oBr aDove sitBation to allocate and initialise the first node Ce might do the folloCing Q strBct node @nodeb! U nodeb! X = strBct node @>malloc= siPeof = strBct node > > U strcpy= nodeb! WnameI .Alan1 > U nodeb! WneEtnode X *U// U +his Dlock of code initialises this node only and DecaBse the ne#tnode pointer is assigned a nBll pointer valBe it designates it as the final =and only> node in the list' (f Ce Cant to add on an item to the list Ce can do the folloCing Q strBct node @nodeb% U nodeb% X = strBct node @>malloc= siPeof = strBct node > > U strcpy= nodeb% WnameI .5en1 > U nodeb% WneEtnode X *U// U nodeb! WneEtnode X nodeb% U *ote that it is only the last line of code that adds the item onto the list' +he remaining code KBst allocates storage and initialises a neC node as Defore' 0e noC have a linked list Cith tCo nodes' +he node pointer node$( points to the first element in the list Chich is normally called the list =7ad' As all the nodes in the list are connected via their link pointer this is in fact a pointer to the complete linked list so Ce CoBldnOt need to store nodeb%I etc' at all' +he last node has a nBll pointer Chich identifies it as the last node in the linked list and is called the list 3ai8'

%perations on (in/ed (ists


0hen Corking Cith linked lists Ce Cill need to perform a nBmDer of operations JBite often so it makes sense to DBild Bp a liDrary of these at the oBtset' 0e Cill need to De aDle to insert items into the listI remove items from the listI traverse the listI etc' 0e Cill continBe to Bse oBr definition of a node eEcept that Ce Cill typedef it as folloCs Q typedef strBct node L char name\%$] U strBct node @neEtnode U M listbnode U *ote in this case Ce cannot Bse the typedef name to declare neEtnode as this name is not in eEistence at that point' +o declare the linked list Ce simply declare a pointer to one of these strBctBre types' listbnode @ptrbhead X *U// U Tra,ersing a (ist (n many list operations Ce Cill need to process the information in each nodeI for eEample to print the complete information in the listU this is termed tra!ersing a list. An iterative version of a print$list fBnction might De as folloCs Q <%

void printblist= listbnode @pbhead > L listbnode @nodebptr U for = nodebptr X pbhead U nodebptr SX *U// U nodebptr X nodebptr WneEtnode > pBts= nodebptr Wname > U M Chereas a recBrsive version might De implemented as folloCs Q void printblist= listbnode @pbhead > L if = pbhead XX *U// > pBts=.Nn1 >U else L pBts= pbhead Wname > U printblist= pbhead WneEtnode > U M M Inserting a Node +here are a variety of Cays this fBnction can De implemented inserting a node in the correct orderI at the headI at the tailI Dy positionI etc' For oBr eEample Ce Cill Crite a fBnction to insert a neC node in the correct order assBming the node has Deen fBlly created Defore Deing passed to Bs' void insert= listbnode @@pbheadI listbnode @neC > L listbnode @nodebptr X @pbhead U listbnode @prev X *U// U Chile = nodebptr SX *U// :: =strcmp= neC WnameI nodebptr Wname > W $ > > L prev X nodebptr U nodebptr X nodebptr WneEtnode U M if = prev XX *U// > ## head position L neC WneEtnode X @pbhead U @pbhead X neC U M else L prev WneEtnode X neC U neC WneEtnode X nodebptr U M M 'emo,ing a Node 0e Cill implement this as a fBnction Chich finds the node Dy the name fieldI Bnlinks it from the list and retBrns a pointer to the removed node CithoBt freeing its associated memory' listbnode @delete= listbnode @@pbheadI char @name > L listbnode @prev X *U//I @cBrrI @nodebptr X @pbhead U Chile = nodebptr SX *U// :: strcmp= nameI nodebptr Wname > > L <"

prev X nodebptr U nodebptr X nodebptr WneEtnode U M if = prev XX *U// > ## removing head position L @pbhead X =@pbhead> WneEtnode U retBrn nodebptr U M else L prev WneEtnode X nodebptr WneEtnode U retBrn nodebptr U M M *ote the Bse of doBDle indirection to type list$node in each of the aDove fBnctions' Can yoB eEplain Chy this is necessary ^ +he folloCing main fBnction is a trivial illBstration of hoC to Bse the aDove fBnctions in practice' void main() { list=node *ptr=head 1 V>?? ' struct node *node=0/ *node=3 ' node=0 1 ( struct node *)malloc( siGeo strcp+( node=08>name/ #Ulan# ) ' insert( Eptr=head/ node=0 ) ' node=3 1 ( struct node *)malloc( siGeo strcp+( node=38>name/ #\en# ) ' insert( Eptr=head/ node=3) ' puts( )?ist with Ulan E \en,) ' print=list( ptr=head ) ' delete( Eptr=head/ #\en# ) ' puts( )?ist with Ulan,) ' print=list( ptr=head ) ' ( 0hat Ce have discBssed in the eEample aDove is one of the more general variations of a linked list' Many different implementations can De implemented Cith slightly different fBnctionality for eEample Ce can implement doBDly linked listsI stacks =/(FO> or JBeBes =F(FO> Bsing the same Dasic DBilding Dlocks' ( struct node ) ) '

( struct node ) ) '

<&

$!$ E44ici7nc6 Con5id7ra3ion5


As descriDed previoBsly pointers shoBld De Bsed to implement call Dy reference in passing large Bser defined data items to fBnctions to redBce the copying overhead involved in call Dy valBe' (f implementing a typical call Dy valBe sitBation Bse of the const keyCord can protect Bs from inadvertent modification of the referenced argBment' Care shoBld De taken not to go overDoard in defining large complicated data strBctBres CithoBt need and to Bse them appropriately' For eEample Chen dealing Cith lists of data of any type a normal array may sometimes De a Detter choice as a data strBctBre rather than a linked list' +he Dig advantage a linked list has over a linear array is that yoB can insert or delete items at Cill CithoBt shifting the remaining data' ,oCever the eEtra overhead involved in setting Bp the linked listI Doth the calls to malloc=> to allocate each neC element and the TeEtraO pointer associated Cith each elementI may not KBstify its selection' 6Bppose Ce need to keep a list of integers' +hen most of the storage is taken Bp Cith the eEtra pointer information Bsed solely for maintaining the list = the pointer to the neEt element and the pointer to each integer >'

<3

$!* E;7rci575
! 0rite a program Chich Cill simBlate the action of a digital clock continBoBsly as closely as possiDle' Use a strBctBre to hold the valBes of hoBrsI minBtes and seconds reJBired' 7oBr program shoBld inclBde a fBnction to display the cBrrent time and to Bpdate the time appropriately Bsing a delay fBnction#loop to simBlate real time reasonaDly Cell' 2ointers to the clock strBctBre shoBld De passed to the display and Bpdate fBnctions rather than Bsing gloDal variaDles' #! CompleE nBmDers are not sBpported as a distinct type in C DBt are BsBally implemented Dy individBal Bsers as Bser defined strBctBres Cith a set of fBnctions representing the operations possiDle on them' Define a data type for compleE valBes and provide fBnctions to sBpport additionI sBDtractionI mBltiplication and division of these nBmDers' Use call Dy reference to make these fBnctions as efficient as possiDle and try to make their Bse as intBitive as yoB can' )! 0rite a program Chich Cill =a> set Bp an array of strBctBres Chich Cill hold the namesI dates of DirthI and addresses of a nBmDer of employees' =D> assign valBes to the strBctBre from the keyDoard' =c> sort the strBctBres into alphaDetical order Dy name Bsing a simple DBDDle sort algorithm' =d> print oBt the contents of a specific array element on demand' "! Use a comDination of Dit fields and Bnions in C to print oBt the Dit patterns of any Bnsigned integer valBes inpBt at the keyDoard' ,! 5CD =5inary Coded Decimal> codes are commonly Bsed in indBstrial applications to represent decimal nBmDers' ,ere foBr Dits are Bsed to represent each decimal digit I e'g' 5555 5550 ... 0550 11> 11> 11> 5 0 @

+hBs short int can De Bsed to represent a foBr digit decimal nBmDer' Use 5it Fields to implement conversion roBtines to encode a decimal nBmDer into 5CD format and Dack again' /! Redo proDlem ! Bsing a Dit field strBctBre as an illBstration of hoC memory reJBirements may De redBced' Compare the old and neC memory reJBirements for data storage' $! Using a doBDly linked list data strBctBre Crite a program that maintains an alphaDetically ordered list of stBdent registration records' +he information held in each record shoBld inclBde the stBdentOs nameI stBdent identity nBmDerI addressI coBrseI etc' 7oBr program shoBld alloC the Bser to add on records to the listI to remove records from the listI to amend records and to prodBce a screen dBmp of all records' Use distinct fBnctions for all maKor operations if possiDle' *! Use a F(FO implementation of a linked list to represent a JBeBe of people entered Dy the Bser'

<6

Chapter 9

S3andard +i87 I(O


+he C standard liDrary (#O fBnctions alloC yoB to read and Crite data to Doth files and devices' +here are no predefined file strBctBres in CI all data Deing treated as a seJBence of Dytes' +hese (#O fBnctions may De Droken into tCo different categories Q stream (#O and loC level (#O' +he stream (#O fBnctions treat a data file as a stream of individBal characters' +he appropriate stream fBnction can provide DBfferedI formatted or Bnformatted inpBt and oBtpBt of dataI ranging from single characters to complicated strBctBres' 5Bffering streamlines the (#O process Dy providing temporary storage for data Chich takes aCay the DBrden from the system of Criting each item of data directly and instead alloCs the DBffer to fill Defore caBsing the data to De Critten' +he loC level (#O system on the other hand does not perform any DBffering or formatting of data instead it makes direct Bse of the systemGs (#O capaDilities to transfer BsBally large Dlocks of information'

*! S3r7am I(O
+he C (#O system provides a consistent interface to the programmer independent of the actBal device Deing accessed' +his interface is termed a 53r7am in C and the actBal device is termed a 4i87' A device may De a disk or tape driveI the screenI printer portI etc' DBt this does not Dother the programmer DecaBse the stream interface is designed to De largely device independent' All (#O throBgh the keyDoard and screen that Ce have seen so far is in fact done throBgh special standard streams called 53din and 53dou3 for inpBt and oBtpBt respectively' 6o in essence the console fBnctions that Ce have Bsed so far sBch as printf=>I etc' are special case versions of the file fBnctions Ce Cill noC discBss' +here are tCo types of streams Q teEt and Dinary' +hese streams are Dasically the same in that all types of data can De transferred throBgh them hoCever there is one important difference DetCeen them as Ce Cill see'

Te!t treams
A teEt stream is simply a seJBence of characters' ,oCever the characters in the stream are open to translation or interpretation Dy the host environment' For eEample the neCline characterI GNnGI Cill normally De converted into a carriage retBrn#linefeed pair and Ya Cill De interpreted as -OF' +hBs the nBmDer of characters sent may not eJBal the nBmDer of characters received'

Binary treams
A Dinary stream is a seJBence of data comprised of Dytes that Cill not De interfered Cith so that a one to one relationship is maintained DetCeen data sent and data received'

<8

Common 5ile 5unctions


open() close() putc()E putc() "etc()E "etc() print ()E scan "ets() E puts() seek() eo () open a stream close a stream Crite a character to a stream read a character from a stream formatted (#O string handling position the file pointer at a particBlar Dyte tests if -OF

%pening and Closing 5iles


A stream is associated Cith a specific file Dy performing an open operation' Once a file is opened information may De eEchanged DetCeen it and yoBr program' -ach file that is opened has a BniJBe file control strBctBre of type F(/- = Chich is defined in [stdio'hW along Cith the prototypes for all (#O fBnctions and constants sBch as -OF = !> >' A 4i87 <oin37r is a pointer to this F(/- strBctBre Chich identifies a specific file and defines varioBs things aDoBt the file inclBding its nameI read#Crite statBsI and cBrrent position' A file pointer variaDle is defined as folloCs XS?< * ptr '

+he fopen=> fBnction opens a stream for Bse and links a file Cith that stream retBrning a valid file pointer Chich is positioned correctly Cithin the file if all is correct' fopen=> has the folloCing prototype XS?< * open( const char * ilename/ const char *mode )' Chere filename is a pointer to a string of characters Chich make Bp the name and path of the reJBired fileI and mode is a pointer to a string Chich specifies hoC the file is to De opened' +he folloCing taDle lists some valBes for mode' r C a rD CD aD rH CH aH rDH CDH aDH opens a teEt file for reading =mBst eEist> opens a teEt file for Criting =overCritten or created> append to a teEt file opens a Dinary file for reading opens a Dinary file for Criting appends to a Dinary file opens a teEt file for read#Crite =mBst eEist> opens a teEt file for read#Crite append a teEt file for read#Crite opens a Dinary file for read#Crite opens a Dinary file for read#Crite append a Dinary file for read#Crite

(f open( ) cannot open Ftest.dat F it Cill a retBrn a *U// pointer Chich shoBld alCays De tested for as folloCs' XS?< * p ' i ( ( p 1 open( #test.dat#/ #r# ) ) 11 V>?? ) { puts( #Cannot open ile#) ' e!it( 0) ' ( +his Cill caBse the program to De eEited immediately if the file cannot De opened' +he close() fBnction is Bsed to disassociate a file from a stream and free the stream for Bse again' <9

close(

p ) '

close() Cill aBtomatically flBsh any data remaining in the data DBffers to the file'

'eading * Writing Characters


Once a file pointer has Deen linked to a file Ce can Crite characters to it Bsing the fBnction' putc( ch/ p ) ' putc()

(f sBccessfBl the fBnction retBrns the character Critten otherCise -OF' Characters may De read from a file Bsing the fgetc=> standard liDrary fBnction' ch 1 "etc( p ) '

0hen -OF is reached in the file "etc( ) retBrns the -OF character Chich informs Bs to stop reading as there is nothing more left in the file' For -Eample Q 2rogram to copy a file Dyte Dy Dyte #include <stdio.h> void main() { XS?< * in/ * out ' char dest]45^/ source]45^/ ch ' puts( "ets( puts( "ets( #<nter source #<nter dest ) source ile name# )' )' destination ile name# )' ' //

i ( ( in 1 open( source/ #rb# ) ) 11 V>?? ) open as binar+ as we donPt {// know what is in ile puts( #Cannot open input ile #) ' puts( source ) ' e!it( 0 ) ' ( i ( ( out 1 open( dest/ #wb# ) ) 11 V>?? ) { puts( #Cannot open output ile #) ' puts( dest ) ' e!it( 0 ) ' ( H1 <DX )

while ( ( ch 1 "etc( in ) ) putc( ch / out ) ' close( close( in ) ' out ) '

( NB 1 0hen any stream (#O fBnction sBch as fgetc=> is called the cBrrent position of the file pointer is aBtomatically moved on Dy the appropriate amoBntI ! character# Dyte in the case of fgetc=> U <<

Wor/ing )ith strings of te!t


+his is JBite similar to Corking Cith characters eEcept that Ce Bse the fBnctions puts() Chose prototypes are as folloCs Q int puts( const char *str/ XS?< * p ) ' char * "ets( char *str/ int ma!len/ XS?< * p ) ' For -Eample Q 2rogram to read lines of teEt from the keyDoardI Crite them to a file and then read them Dack again' #include <stdio.h> void main() { char ile]F5^/ strin"]F5^ ' XS?< * p ' print ( #<nter "ets( ile )' i writin" (( p 1 ile Vame * # )' open( ile/ #w# )) 11 V>?? )//open or "ets() and

{ print ( #Cannot open e!it( 0 ) ' (

ile As#/

ile ) '

while ( strlen ( "ets( str ) ) > 5 ) { puts( str/ p ) ' putc( 2&n2/ p ) ' /* must readabilit+ 88 not stored b+ "ets() */ ( close( i readin" (( p ) ' p 1 open( ile/ #r# )) 11

append

&n

or

V>??

)//open

or

{ print ( #Cannot open e!it( 0 ) ' ( while ( "ets( str/ 7@/ characters puts( str ) ' close( ( p ) '

ile As#/

ile ) '

ptr )

H1 <DX )// read at most 7@

!$$

5ormatted I6%
For -Eample Q 2rogram to read in a string and an integer from the keyDoardI Crite them to a disk file and then read and display the file contents on screen' #include <stdio.h> #include <stdlib.h> void main() { XS?< * p ' char s]F5^ ' int t ' i ( ( p 1 open( #test.dat#/ #w# ) ) 11 V>?? ) { puts( #Cannot open ile test.dat#) ' e!it(0) ' (

puts( #<nter a strin" and a number#) ' scan ( #As Ad#/ s/ Et )' print ( p/ #As Ad#/ s/ t )' close( p ) ' i ( ( p 1 open( #test.dat#/ #r# ) ) 11 V>?? ) { puts) #Cannot open ile#) ' e!it(0) ' (

scan ( p/ #As Ad# / s / Et ) ' print ( #As/ Ad&n#/ s/ t ) ' close( ( No37 1 +here are several (#O streams opened aBtomatically at the start of every C program' stdin stdout stderr standard inpBt ie' keyDoard standard oBtpBt ie' screen again the screen for Bse if stdoBt malfBnctions p ) '

(t is throBgh these streams that the console fBnctions Ce normally Bse operate' For eEample in reality a normal printf call sBch as print ( #As Ad#/ s/ t ) ' is in fact interpreted as print ( stdout/ #As Ad#/ s/ t ) '

fread() and f)rite()


!$!

+hese tCo fBnctions are Bsed to read and Crite Dlocks of data of any type' +heir prototypes are as folloCs Chere siPebt is eJBivalent to Bnsigned' siGe=t read( void *bu er/ siGe=t num=b+tes/ siGe=t count/ XS?< * p ) ' siGe=t write( const void *bu er/ siGe=t num=b+tes/ siGe=t count/ XS?< * p ) ' Chere :u447r is a pointer to the region in memory from Chich the data is to De read or Critten respectivelyI numO:6375 is the nBmDer of Dytes in each item to De read or CrittenI and coun3 is the total nBmDer of items = each nBmbDytes long > to De read#Critten' +he fBnctions retBrn the nBmDer of items sBccessfBlly read or Critten' For -Eample Q #include <stdio.h> #include <stdlib.h> struct ta" { loat balance ' char name] F5 ^ ' ( customer 1 { 034.343/ #`ohn# ( ' void main() { XS?< * p ' double d 1 03.4: ' int i]:^ 1 {05 / 35/ 45/ :5 ( ' i ( ( p 1 open ( #test.dat#/ #wbB# ) ) 11 V>?? ) { puts( #Cannot open Xile# ) ' e!it(0) ' ( write( Ed/ siGeo ( double )/ 0/ p ) ' write( i/ siGeo ( int )/ :/ p ) ' write( Ecustomer/ siGeo ( struct ta" )/ 0/ rewind( p ) ' /* repositions

p ) '

ile pointer to start */

read( Ed/ siGeo ( double )/ 0/ p ) ' read( i/ siGeo ( int )/ :/ p ) ' read( Ecustomer/ siGeo ( struct ta" )/ 0/ close( ( p ) '

p ) '

NB 1 Unlike all the other fBnctions Ce have encoBntered so far fread and fCrite read and Crite :inar6 data in the same format as it is stored in memory so if Ce try to edit one these files it Cill appear completely garDled' FBnctions like fprintfI fgetsI etc' read and Crite displayaDle data' fprintf Cill Crite a doBDle as a series of digits Chile fCrite Cill transfer the contents of the 9 Dytes of memory Chere the doBDle is stored directly'

'andom $ccess I6%

!$%

+he seek() fBnction is Bsed in C to perform random access (#O and has the folloCing prototype' int seek ( XS?< * p/ lon" num=b+tes/ int ori"in ) '

Chere origin specifies one of the folloCing positions as the origin in the operation 6--Ab6-+ 6--AbCUR 6--Ab-*D Deginning of file cBrrent position -OF

and Chere numO:6375 is the offset in Dytes to the reJBired position in the file' fseek=> retBrns Pero Chen sBccessfBlI otherCise a non Pero valBe' For -Eample if Ce had opened a file Chich stored an array of integers and Ce Cish to read the 3$th valBe Ce might do the folloCing seek ( scan ( p/ ( :@ * siGeo ( int ) )/ M<<T=M<T ) ' p/ #Ad#/ Ei ) '

from anyChere in the program'

*!# &oD AA &7978 I(O


/oC level file inpBt and oBtpBt in C does not perform any formatting or DBffering of data ChatsoeverI transferring Dlocks of anonymoBs data instead Dy making Bse of the Bnderlying operating systemGs capaDilities' /oC level (#O makes Bse of a file handle or descriptorI Chich is KBst a non negative integerI to BniJBely identify a file instead of Bsing a pointer to the F(/- strBctBre as in the case of stream (#O' As in the case of stream (#O a nBmDer of standard files are opened aBtomatically Q 53andard in<u3 AAA 53andard ou3<u3 AAA 53andard 7rror AAA 2 #

+he folloCing taDle lists some of the more common loC level (#O fBnctionsI Chose prototypes are given in [io'hW and some associated constants are contained in [fcntl'hW and [sysNstat'hW' open=> close=> read=> Crite=> opens a disk file closes a disk file reads a DBffer of data from disk Crites a DBffer of data to disk

+he open fBnction has the folloCing prototype and retBrns ! if the open operation fails' int open ( char * ilename/ int o la" ]/ int pmode^ ) ' Chere filename is the name of the file to De openedI oflag specifies the type of operations that are to De alloCed on the fileI and pmode specifies hoC a file is to De created if it does not eEist' o48ag may De any logical comDination of the folloCing constants Chich are KBst bit flags comDined Bsing the DitCise OR operator' !$"

ObA22-*D Ob5(*AR7 ObCR-A+ ObRDO*/7 ObRD0R Ob+-;+ Ob+RU*C Ob0RO*/7

appends to end of file Dinary mode creates a neC file if it doesnGt eEist read only access read Crite access teEt mode trBncates file to Pero length Crite only access

<mod7 is only Bsed Chen ObCR-A+ is specified as part of oflag and may De one of the folloCing valBes SOI?RITE SOIREAD SOIREAD U SOI?RITE +his Cill actBally set the read # Crite access permission of the file at the operating system level permanently Bnlike oflag Chich specifies read # Crite access KBst Chile yoBr program Bses the file' +he close() fBnction has the folloCing prototype int close ( int handle ) ' and closes the file associated Cith the specific handle' +he read() and write() fBnctions have the folloCing prototypes int read( int handle/ void *bu er/ unsi"ned int count ) ' int write( int handle/ void *bu er/ unsi"ned int count ) ' Chere handle refers to a specific file opened Cith open=>I DBffer is the storage location for the data = of any type > and coBnt is the maEimBm nBmDer of Dytes to De read in the case of read=> or the maEimBm nBmDer of Dytes Critten in the case of Crite=>' +he fBnction retBrns the nBmDer of Dytes actBally read or Critten or ! if an error occBrred dBring the operation' -Eample Q 2rogram to read the first !$$$ characters from a file and copy them to another' #include <io.h> #include < cntl.h> #include <s+s&stat.h> void main() { char bu ]0555^ ' int handle ' handle1open(# test.dat#/ D=\SVUYQJD=YLDV?Q/ M=S%YST< )' i ( handle 11 80 ) return ' i ( read( handle/ bu / 0555 ) 11 0555 ) puts( #Yead success ul#)' else { puts( Yead ailed# ) ' e!it( 0 )' ( !$& M=SY<UL J

close( handle ) ' handle 1 open(#test.bak#/ D=\SVUYQJD=CY<UTJD=%YDV?QJ D=TY>VC/ M=SY<UL J M=S%YST< ) ' i ( write( handle/ bu / 0555 ) puts( #%rite success ul#) ' else { puts( #%rite Xailed#) ' e!it( 0 ) ' ( close( handle ) ' ( /oC level file (#O also provides a seek fBnction 8577T Cith the folloCing prototype' lon" =lseek( int handle / lon" offset / int origin )' O8577T Bses the same origin etc' as fseek() DBt Bnlike fseek=> retBrns the offsetI in DytesI of the neC file position from the Deginning of the file or ! if an error occBrs' For -Eample Q 2rogram to determine the siPe in Dytes of a file' #include #include #include #include <stdio.h> <io.h> < cntl.h> <s+s&stat.h> 11 0555 )

void main() { int handle ' lon" len"th ' char name]F5^ ' print ( )<nter "ets( name ) ' handle1open( M=S%YST< )' ile name * , ) ' name/D=\SVUYQJ D=YLDV?Q/ M=SY<UL J

lseek( handle/ 5?/ M<<T=M<T ) ' len"th 1 lseek( handle/ 5?/ M<<T=<VL ) ' close( handle ) ' print ( )The len"th o ' ( As is Ald b+tes &n,/ name/ len"th )

*!) E;7rci575
! 0rite a program that determines the folloCing statistics pertaining to a teEt file' i' +otal nBmDer of characters ii' *BmDer of alphaDetic characters iii' *BmDer of Cords !$3

iv' *BmDer of non alphaDetic characters v' +aDBlates the Bsage of each letter of the alphaDet' #! 0rite a program that compBtes the valBe of 6in= E > for E in the range $ to % in steps of $'$! radians and stores them in a Dinary file' +his look Bp taDle is commonly Bsed to improve program performance in practical programming rather than calcBlating valBes on the spot' Using the standard liDrary random nBmDer generator to generate the angles compare the time it takes to TcalcBlateO 6in=E> for !$$ valBes of E Bsing the look Bp taDle and calcBlating them straight' 7oB might find the standard liDrary time fBnctions BsefBl to compare times accBrately' )! Programming A55ignm7n3 1 Sim<87 Da3aBa57! 0rite a simple dataDase program Chich stores and manages information of the type contained in the folloCing strBctBre Dy making Bse of a dynamically allocated array # list of strBctBres of this type as descriDed DeloC' t+pede struct details { int rec=id ' char name]35^ ' char address]F5^ ' lon" >CCid ' ( L<TUS?M ' struct list { L<TUS?M **data=items ' int numrecords ' int selrecord ' ( ?SMT '

t+pede

+he list strBctBre defined aDove contains three data items' [nBmrecordsW is the total nBmDer of records in the list at presentI [selrecordW is the cBrrent record selectedI and [databitemsW is a pointer to a pointer to type D-+A(/6I i'e' a doBDly indirected pointer to the actBal data' +he data is arranged as illBstrated DeloC in the case of a list Cith tCo records'

!$6

+he list strBctBre tells Bs that there are tCo records in the listI the cBrrent Deing the first in the list' +he pointer mylist WdatabitemsI of type D-+A(/6 @@I has Deen allocated memory to store tCo addressesI of type D-+A(/6 @I i'e' the addresses for each individBal record' -ach of these individBal pointersI i'e' @=mylist Wdatabitems H i>I has Deen allocated sBfficient memory to store an individBal record' 7oBr program shoBld set Bp a data strBctBre of the type descriDed aDove and alloC the Bser to perform the folloCing tasks' !' %' "' &' 3' 6' 8' Add a record to the dataDase' 6earch for a record Dy field in the dataDase' Order the dataDase Dy field' Retrieve a record from the dataDase' -Etract a record from the dataDaseI deleting it completely' 6ave the dataDase appropriately to a file' /oad an eEisting dataDase from a file'

7oBr program shoBld contain the folloCing fBnctions # featBres'


void initlist( ?SMT *list ) ' +his fBnction shoBld set [selrecordW X [nBmrecordsW X $ and [databitemsW X *U//' void add( ?SMT *list/ L<TUS?M *new )' +his fBnction shoBld add the record pointed to Dy [neCW onto the end of the list pointed to Dy [listW' +his means that [selrecordW and [nBmrecordsW Cill have to De modified appropriately and the pointer [list WdatabitemsW mBst De resiPed to hold the address of one eEtra record = Bsing realloc( ) for eEample >I and memory mBst De allocated for the actBal record i'e' or *( list8> data=items B list8>numrecords 8 0 ) ' L<TUS?M *probe( ?SMT *list/ int i ) ' +his fBnction retBrns a pointer to the cBrrent record and aBtomatically moves yoB onto the neEt record' (f the cBrrent selection is $I i'e' no record eEists in the listI the fBnction shoBld retBrn *U//' (f the cBrrent selection is otherCise invalid [selrecordW shoBld De reset to the first record and continBe as normal' (f [iW is eJBal to Pero the list is to De reset and continBe as normalI otherCise ignore [iW' void e!tract( ?SMT *list )' +his fBnction removes the cBrrent selection completely from the list' (t removes nothing if the cBrrent record is invalid' void swap( ?SMT *list/ int i/ int . ) ' !$8

6Caps records i and K in the list' *ote yoB shoBld only sCap the actBal addresses of the individBal records'

void orderlist( ?SMT *list/ int ield ) ' +his fBnction shoBld ideally order the complete list in terms of the field givenI e'g' in terms of nameI UCCidI etc' ,oCever it Cill sBffice to do this in terms of name only say' L<TUS?M *search( ?SMT *list/ char *item/ int ield ) ' 6earch the list from the cBrrent position onI for the neEt occBrrence of the searchitemI [itemWI in a particBlar field of the list = Cith the same proviso as aDove >' +he fBnction retBrns the nBll pointer if the item is not foBndI or a pointer to the particBlar record if it is foBnd' +he record Decomes the cBrrent selection'

A22-*D(; A Q A6C(( Character 6et

!$9

!$<

Potrebbero piacerti anche