You are on page 1of 107

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
6
th
Revision !"#$%#"$!&
CHAPTER
INTRODUCTION
!'! OR()(* OF C
!'" +,- .,-//O 0OR/D1 2RO)RAM
!'3 +,- C 2RO)RAMM(*) -*4(RO*M-*+
CHAPTER !
"ARIAB#ES, DATA T$PES, I%O AND OPERATORS
"'! 5A6(C DA+A +72-6
"'" 4AR(A5/-6
"'3 CO*6O/- (*2U+ # OU+2U+
"'& O2-RA+OR6
"'8 +72- O4-RF/O0 9 U*D-RF/O0
"'6 -:-RC(6-6
CHAPTER &
STATEMENTS
3'! -:2R-66(O*6 A*D 6+A+-M-*+6
3'" (+-RA+(O* 6+A+-M-*+6
3'3 D-C(6(O* 6+A+-M-*+6
3'& -FF(C(-*C7 CO*6(D-RA+(O*6
3'8 -:-RC(6-6
CHAPTER '
(UNCTIONS
&'! FU*C+(O* 2RO+O+72- ; D-C/ARA+(O*<
&'" FU*C+(O* D-F(*(+(O* 9 /OCA/ 4AR(A5/-6
&'3 6CO2- RU/-6
&'& R-+UR*(*) A 4A/U-
&'8 FU*C+(O* AR)UM-*+6
&'6 R-CUR6(O*
&'= >D-F(*- D(R-C+(4-
&'? -FF(C(-*C7 CO*6(D-RA+(O*6
&'% -:-RC(6-6
CHAPTER )
ARRA$S * STRINGS
8'! 6(*)/- D(M-*6(O* ARRA76
8'" 6+R(*)6
8'3 MU/+(D(M-*6(O*A/ ARRA76
8'& ARRA76 OF 6+R(*)6
8'8 ARRA76 A6 AR)UM-*+6 +O FU*C+(O*6 ; !D <
8'6 2A66(*) MU/+(D(M-*6(O*A/ ARRA76
8'= -:-RC(6-6
CHAPTER +
"
POINTERS
6'! 2O(*+-R 4AR(A5/-6
6'" 2O(*+-R O2-RA+OR6 @ A*D 9
6'3 CA// 57 R-F-R-*C-
6'& 2O(*+-R6 A*D ARRA76
6'8 2O(*+-R AR(+,M-+(C
6'6 ARRA76 OF 2O(*+-R6
6'= COMMA*D /(*- AR)UM-*+6
6'? D7*AM(C M-MOR7 A//OCA+(O*
6'% MU/+(2/- (*D(R-C+(O* 2O(*+-R6 +O 2O(*+-R6
6'!$ 2O(*+-R6 +O FU*C+(O*6
6'!! -FF(C(-*C7 CO*6(D-RA+(O*6
6'!" -:-RC(6-6
CHAPTER ,
STRUCTURES * UNIONS
='! 6+RUC+UR-6
='" 5(+F(-/D6
='3 U*(O*6
='& -*UM-RA+(O*6
='8 +,- +72-D-F A-70ORD
='6 /(*A-D /(6+6
='= -FF(C(-*C7 CO*6(D-RA+(O*6
='? -:-RC(6-6
CHAPTER -
STANDARD (I#E I%O
?'! 6+R-AM (#O
?'" /O0 /-4-/ (#O
?'3 -:-RC(6-6
APPENDI. A / ASCII CHARACTER SET
3
Chapter !
In0roduc0ion
1 Origin o2 C
+he C 2rogramming /angBage Cas initially developed Dy Denis Ritchie Bsing a UniE system in
!%="' +his Cas varied and modified Bntil a standard Cas defined Dy 5rian Aernighan and Dennis
Ritchie in !%=? in F+he C 2rogramming /angBageF'
5y the early ?$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 !%?3' (t is this standard this set of
notes primarily addresses'
Why use C ?
Indu30r4 Pr535nc5 / 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'
Midd65 #5756 / 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'
Por0a8i6i04 / 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'
(659i8i6i04 / 6Bpporting its position as the mainstream development langBage C can De interfaced
readily to other programming langBages'
Ma665a865 / 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:55d / +he availaDility of varioBs optimising compilers alloC eEtremely efficient code to De
generated aBtomatically'
&
1! T;5 <H566o =or6d> 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 semicolon'
+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'
8
+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 / C is case sensitive i'e' print() and -rint() CoBld De regarded as tCo different
fBnctions'
1& T;5 C Programming En7ironm5n0
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 1c 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 Dreakpoints and to look at the valBes of variaDles in the code in order to estaDlish
Chere errors are introdBced'
6
Chapter "
"aria8653, Da0a T4:53, I%O and O:5ra0or3
(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'
!1 Ba3ic Da0a T4:53
+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 ! Dyte ; ? Dits < Cith range !"? to !"=
in0 !6Dit O6 Q " Dytes Cith range 3"=6? to 3"=6=
3"Dit O6 Q & Dytes Cith range "I!&=I&?3I6&? to "I!&=I&?3I6&=
26oa0
& Dytes Cith range !$
3?
to !$
3?
Cith = digits of precision
dou865
? Dytes Cith range !$
3$?
to !$
3$?
Cith !8 digits of precision
7oid 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 "88I
all positiveI as opposed to a signed char Chich has a range of !"? to !"=' An unsigned integer on
a !6Dit system has a range of $ to 68838 as opposed to a signed int Chich has a range of 3"=6?
to 3"=6='
*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!&=I&?3I6&? to
"I!&=I&?3I6&=' 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'
=
NB / *ote that the keyCord int may De omitted CithoBt error so that the type unsigned is the same
as type unsigned intI the type long is eJBivalent to the type long int, and the type
short is eJBivalent to the type short int.
!1! "aria8653
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 04:5, its 7a6u5 and
its addr5331
+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 6oca6 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 g6o8a6 variaDles and are visiDle throBghoBt the
file or have file scope' +hese variaDles are created at program startBp 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 3! characters in length'
?
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 no0 ini0ia6i35d to Pero or to any
other valBe aBtomatically and so Cill contain random valBes Bnless specifically initialised Defore
Bse'
ynta! /? 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 / 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:9F '
(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"='
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' %= 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 !"? 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 neCline
Nt taD
ND Dackspace
NG single JBote
NF doBDle JBote
N$ nBll character
NEdd represent as heEadecimal constant
!1& Con3o65 In:u0 % Ou0:u0
+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 character Rf floating point
Rd signed integer Rlf doBDle floating point
Ri signed integer Re eEponential notation
RB Bnsigned integer Rs string
Rld signed long RE Bnsigned heEadecimal
RlB Bnsigned long Ro Bnsigned octal
RR prints a R sign
For -Eample Q
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 Specifers
Field Cidth specifiers are Bsed in the control string to format the nBmDers or characters oBtpBt
appropriately '
ynta! "# @A0o0a6 Bid0; :rin05dCA1d5cima6 :6ac53 :rin05dC2orma0 3:5ci2i5r
Chere sJBare Draces indicate optional argBments'
For -Eample Q
int i 1 09 '
loat 1 04.497; '
print( #A4d#/ i ) ' /* prints #=09 # where = indicates a
space
character */
print( #A;.3#/ ) ' /* prints #=04.4;# which has a total
width
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 leftKBstified 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 ) ' /* e.". t+pe #05=!=0.34:RET#
*/
scan( #Ad*Ac#/ Ei/ Ec ) ' /* e.". t+pe #05*!RET#
*/
+he 9 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 callDyvalBe' +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 / +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( #<nter two characters * # ) '
ch0 1 "etchar() '
ch3 1 "etchar() '
print( #&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 a205r 5ac; 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() '
!1' O:5ra0or3
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 left hand side of an assignment operation
rvalBe right hand side of an assignment operation
!3
+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 inormation
loss */
! 1 ' /* ! is assi"ned non ractional part o onl+
within int ran"e/ inormation 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 @ # same rBles as mathematics Cith @ and # Deing evalBated Defore H and '
R 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 ' // inte"er division/ ! 1 3.
1 c / d ' // loatin" point division/ 1 3.9.
! 1 9 A 3 ' // remainder operator/ ! 1 0.
! 1 7 B 4 * ; / 3 8 0 '// !109/* and / evaluated ahead o B and
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 ' // clariies 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 I Chich caBse the
variaDle they act on to De incremented or decremented Dy ! respectively'
!&
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 . ' /* prei! *8 i has value 4/ . has value 4 */
i 1 .BB ' /* posti! *8 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/ A1I 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
> >1 < <1 11 H1
For -Eample Q
i ( ! 11 3 )
print( )! is eCual to 3&n, ) '
(ogical %perators
99 /ogical A*D
V V /ogical OR
S /ogical *O+
For -Eample Q
i ( ! >1 5 EE ! < 05 )
print( ) ! is "reater than or eCual to Gero and less than
ten.&n, ) '
NB / +here is no 5oolean type in C so +RU- and FA/6- are deemed to have the folloCing
meanings'
FA/6- valBe Pero
+RU- any nonPero valBe DBt ! in the case of inDBilt relational operations
For -Eample Q
!8
" W ! +RU- so eEpression has valBe !
" W 3 FA/6- so eEpression has valBe $
i X " W ! U relation is +RU- has valBe !I i is assigned valBe !
NB / -very C eEpression has a valBe' +ypically Ce regard eEpressions like " H 3 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 / 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 nonPero 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 in0 argum5n03 on64' +hey alloC the programmer to
get closer to the machine level Dy operating at Ditlevel in their argBments'
9 5itCise A*D V 5itCise OR
Y 5itCise :OR Z Ones Complement
WW 6hift Right [[ 6hift left
Recall that type char is one Dyte in siPe' +his means it is made Bp of ? distinct Dits or Dinary digits
normally designated as illBstrated DeloC Cith 5it $ Deing the /east 6ignificant 5it ;/65< and 5it =
Deing the Most 6ignificant 5it ;M65<' +he valBe represented DeloC is !3 in decimal'
5it = 5it 6 5it 8 5it & 5it 3 5it " 5it ! 5it $
$ $ $ $ ! ! $ !
An integer on a !6 Dit O6 is tCo Dytes in siPe and so 5it !8 Cill De the M65 Chile on a 3" Dit
system the integer is foBr Dytes in siPe Cith 5it 3! as the M65'
Bitwise AND, &
RU#E / (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
0500 5505 (07F)
E 5500 0000 (;4)
1 5500 5505 (95)
Bitwise OR, |
RU#E / (f either Dit in corresponding positions are set the resBltant Dit in that position is set'
For -Eample Q
0500 5505 (07F)
J 5555 0555 (;4)
!6
1 0500 0505 (0F;)
Bitwise XOR, ^
RU#E / (f the Dits in corresponding positions are different then the resBltant Dit is set'
For -Eample Q
0500 5505 (07F)
K 5500 0055 (;4)
1 0555 0005 (0:3)
Shift Operators, << and >>
RU#E / +hese move all Dits in the operand left or right Dy a specified nBmDer of places'
ynta! Q variable << number of places
variable >> number of places
For -Eample Q
3 << 3 1 F
i'e'
0000 0010 Decomes 0000 1000
NB / shift left Dy one place mBltiplies Dy "
shift right Dy one place divides Dy "
Ones Complement
RU#E / Reverses the state of each Dit'
For -Eample Q
1101 0011 Decomes 0010 1100
NB / 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 = of a char variaDle'
char ch 1 F@ ' // an+ value
char mask 1 037 ' // 5000 0000
ch 1 ch E mask '// or ch E1 mask '
For -Eample Q +o set Dit ! of an integer variaDle'
int i 1 34: ' // an+ value
int mask 1 3 ' // a 0 in bit position 3
!=
i J1 mask '
Implicit * +!plicit Type Con,ersions
*ormally in miEed type eEpressions all operands are converted 05m:orari64 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/ 3 '
0 1 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
ca30 o:5ra0or 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 / (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'
!?
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 typecast 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 take up Ad b+tes on this machine,/ siGeo
( double ) ) '
!%
.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'
Pr5c5d5nc5 O:5ra0or A33ocia0i7i04
,ighest ; < \ ] W ' left to right
S Z HH H;Bnary< ;Bnary< ;type< @ 9 siPeof right to left
@ # R left to right
H left to right
[[ WW left to right
[ [X W WX left to right
XX SX left to right
9 left to right
Y left to right
V left to right
99 left to right
VV left to right
^ Q right to left
X HX X @X #X RX 9X YX VX [[X WWX right to left
/oCest I left to right
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 / 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 ! D E F ) G to De
carried oBt first Ce CoBld Crite it as H! D EI F )G
"$
!1) T4:5 O75r26oB * Und5r26oB
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 rBntime error' (f this happens yoB need to promote the
variaDles involved in the offending operation to the largest possiDle and try again'
NB / +he C standard liDrary inclBdes a nBmDer of eEception handling fBnctions to alloC yoB to
intercept these sitBations in yoBr program'
!1+ E95rci353
1 0rite a program to check the siPes of the main C data types on yoBr machine'
!1 0rite a program to illBstrate Chether the printf;< standard liDrary fBnction trBncates or roBnds
Chen printing oBt a floating point nBmDer'
&1 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 ) ) '
'1 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'
)1 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()'
+1 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 ) '

,1 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 ;;/mm/33 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 .@, J and K r5Luir5 3:5cia6 0r5a0m5n01 '
iv' Read the valBe !"3&86=?%'$!"3&8&86=?%eH8 into a floating pointI a doBDle and a long
doBDle variaDle and print all three oBt again Cith the maEimBm precision possiDle'
-1 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 '
M1 0rite a program to read Fahrenheit temperatBres and print them in CelsiBs' +he formBla is
C X ;8#%<;F 3"<' Use variaDles of type doBDle in yoBr program'
E1 0rite a program that reads in the radiBs of a circle and prints the circleOs diameterI
circBmference and area' Use the valBe 3'!&!8% for .pi1'
""
Chapter 3
S0a05m5n03
&1 E9:r533ion3 and S0a05m5n03
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 semicolon' +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 semicolon'
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 semicolon 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 semicolon' 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'
&1! I05ra0ion S0a05m5n03
"3
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" ;
ini0ia6i3a0ion Q this is BsBally an assignment to set a loop coBnter variaDle for eEample'
condi0ion Q determines Chen loop Cill terminate'
incr5m5n0 Q defines hoC the loop control variaDle Cill change each time the loop is eEecBted'
30a05m5n0 8od4 Q can De a single statementI no statement or a Dlock of statements'
+he for statement eEecBtes as folloCs Q
initialisation
test condition
statement body
increment
FALSE
continue
with next
iteration
end of statement
TRUE
NB / +he sJBare Draces aDove are to denote optional sections in the syntaE DBt are not part of the
syntaE' +he semicolons 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:5ra0or 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 semicolons mBst De
present alCays'
For -Eample Q
or ( ! 1 5' ! < 05' )
print( #Ad&n#/ !BB ) '
...
! 1 5 '
or ( ' ! < 05' !BB )
print( #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 )/ ! ) '
"8
(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
#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
statement body
FALSE
continue
with next
iteration
end of statement
TRUE
"6
! " 3 & 8
" 3 & 8 6
3 & 8 6 =
& 8 6 = ?
8 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 posti! decrement operatorH
print( )Mum is Ad &n,/ sum ) '
(
Chere it shoBld De recalled that any nonPero 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 ' // secret letter is OcP
char inish 1 O&5P '
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 buer
(
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 OP
print( )&n&nLo +ou want to continue (Q/V) W ))'
inish 1 "etchar() '
=lushall() '
(
(
do )hile
"=
+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 ;
test condition
statement body
FALSE
continue
with next
iteration
end of statement
TRUE
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 doChile 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 ' !BB )
{
i ( ! > : )
break '
print( )Ad ) / ! ) '
(
print( #Ve!t e!ecuted&n# )'//Dutput * )0 3 4 : Ve!t
<!ecuted,
'''
continue statement
"?
+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, ) ' // Dutput * )0 3 : 9 Xinished
?oop,
'''
&1& D5ci3ion S0a05m5n03
if statement
+he if statement is the most general method for alloCing conditional eEecBtion in C'
ynta! " if ( con#ition
statement bo#y ;
else
statement bo#y G
or 0ust "
if ( 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 ollows numerator/
denominator *# )'
scan( #Ad/ Ad#/ Enumerator/ Edenominator ) '
i ( 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 ( ( ch 1 "etchar() ) H1 04 ) // 04 is UMCSS value or
//carria"e return
{
i ( ch 11 2a2 )
{
count BB '
print( )&n Yetrieved letter OaP number Ad&n,/
count ) '
(
total BB '
=lushall() '
(
print( #&n&n Ad letters a t+ped in a total o Ad letters.#/
count/ total ) '
(
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 ( ! > 05 )
puts ( # ! is "reater than Gero and also "reater than 05 #)'
else
puts (#! is "reater than Gero but less than or eCual to
05#)'
+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 ( ! > 5 )
{
i ( ! > 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
3$
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 ifelseif 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 ifelse 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 ) // ininite loop until we break out o it
{
print( )&n Zake +our "uess* , ) '
scan( )Ad,/ E"uess ) '
count BB '
i ( "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 / CaBtion is advisaDle Chen coding the ifelseif ladder as it tends to De prone to error dBe to
mismatched ifelse claBses'
3!
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 mBltiDranch statement similar to the if else ladder ;Cith limitations< DBt clearer and
easier to code'
ynta! " 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 ca35 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'
3"
+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 in05g5r con30an03 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
deault * print (#<YYDY 88 Snvalid operation or division
b+ 5.5# ) '
(
print( #A Ac A 1 A&n#/ num0/ op/ num3/ result) '
( /* while statement */
(
NB / +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 <'
&1' E22ici5nc4 Con3id5ra0ion3
(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
33
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 '
1 +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'
!1 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'<
3&
+o remedy the sitBation Ce simply do the folloCing Q
avera"e 1 sum / 0555.5 '
&1 +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 6oB530 65756 ari0;m50ic 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
3
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 ) '
38
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 nBm
n
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 &%8$ 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' %? mBltiplications in total'
COs 5itCise 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, ) '
&1) E95rci353
1 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'
!1 0rite a program to keep coBnt of the occBrrence of a Bser specified character in a stream of
characters of knoCn length ; e'g' 8$ 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 68'''%$ and GaG'''GPG are %='''!""'
&1 0rite a program to find the roots of a Bser specified JBadratic eJBation'
Recall the roots of
aE DE c $
"
+ + =
are
36
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 / +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
$'!"3&86= and $'!"3&86? 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'
'1 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 nonnBmeric character etc'
)1 0rite a program to print oBt all the FiDonacci nBmDers Bsing 3;or0 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"I3I8I?I!3I'''
)1 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 HII@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'
3=
Chapter &
(unc0ion3
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 sBDtasks' (f
these sBDtasks are still too compleE they are sBDdivided fBrther into simpler sBDtasksI and so on
Bntil the sBDtasks 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 ( parameter(list
&
bo#y of function ;
'
+he aDove is termed the 2unc0ion d52ini0ion 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'
'1 (unc0ion Pro0o04:5 H d5c6ara0ionI
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'
3?
#include <stdio.h> /* standard S/D unction protot+pes */
void hello( void ) ' /* protot+pe */
void main( void )
{
hello () ' // unction call
(
void hello ( ) // unction deinition
{
print ( #$ello %orld &n# ) '
(
'1! (unc0ion D52ini0ion * #oca6 "aria8653
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'
3%
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 / +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'
'1& Sco:5 Ru653
+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 <'
'1' R50urning a "a6u5
+he r50urn 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 man+ times it was
called
return ( iBB ) ' // and passes that inormation
back to its caller
(
NB / +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 / 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'
'1) (unc0ion Argum5n03
+he types of all fBnction argBments shoBld De declared in the fBnction prototype as Cell as in the
fBnction definition'
&!
NB / (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>
int add( int/ int ) ' /* protot+pe 88 need to indicate
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 / (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'
add()
a
b
result
main()
y
x Value coied
Value coied
NB / +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 9 operator to give the address of the variaDles into Chich Ce Cant the valBes placed'
'1+ R5cur3ion
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" @ ''' @ 3 @ " @ !'
0e can simplify this operation into
nS X n @ ;n!<S
&3
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 ?S is &$3"$ Chich is too large to De held in a short so integer
overfloC Cill occBr Chen the valBe entered is greater than =' 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'
'1, Nd52in5 dir5c0i75

+his is a preprocessor command Chich is Bsed to replace any teEt Cithin a C program Cith a more
informative pseBdonym'
For -Eample Q #deine -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'
#deine <YYDY print( #&n <rror &n# )
void main( )
{
...
i ( i > 0555 )
<YYDY ' /* note must add ' in this case to make
correct IC statement */
(
Macros can also De defined so that they may take argBments'
For -Eample Q
#deine -Y( l ) print( #AF.3 #/ l )
void main()
{
loat num 1 05.34: '
-Y( num ) '
(
0hat the compiler actBally sees is Q printf; FR?'"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
#deine ZU[(U/ \) ( ( U ) > ( \ ) W ( U ) *
( \ ) )
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
&8
( ( iBB ) > ( .BB ) W ( iBB ) * ( .BB ) )
so that the larger parameter is incremented tCice in error since parameter passing to macros is
essentially teEt replacement'
'1- E22ici5nc4 Con3id5ra0ion3
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
'1M E95rci353
1 0rite a program that can convert temperatBres from the Fahrenheit scale to CelsiBs and Dack'
+he relationship is C X ;8#%<;F 3"<' 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'
!1 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'
&1 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'
'1 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'
)1 0rite and test a circBlar shift left fBnction for one Dyte Bnsigned variaDles i'e' Bnsigned
characters'
e'g' !$$!!!$$ circBlar shift left Dy " yields $!!!$$!$'
+1 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$$$'
,1 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 &? 8= and
that if Ce Cish to convert the digit T3O for eEample to an integer Ce simply sBDtract the A6C((
valBe of digit T$O from its A6C(( valBe i'e' T3O T$O X 8! &? X 3'
-1 0rite and test a fBnction to get a floating point nBmDer from the standard inpBt device' +he
fBnction shoBld have the prototype
loat "etloat( void ) '
and shoBld De aDle to accommodate normal floating point notation and eEponential notation' 7oB
shoBld make Bse of the "etint() fBnction in eEercise 8' to read in the varioBs components of
the floating point nBmDer'
M1 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'
E1 0rite a recBrsive fBnction to calcBlate and print oBt all the FiDonacci valBes Bp to and
inclBding the n
th
' Recall that the FiDonacci series is !I !I "I 3I 8I ?I !3I ''' '+o test yoBr program
&=
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'
1 Programming A33ignm5n0 / Non?6in5ar ELua0ion31
7oBr Dasic task in this assignment is to Crite a C program Chich Cill alloC the Bser to solve the
folloCing nonlinear eJBation
f #
#
# ; < sin = + =
"
8
! $
to an accBracy of !$
8
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 6ogica6 fBnctions and try to intercept all
erroneoBs sitBations as soon as possiDle and take appropriate action'
No05 / +he eEact solBtion to the aDove eJBation is !'8%8?6%38%'
&?
Chapter 8
Arra43 * S0ring3
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 mBltidimensional arrays'
)1 Sing65 Dim5n3ion Arra43
ynta! " 04:5 7arOnam5A 3iP5 C G
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 / In C a66 arra43 u35 P5ro a3 0;5 ind59 0o 0;5 2ir30 565m5n0 in 0;5 arra4'
For -Eample Q
int arra+] 9 ^ '
Chich Ce might illBstrate as folloCs for a 3"Dit system Chere each int reJBires & Dytes'
array\$] !" loc
n
!$$$
array\!] 3&8 loc
n
!$$&
array\"] 3&" loc
n
!$$?
array\3] 3$$$$ loc
n
!$!"
array\&] "3&88 loc
n
!$!6
NB / +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 / *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 / 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\8] aDove Chich does not eEist the system Cill give access to
the location Chere element array\8] shoBld De i'e' 8 E & Dytes from the Deginning of the array'
array\$] !" loc
n
!$$$
array\!] 3&8 loc
n
!$$&
array\"] 3&" loc
n
!$$?
array\3] 3$$$$ loc
n
!$!"
array\&] "3&88 loc
n
!$!6
array\8] !"3 loc
n
!$"$
+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 ( '
)1! S0ring3
(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'
8$
For -Eample Q string to hold 8 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 GeG GlG GlG GoG GN$G
as opposed to
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 9 as 0;5 nam5 o2 an arra4 Bi0;ou0 an4 ind59 or 3Luar5
8rac53 i3 a63o 0;5 addr533 o2 0;5 arra4'
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,/ s3]35^ 1 )Mtrin"3, '
int i '
strcp+( s0/ s3 ) ' /* 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 ) ' /* returns the len"th o s0 */
strcat ( s0/ s3 ) ' /* Concatenates s3 onto end o s0 */
)1& Mu60idim5n3iona6 Arra43
8!
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 " : 3'
int d] 3 ^ ] 4 ^ '
d]5^]5^ d]5^]0^ d]5^]3^
d]0^]5^ d]0^]0^ 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 roCCise in memory'
For -Eample Q 2rogram to fill in a "D array Cith nBmDers ! to 6 and to print it oBt roCCise'
#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
8"
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/ ;( ( '
)1' Arra43 o2 S0ring3
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 suices
{
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 ) '
(
(
83
)1) Arra43 a3 argum5n03 0o 2unc0ion3 H D I
(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 unc0 */
(
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'
func!
x
main()
array
refers to data
at address !"""
data at
address !"""
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 3 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 !6Dit system DBt foBr in
3"Dit systems'
For -Eample Q 2rogram to calcBlate the average valBe of an array of doBDles'
#include <stdio.h>
8&
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+] ^ ) ' /* Xunction to determine i
arra+
is a palindrome returns 0 i it is a palindrome/ 5 otherwise
*/
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#) '
(
88
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 */
or ( ' i < . ' iBB/ .88 )
i ( arra+] i ^ H1 arra+] . ^
return 5 ' /* return value 5 i not a
palindrome */
return 0 ' /* 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 strin" */
strrev( temp ) ' /* reverse strin" */
i ( H strcmp( temp/ arra+ ) ) /* compare strin"s _
i same strcmp returns 5 */
return 0 '
else
return 5 '
(
)1+ Pa33ing Mu60idim5n3iona6 Arra43
FBnction calls Cith mBltidimensional 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 double !]05^]35^ '
Call fBnc! Cith E a parameter Q unc0( ! ) '
Declaration in fBnc! Q 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\8]\3] of the array in memory the compiler might do the folloCing
element Vo 1 9 * 35 B 4 1 054.
86
NB / MBltidimensional arrays are stored roCCise so +]9^]4^ is the &
th
element in the 6
th
roC'
6ince Ce are dealing Cith an array of doBDles this means it mBst access the memory location
!$3 : ? 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 two unctions
or
//+ourselves
void mat=print( int mat]3^]3^ ) '
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^ '
(
8=
)1, E95rci353
1 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'
!1 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'
&1 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'
'1 0rite a program that reads an array of Bp to "$ integers from the keyDoard and prodBces a
histogram of the valBes as indicated DeloC'
F
F F
F F
F F F F
F F F F F F
F F F F F F F
F F F F F F F F F
& ! ' + , ' &
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'
)1 0rite a program to accept tCo strings from the keyDoardI compare them and then print oBt
Chether or not they are the same'
+HaI1 0rite a fBnction to test Chether or not a Cord is a palindrome e'g' MADAM'
H8I1 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'
,1 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'
3' 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'
?' 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
8?
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 D
a D
'
c d
c d
a c D c a d D d
a c D c a d D d
! !
" "
! !
" "
! ! ! " ! ! ! "
" ! " " " ! " "

=
+ +
+ +

M1 A real polynomial p;E< of degree n is given Dy


p # a a # a # a #
n
n
; < = + + + +
$ ! "
"

Chere the coefficients a


n
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
3
<<<
Compare the efficiency oDtained Bsing Doth methods'
E1 Programming A33ignm5n0 / Tic?Tac?To5
0rite a C program Chich alloCs the Bser to play the compBter in a game of tictactoe ;noBghts
and crosses <'
+he program shoBld Bse a tCo dimensional array to represent the 3E3 Doard matriE and alloC the
varioBs positions on the Doard to De referenced as coordinates sBch as ;$I$< for the Bpperleft
corner and ;"I"< for the loCerright corner'
7oBr program might inclBde fBnctions to do the folloCing Q
!' (nitialise the playing area appropriately'
"' Display the cBrrent state of the game'
3' )et the playerGs move'
&' )et the compBterGs move'
8' 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'
The tic tac toe program should incorporate the following three user specifed
options in a single package.
8%
Option 1: The computer will be limited to playing a very simple dull game.
When it is the computers turn to move it simply scans the board matri! and
flls the frst unoccupied position encountered. "f it cannot fnd an unoccupied
location it reports a drawn game.
Option #: The computer plays a full game ie. it checks frst if it can win the
game with its current move. This failing it checks if it can prevent the player
from winning with his$her ne!t move. Otherwise it flls the frst available
unoccupied position.
Option %: The program allows two players to play each other &without any
help or hints'(.
+he program shoBld rBn continBoBsly alloCing the player to eEit Bsing a special FhotkeyF dBring
a game and shoBld alloC the player to choose Cho moves first'
6$
Chapter 6
Poin05r3
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 4alBe 4ariaDle
!$$$
!$$& !$!" ivarbptr
!$$?
!$!" "3 ivar
!$!6
(n the aDove illBstration i!ar is a variaDle of type int Cith a valBe "3 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 / (t shoBld De rememDered that ivarbptr is a variaDle itself Cith a specific piece of memory
associated Cith itI in this 3"Dit case foBr Dytes at address !$$& Chich is Bsed to store an address'
+1 Poin05r "aria8653
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 / +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 !6Dit 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 3" Dits
long and thBs pointers are & Dytes in siPe and are termed far pointers'
(n 3"Dit systems Ce have a flat address system Chere every part of memory is accessiDle
Bsing 3"Dit pointers'
+1! Poin05r O:5ra0or3 F and *
6!
* is a Bnary operator that retBrns the addr533 of its operand Chich mBst De a variaDle'
For -Eample Q
int *m '
int count1039/ i '/* m is a pointer to int/ count/ i are
inte"ers */
m 1 Ecount '
+he address of the variaDle coBnt is placed in the pointer variaDle m'
+he @ operator is the complement of the address operator 9 and is normally termed the indirection
operator' /ike the 9 operator it is a Bnary operator and it retBrns the 7a6u5 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'
!"8 !"8 !$$$
!$$$ !="& !?"&
coBnt m i
indirection
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 rBntime 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 / *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'
+1& Ca66 84 R525r5nc5
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 dereferenced 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 callDyvalBe 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 callDyreference 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 dereference these pointers Ce are accessing
the valBes in the main;< fBnction as their addresses do not change'
63
+1' Poin05r3 and Arra43
+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 perorms 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 ' // position the pointer appropriatel+
*ptr 1 2a2 ' // access irst element i.e. str]5^
ch 1 *( ptr B 0 ) ' // access second element i.e. str]0^
+hBs FH arra4 D ind59 I is eJBivalent to arra4Aind59C'
*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 ' /* accesses element 9 o arra+ b+ indexing a
pointer */
+1) Poin05r Ari0;m50ic
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'
A33ignm5n0
int count/ *p0/ *p3 '
6&
p0 1 Ecount ' // assi"n the address o a variable
directl+
p3 1 p0 ' // assi"n the value o another pointer variable/
an address
Addi0ion % Su80rac0ion
+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 3"Dit system and hence 3"Dit integers'
int *ptr ' Address 4alBe
int arra+]4^ 1 { 055/ 050/
053 ( '
ptr !$$$ "$$?
ptr 1 arra+ '
array\$] "$$? !$$
array\!] "$!" !$!
array\"] "$!6 !$"
0e noC have the pointer variaDle ptr pointing at the start of array Chich is stored at memory
location "$$? 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 3"Dit system' 0hen Ce add ! to ptr Chat Ce Cant to
happen is to point to the n590 in05g5r 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 / +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:ari3on3
68
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'
1 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 ) '
(
!1 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 #@ FBnction to determine if array is a palindrome' retBrns ! if
it is a palindromeI $ otherCise @#
void main; <
L
char str\3$]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
ptrHH U #@ get length of string i'e' increment ptr Chile @ptr SX GN$G @#
ptr U #@ move Dack on5 from GN$G @#
Chile ; str [ ptr <
if ; @strHH SX @ptr <
retBrn $ U #@ retBrn valBe $ if not a palindrome @#
retBrn ! U #@ otherCise it is a palindrome @#
M
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'
+1+ Arra43 o2 Poin05r3
(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 9var U
+o access the valBe pointed to Dy E\ " ] Ce CoBld do the folloCing
@E\ " ]
Chich simply dereferences 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
6=
*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\3]\3$] X L
''' M U
+1, Command #in5 Argum5n03
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 inDBilt argBments to the main;< fBnction commonly called argc and arg7
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
6?
+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 " 99 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 / 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'
+1- D4namic M5mor4 A66oca0ion
+his is the means Dy Chich a program can oDtain and release memory at rBntime' +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 ma66ocHI and 2r55HI 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;< '
+1M Mu60i:65 Indir5c0ion ?? Poin05r3 0o Poin05r3
(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 dereferencing 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 dereference this latter pointer tCice to actBally access the
variaDle Ce are interested in' Dereferencing the pointer to a pointer once gives Bs a normal singly
indirected pointerI dereferencing the pointer to a pointer secondly alloCs Bs to access the actBal
data variaDle' +he sitBation is depicted in the diagram DeloC'
=$
address "
address 3
doBDlebptr
address !
single indirection
variaDle
valBe
doBDle indirection
single indirection
address " address 3
singlebptr
+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 9E U
J X 9p U
@@J X "$ U ## dereference tCice to access valBe
p X @J U ## dereference J once to get a pointer to int
c
int array!\] X L !I"I3I&I8I6 I= I?I%I!$M U
int array"\] X L!$I"$I3$I&$I8$M U
int @pointers\"] U ## an array of pointers to type int
int @@ptr U ## a doBDly indirected pointer
ptr X pointers U ## initialise pointer to array of pointers
@ptrHH X array! U ## noC Ce simply dereference the pointer to a pointer
@ptr X array" U ## once and move it on like any pointer
@@ptr X !$$ U ## 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'
ptrbroCs
arrays of n doBDlesI
the roCs
array of m
pointers to roCs
pointer to
pointer to
doBDle
=!
>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 9mI 9n < U
bflBshall;< U
ptrbroCs X ; doBDle @@< malloc; m @ siPeof ; doBDle @ < < U ## space for roC pointers
Bserbptr X ptrbroCs U
for ; i X $U i [ m U iHH < ## and then roC elements
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 ## move onto neEt roC pointer
M
## after Bse Ce need to clean Bp in reverse order
Bserbptr X ptrbroCs U
for ; i X $U i [ nU iHH <
free; @Bserbptr HH < U ## free a roC and move onto neEt
free; ptrbroCs < U ## free pointers to roCs
M
+1E Poin05r3 0o (unc0ion3
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! " r50O04:5 H F 2:0r I H :aram505r 6i30 I G
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
="
+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!\?$]I s"\?$] 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
=3
void main; <
L
char s!\?$]I s"\?$] 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
+1 E22ici5nc4 Con3id5ra0ion3
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'
=&
+1! E95rci353
1 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'
!1 +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\?$] U
p! X s U
do
L
gets; s < U
Chile; @p! <
printf;FRdFI@p!HH < U
M Chile;strcmp;sI FdoneF< < U
M
&1 +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
'1 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'
)1 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 '
e'g'' ! 6BndayI " MondayI etc'
=8
+he fBnction shoBld print oBt an invalid message if an incorrect nBmDer is passed to it'
+1 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 8 and the length of each Cord to !$ '
,1 0rite and test a fBnction Chich can perform Bnsigned integer addition Cith Bp to 8$ digits of
precision maintained'
For -Eample Q
%!"3&!"3&!"3&!"3&!"3&!"3&!"3&!"3&!"3&
H !!"3&!"3&!"3&!"3&!"3&!"3&!"3&!"3&!"3&
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
!$"&6?"&6?"&6?"&6?"&6?"&6?"&6?"&6?"&6?
+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 8$ digits of precision'
-1 0rite a simple fBnction e'g' to add tCo nBmDers and define a pointer to this fBnction to call the
fBnction'
M1 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'
E1 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"'
=6
1 Programming A33ignm5n0 / Ba35 Con75r3ion Program
7oBr task in this assignment is to Crite a C program Chich converts an un3ign5d 3;or0 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 30ring 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 " !$ inclBsive are to De alloCed in the programI so yoB shoBld
check
!' 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 Chitespace
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 "3 in Dase & X " E &
!
H 3 E &
$
X ? H 3 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 $ 6883& valid valBes and Bse 68838 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
==
!!$$ in Dase "

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
!" !$ "
"& 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'
No05 / 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 ? so this section shoBld De pBt aside Bntil later'
=?
" !" 6 Rem $
" 6 3 Rem $
" 3 ! Rem !
Rem !
=
=
=
= " ! $
!1 Programming A33ignm5n0 / Ta8u6a0ion Program1
7oBr main task in this assignment is to Crite and test a fBnction
in0 F0a8u6a05H in0 Fda0a, in0 num7a63 I G
+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 ?I = M then min X 6 and maE X !$ so Ce need
to allocate a Dlock of ; maE min H ! < X 8 integers to contain all valBes in the range' +he first
element in the array is for the valBe 6I the second for =I 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 maE > 6Os > =Os > ?Os > %Os > !$Os
6 !$ $ $ $ $ $
+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 maE > 6Os > =Os > ?Os > %Os > !$Os
6 !$ " ! ! $ !
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'
=%
&1 Programming A33ignm5n0 / Po64nomia6 Par35r
The basic re)uirement of this assignment is to write a * program which can
resolve a simple polynomial into a vector of its components and to make use
of this form to implement di+erentiation of the e)uation.
The e)uation parser should be implemented as a function which is passed an
,-*"" character string which is used to represent a polynomial of degree n
which has the general form
a # a # a # a a # a # a # a #
n
n
n
n
n
n
n
n

+
+

+ + + + + + +
!
!
!
!
$ ! "
"
!
!

where ! is the dependant variable. a
n
are the coe/cients of the polynomial
&which may be limited to signed integer values(.
The character string representation may be of any degree. n. and the
components may be in any random order and may even be repeated. 0se
the 123 character to represent to the power of. The character string may also
include white space characters for readability. namely the space character.
which do not convey any information but which nonetheless must be
processed being part of the string. -ome e!amples of valid e)uations are
given below where 4 represents the space character.
1 5 ! 5 #!2# 5 6!27
#!27 5 %! 81#
89 5 #!2% 8 #! 5 7 8 !
87 !28# 5 !2815 #!2%
!424#454#4!424%
The e)uation parser must resolve the polynomial into a vector
representation. ie. it must establish a value for the coe/cient of each
component of the polynomial. This information or vector should be stored in
a single dimension integer array where the inde! into the array represents a
specifc component of the vector. :ector;0< represents the coe/cient of !20.
:ector;1< represents the coe/cient of !21. and so on up to the degree of the
polynomial.
The si=e of the vector array should be >ust su/cient to store the re)uired
vector. memory being allocated dynamically once the degree of the
polynomial has been established. ?or e!ample a polynomial of degree #
would re)uire an array of three elements to store all the component
coe/cients.
?or testing purposes your program should frst of all take in a polynomial in
the form of a character string as input. resolve this into a vector using the
parser function. and then pass this vector to a function which should
di+erentiate the vector & or e)uation ( and store the result in a di+erent
vector of appropriate dimension.
The results of each operation should be displayed in tabular form as
illustrated in the following e!ample where the e)uation input was 6!2% 5
%!2# 8 ! 5 7.
*oe/cients : !20 !21 !2# !2%
@)uation : 7 81 % 6
?$
@)uation : 81 9 16
The results of the operation should also be stored to a user specifed te!t fle
in the same tabular form as above. "n the case where the fle specifed
already e!ists and has a number of valid entries. the new entry to be added
should be separated by a blank line from the others for readability.
?!
Chapter =
S0ruc0ur53 * Union3
,1 S0ruc0ur53
A strBctBre is a cBstomised Bserdefined 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'
Som5 05rmino6og4 /?
strBctBre definition Q the template Bsed to create strBctBre variaDles'
strBctBre elements Q the memDer variaDles of the strBctBre type
&efining tructures
ynta! " 30ruc0 0ag Q
04:5 7arO G
04:5 7arO! G
111
04:5 7arOn G
R G
+he keyCord 30ruc0 tells the compiler Ce are dealing Cith a strBctBre and mBst De present
Chenever Ce refer to the neC typeI 0ag 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\3$] U
char toCn\&$] U
char coBntry\ "$ ]
M U
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 / +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'
?"
strBct compleE L
doBDle real U
doBDle imaginary U ## *ote that a variaDle may also De
M cplE U ## defined at strBctBre definition time
+he elements of the strBctBre are accessed Bsing the do0 o:5ra0orI 1 I as folloCs
cplE'real X !$'$ U
cplE'imag X "$'"3 U
scanf ; FRlfFI 9cplE'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\3$] U
int idbno U
M U
strBct id stBdent X L FdohnFI &863 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
y X E U ## 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'
?3
strBct time L
int hoBr U
int min U
int sec U
M U
strBct employeeblog L
char name\3$] 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
?&
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
M U
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 9person 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 on64 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
M U
void display ; const strBct timebvar @ < U #@ note strBctBre pointer and const @#
void main;<
L
strBct timebvar time U
time'hoBrs X !" U
time'minBtes X $ U
time'seconds X $ U
display; 9time < 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'
&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'
?8
For -Eample Q
strBct coordinate L
int EI yI P U
M U
strBct coordinate @ptr U
ptr X ;strBct coordinate @ < malloc; siPeof ; strBct coordinate < < U
,1! Bi0??(i56d3
5itfields 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 Ditfield elements are restricted to De of type int ; signed or Bnsigned <'
For -Eample Q
strBct clock L
Bnsigned hoBr Q 8 U
Bnsigned minBtes Q 6 U
Bnsigned seconds Q 6 U
M time U
+his time strBctBre reJBires != Dits to store the information noC so the storage reJBirement is
roBnded Bp to 3 Dytes' Using the normal strBctBre format and 3"Dit integer elements Ce CoBld
reJBire !" Dytes so Ce achieve a sBDstantial saving'
5itfields 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
Ditfield'
strBct statBs L
Bnsigned Dit$ Q ! U
Bnsigned Dit! Q ! U
'''
Bnsigned Dit!8 Q ! U
M U
(f Ce are interested in Dit !8 only Ce need only do the folloCing
strBct statBs L
Bnsigned Q !8 U #@ skip over first !8 Dits Cith a FnonmemDerF @#
Bnsigned Dit!8 Q ! U
M U
+here are tCo fBrther restrictions on the Bse of Ditfields
Cannot take the address of a Ditfield variaDle
Cannot create an array of Ditfield variaDles
Can yoB sBggest reasons for this ^
,1& Union3
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
?6
union uO0ag Q
3;or0 i7a6 G
26oa0 27a6 G
c;ar c7a6 G
R u7a6 G
+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 Ditfield 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 9nBmDer'nBm <U
6ince the integer and Ditfield elements of the Bnion share the same storage if Ce noC access the
Bnion as the Ditfield variaDle bits Ce can interpret the Dinary representation of nBm directly'
i'e' if ; Bvar'Dits'Dit!8 <
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'
,1' Enum5ra0ion3
?=
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!" 5num 0ag Q 7a6u5O6i30 R A 5numO7ar C G
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 3
enBm day L sBn X !I monI tBeI Ced X "!I thBrI friI sat M U
enBm day Ceekday U
## valBes are !I "I 3I "!I ""I "3I "&
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 ## assign a valBe to shade enBm variaDle
i X shade U ## assign valBe of enBm to an int
shade X 3 U ## assign 7a6id int to an enBmI treat Cith care
,1) T;5 04:5d52 S54Bord
C makes Bse of the 04:5d52 keyCord to alloC neC data type nam53 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 inDBilt types or a Bserdefined type'
ynta! " 04:5d52 04:5 nam5 G
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 ## can noC declare a variaDle of type T(*+-)-RO
typedef doBDle @ doBDlebptr U
doBDlebptr ptr U ## 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
??
+o remedy the sitBation Ce modify the Bser defined type as folloCs
typedef doBDle F/OA+(*) U
,1+ #inT5d #i303
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 rBntime'
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 3'
3' 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" 9 & Cill have to De carried oBt in one
form or another' ,oCever step 3 can De avoided if Ce represent the data in an alternate fashion'
(f Ce can represent oBr data as a chain of interconnected 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'
?%
Alan #en Sam Tom
$ohn
#rea%
Existin& Lin%
'ew Lin%s
*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 selfreferential strBctBre' For eEample Q
strBct node L
char name\"$] U
strBct node @neEtnode U
MU
+his defines a neC typeI 30ruc0 nod5I 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 ;5ad' 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 0ai6'
%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 nodebptrWneEtnode <
pBts; nodebptrWname < 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; pbheadWname < U
printblist; pbheadWneEtnode < 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// 99 ;strcmp; neCWnameI nodebptrWname < W $ < <
L
prev X nodebptr U
nodebptr X nodebptrWneEtnode U
M
if ; prev XX *U// < ## head position
L
neCWneEtnode X @pbhead U
@pbhead X neC U
M
else
L
prevWneEtnode X neC U
neCWneEtnode 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// 99 strcmp; nameI nodebptrWname < <
L
%"
prev X nodebptr U
nodebptr X nodebptrWneEtnode U
M
if ; prev XX *U// < ## removing head position
L
@pbhead X ;@pbhead<WneEtnode U
retBrn nodebptr U
M
else L
prevWneEtnode X nodebptrWneEtnode 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 ( struct node ) ) '
strcp+( node=08>name/ #Ulan# ) '
insert( Eptr=head/ node=0 ) '
node=3 1 ( struct node *)malloc( siGeo ( struct node ) ) '
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'
%3
,1, E22ici5nc4 Con3id5ra0ion3
As descriDed previoBsly pointers shoBld De Bsed to implement callDyreference in passing large
Bser defined data items to fBnctions to redBce the copying overhead involved in callDyvalBe' (f
implementing a typical callDyvalBe 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 <'

%&
,1- E95rci353
1 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'
!1 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'
&1 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'
'1 Use a comDination of Ditfields and Bnions in C to print oBt the Dit patterns of any Bnsigned
integer valBes inpBt at the keyDoard'
)1 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 11> 5
5550 11> 0
...
0550 11> @
+hBs short int can De Bsed to represent a foBr digit decimal nBmDer'
Use 5itFields to implement conversion roBtines to encode a decimal nBmDer into 5CD format
and Dack again'
+1 Redo proDlem ! Bsing a Ditfield strBctBre as an illBstration of hoC memory reJBirements may
De redBced' Compare the old and neC memory reJBirements for data storage'
,1 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'
-1 Use a F(FO implementation of a linked list to represent a JBeBe of people entered Dy the Bser'
%8
Chapter ?
S0andard (i65 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 loClevel (#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 loClevel (#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'
-1 S0r5am 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 30r5am in C and the actBal device is termed a 2i65'
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 30din and 30dou0 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
onetoone relationship is maintained DetCeen data sent and data received'
%6
Common 5ile 5unctions
open() open a stream
close() close a stream
putc()E putc() Crite a character to a stream
"etc()E "etc() read a character from a stream
print()E scan formatted (#O
"ets() E puts() string handling
seek() position the file pointer at a particBlar Dyte
eo() 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 2i65 :oin05r 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 opens a teEt file for reading ;mBst eEist<
C opens a teEt file for Criting ;overCritten or created<
a append to a teEt file
rD opens a Dinary file for reading
CD opens a Dinary file for Criting
aD appends to a Dinary file
rH opens a teEt file for read#Crite ;mBst eEist<
CH opens a teEt file for read#Crite
aH append a teEt file for read#Crite
rDH opens a Dinary file for read#Crite
CDH opens a Dinary file for read#Crite
aDH 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'
%=
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 putc()
fBnction'
putc( ch/ p ) '
(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( #<nter source ile name# )'
"ets( source )'
puts( #<nter destination ile name# )'
"ets( dest ) '
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 ) '
(
while ( ( ch 1 "etc( in ) ) H1 <DX )
putc( ch / out ) '
close( in ) '
close( out ) '
(
NB / 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 "ets() and
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 ile Vame * # )'
"ets( ile )'
i (( p 1 open( ile/ #w# )) 11 V>?? )//open or
writin"
{
print( #Cannot open ile As#/ ile ) '
e!it( 0 ) '
(
while ( strlen ( "ets( str ) ) > 5 )
{
puts( str/ p ) '
putc( 2&n2/ p ) ' /* must append &n or
readabilit+ 88 not stored b+ "ets() */
(
close( p ) '
i (( p 1 open( ile/ #r# )) 11 V>?? )//open or
readin"
{
print( #Cannot open ile As#/ ile ) '
e!it( 0 ) '
(
while ("ets( str/ 7@/ ptr ) H1 <DX )// read at most 7@
characters
puts( str ) '
close( p ) '
(
%%
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( p ) '
(
No05 / +here are several (#O streams opened aBtomatically at the start of every C program'
stdin standard inpBt ie' keyDoard
stdout standard oBtpBt ie' screen
stderr again the screen for Bse if stdoBt malfBnctions
(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 *buer/ siGe=t num=b+tes/ siGe=t count/
XS?< *p ) '
siGe=t write( const void *buer/ siGe=t num=b+tes/ siGe=t
count/ XS?< *p ) '
Chere 8u225r is a pointer to the region in memory from Chich the data is to De read or Critten
respectivelyI numO84053 is the nBmDer of Dytes in each item to De read or CrittenI and coun0 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/ p ) '
rewind( p ) ' /* repositions ile pointer to start */
read( Ed/ siGeo( double )/ 0/ p ) '
read( i/ siGeo( int )/ :/ p ) '
read( Ecustomer/ siGeo( struct ta" )/ 0/ p ) '
close( p ) '
(
NB / Unlike all the other fBnctions Ce have encoBntered so far fread and fCrite read and Crite
8inar4 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 ? 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-+ Deginning of file
6--AbCUR cBrrent position
6--Ab-*D -OF
and Chere numO84053 is the offset in Dytes to the reJBired position in the file' fseek;< retBrns Pero
Chen sBccessfBlI otherCise a nonPero valBe'
For -Eample if Ce had opened a file Chich stored an array of integers and Ce Cish to read the
8$
th
valBe Ce might do the folloCing
seek ( p/ ( :@ * siGeo( int ) )/ M<<T=M<T ) '
scan( p/ #Ad#/ Ei ) '
from anyChere in the program'
-1! #oB ?? #5756 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 nonnegative 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
30andard in:u0 ??? E
30andard ou0:u0 ???
30andard 5rror ??? !
+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;< opens a disk file
close;< closes a disk file
read;< reads a DBffer of data from
disk
Crite;< 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 ola" ]/ 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'
o26ag may De any logical comDination of the folloCing constants Chich are KBst bit flags comDined
Bsing the DitCise OR operator'
!$"
ObA22-*D appends to end of file
Ob5(*AR7 Dinary mode
ObCR-A+ creates a neC file if it doesnGt eEist
ObRDO*/7 read only access
ObRD0R read Crite access
Ob+-:+ teEt mode
Ob+RU*C trBncates file to Pero length
Ob0RO*/7 Crite only access
:mod5 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 *buer/ unsi"ned int count ) '
int write( int handle/ void *buer/ 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=SY<UL J
M=S%YST< )'
i ( handle 11 80 ) return '
i ( read( handle/ bu/ 0555 ) 11 0555 )
puts( #Yead successul#)'
else
{
puts( Yead ailed# ) '
e!it( 0 )'
(
!$3
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 ) 11 0555 )
puts( #%rite successul#) '
else
{
puts( #%rite Xailed#) '
e!it( 0 ) '
(
close( handle ) '
(
/oC level file (#O also provides a seek fBnction 6355T Cith the folloCing prototype'
lon" =lseek( int handle/ lon" offset/ int origin )'
O6355T 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 <stdio.h>
#include <io.h>
#include <cntl.h>
#include <s+s&stat.h>
void main()
{
int handle '
lon" len"th '
char name]F5^ '
print( )<nter ile name * , ) '
"ets( name ) '
handle1open( name/D=\SVUYQJ D=YLDV?Q/ M=SY<UL J
M=S%YST< )'
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 )
'
(
-1& E95rci353
1 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
!$&
iv' *BmDer of non alphaDetic characters
v' +aDBlates the Bsage of each letter of the alphaDet'
!1 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 lookBp 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 lookBp taDle and calcBlating them straight' 7oB
might find the standard liDrary time fBnctions BsefBl to compare times accBrately'
&1 Programming A33ignm5n0 / Sim:65 Da0aBa351
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 '
t+pede struct list {
L<TUS?M **data=items '
int numrecords '
int selrecord '
( ?SMT '
+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'
+he list strBctBre tells Bs that there are tCo records in the listI the cBrrent Deing the first in the list'
+he pointer mylistWdatabitemsI 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' @;mylistWdatabitems 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'
!$8
!' Add a record to the dataDase'
"' 6earch for a record Dy field in the dataDase'
3' Order the dataDase Dy field'
&' Retrieve a record from the dataDase'
8' -Etract a record from the dataDaseI deleting it completely'
6' 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
[listWdatabitemsW 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 . ) '
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
!$6

!$=

You might also like