Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

C Programming

C programming language was developed in 1972 by Dennis Ritchie at Bell Labs to develop the UNIX operating system. It is a general-purpose, procedural language that is widely used today. C produces efficient programs and can handle both high-level and low-level activities. It has become popular for systems programming due to its ability to be compiled on many platforms and because it produces fast code like assembly languages.

Uploaded by

rahulsinghktr07
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

C Programming

C programming language was developed in 1972 by Dennis Ritchie at Bell Labs to develop the UNIX operating system. It is a general-purpose, procedural language that is widely used today. C produces efficient programs and can handle both high-level and low-level activities. It has become popular for systems programming due to its ability to be compiled on many platforms and because it produces fast code like assembly languages.

Uploaded by

rahulsinghktr07
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 268

Cpr ogrammi ngisagener al-

purpose, pr
ocedur al
,
i
mper ativecomput erpr ogrammi ngl anguagedev el
oped
i
n1972byDenni sM.Ri tchieattheBel lTelephone
Laboratoriest odevelopt heUNI Xoper ati
ngsy stem.Cis
themostwi delyusedcomput erlanguage.Itkeeps
fl
uctuatingatnumberonescal eofpopul ari
tyalongwi t
h
Javaprogr ammi ngl anguage, whichi salsoequal l
y
popularandmostwi delyusedamongmoder nsof t
ware
programmer s.

Whyt oLearnCPr ogr


ammi ng?
Cpr ogrammingl anguageisaMUSTf orstudentsand
working prof
essionalsto become a gr eatSof t
ware
Engineerspecial
lywhent heyar eworkinginSof t
ware
DevelopmentDomai n.Iwi
lll
istdownsomeoft hekey
advantagesoflearni
ngCPr ogramming:
 Easyt
olear
n
 St
ruct
uredl
anguage
 I
tpr
oducesef
fi
cientpr
ogr
ams
 I
tcanhandl
elow-
lev
elact
ivi
ti
es
 I
tcan be compi
l
ed on a v
ari
ety ofcomput
er
pl
atf
orms
Fact
saboutC
 Cwasi
nvent
edt
owrit
eanoperat
ingsy
stem cal
l
ed
UNI
X.
 C i
s a successor of B l
anguage whi
ch was
i
ntr
oducedar
oundtheearl
y1970s.
 The l
anguage was f
ormal
ized in 1988 by t
he
Ameri
canNati
onalSt
andar
dInsti
tut
e( ANSI
).
 TheUNI
XOSwast
otal
l
ywr
it
teni
nC.
 Today C isthe mostwi del
y used and popul
ar
System Pr
ogr
ammi ngLanguage.
 Mostofthe st
ate-
of-
the-
artsof
twar
e hav
e been
i
mplement
edusingC.
 Today
'smostpopul
arLi
nuxOSandRDBMSMy
SQL
havebeenwr
it
teninC.

Hel
loWorl
dusingCPr ogr
amming.
Just to gi v
e y ou a l it
tl
e excit
ement aboutC
programming, I
'm going t o give you a small
conventi
onalCProgr
ammi ngHell
oWorldpr
ogram,

The#i ncl
udei saprepr ocessorcommandt hatt el
l
sthe
compi l
ertoincludethecont ent sofstdi
o.h(standard
i
nputandout put)fi
l
ei nthepr ogram.
 Thest di
o.hfil
econt ai
nsf unctionssuch
asscanf (
)andpr int
f()totakei nputanddisplayoutput
respecti
vely
.
 Ifyouuset hepr intf
()functionwithoutwr i
ti
ng#incl
ude
<stdio.h>, thepr ogram wi l
lnotcompi l
e.
 Theexecut ionofaCpr ogram startsfrom
themai n(
)f unct ion.
 printf()isal ibrar yfunctiontosendf ormattedoutputt
o
thescr een.I nthi sprogram, pri
ntf()displaysHel
lo,
Wor ld!t extont hescr een.
 Ther et urn0; statementi sthe"Exitst atus"oft
he
progr am.I nsi mpl eterms, t
heprogr am endswi t
ht hi
s
statement .

#i
ncl
ude<st
dio.
h>

i
ntmain(){
/*myf i
rstprogr
am inC* /
pri
ntf
("Hell
o,World!\
n")
;

ret
urn0;
}

Appl i
cati
onsofCPr ogrammi ng
C was init
ially used forsystem dev el
opmentwor k,
part
icul
arl
yt hepr ogramst hatmake- uptheoper ati
ng
system.C was adopt ed as a system development
l
anguagebecausei tproducescodet hatrunsnearlyas
fastasthecodewr i
tteninassembl ylanguage.Some
examplesoft heuseofCar e-
 Oper
ati
ngSy
stems
 LanguageCompi
l
ers
 Assembl
ers
 TextEdi
tor
s
 Pr
intSpool
ers
 Net
wor
kDr
iver
s
 Moder
nPr
ogr
ams
 Dat
abases
 LanguageI
nter
pret
ers
 Ut
il
it
ies

Ci sagener al
-pur
pose,high-
levell
anguagethatwas
ori
ginal
lydevel
opedbyDennisM.Ri t
chiet
odev el
opt he
UNIXoper at
ingsystem atBellLabs.C wasor i
ginall
y
fi
rstimplement
edont heDECPDP- 11computerin1972.
In1978,Bri
anKernighanandDennisRi
tchi
eproduced
thefi
rstpubl
icl
yavail
abl
edescr
ipt
ionofC,now known
astheK&Rstandar
d.
The UNI X operat
ing system,t he C compi l
er,and
essent
iall
yallUNIX applicati
on programshavebeen
writ
ten in C.C has now become a wi del
y used
prof
essionall
anguageforv ar
iousreasons−
 Easyt
olear
n
 St
ruct
uredl
anguage
 I
tpr
oducesef
fi
cientpr
ogr
ams
 I
tcanhandl
elow-
lev
elact
ivi
ti
es
 Itcanbecompi
l
edonav
ari
etyofcomput
er
platf
orms
Fact
saboutC
 Cwasi
nvent
edt
owr
it
eanoper
ati
ngsy
stem cal
l
ed
UNI
X.
 C i
s a successor of B l
anguage whi
ch was
i
ntr
oducedar
oundtheearl
y1970s.
 The l
anguage was f
ormal
ized in 1988 by t
he
Ameri
canNati
onalSt
andar
dInsti
tut
e( ANSI
).
 TheUNI
XOSwast
otal
l
ywr
it
teni
nC.
 Today C isthe mostwi del
y used and popul
ar
System Pr
ogr
ammi ngLanguage.
 Mostofthe st
ate-
of-
the-
artsof
twar
e hav
e been
i
mplement
edusingC.
 Today
'smostpopul
arLi
nuxOSandRDBMSMy
SQL
havebeenwr
it
teninC.
WhyuseC?
C was init
ially used forsystem dev el
opmentwor k,
part
icul
arl
yt hepr ogramst hatmake- uptheoper ati
ng
system.C was adopt ed as a sy
st em development
l
anguagebecausei tproducescodet hatrunsnearlyas
fastasthecodewr i
tteninassemblyl anguage.Some
examplesoft heuseofCmi ghtbe−
 Oper
ati
ngSy
stems
 LanguageCompi
l
ers
 Assembl
ers
 TextEdi
tor
s
 Pr
intSpool
ers
 Net
wor
kDr
iver
s
 Moder
nPr
ogr
ams
 Dat
abases
 LanguageI
nter
pret
ers
Uti
l
iti
es
CPr
ogr
ams
ACpr ogram canv ar
yfrom 3linestomil
l
ionsoflines
andi tshouldbewr i
tt
enintooneormor et
extfi
leswith
extension".
c"; f or exampl e,hel
lo.
c. You can
use" vi
","
vim"oranyot hertextedit
ortowrit
ey ourC
program int
oaf i
l
e.
Thist
utor
ialassumesthaty
ouknowhowtoedi
tatext
fi
l
eandhowt owr i
tesour
cecodei
nsi
deapr
ogr
am f
il
e.

Tokensi
nC
ACpr ogram consi
stsofv ar
ioustokensandat okenis
ei
therakeyword,anident
ifi
er,aconstant,
astri
ngl i
ter
al,
orasy mbol.Forexampl e,thefoll
owi ngC statement
consi
stsoffi
vetokens−
pr
int
f("
Hel
l
o,Wor
ld!\
n")
;
Thei
ndi
vi
dual
tokensar
e−
pr
int
f
(
"Hel
lo,
World!\
n"
)
;
Semicol
ons
InaCpr ogr
am, t
hesemi col
oni
sastatementter
minator
.
Thatis,
eachindivi
dualstat
ementmustbeendedwi t
ha
semicol
on.Iti
ndicat
estheendofonelogi
calent
ity
.
Gi
venbel
owar
etwodi
ff
erentst
atement
s−
pri
ntf
("Hel
l
o,Wor
ld!\
n")
;
ret
urn0;
Comment s
Comment sarel i
kehelpi
ngtextinyourCprogram and
theyar
ei gnor
edbyt hecompil
er.Theyst
artwit
h/ *and
termi
natewiththecharact
ers*/asshownbelow−
/
*myf i
rstpr
ogr
am inC*/
Youcannothav
ecomment swit
hincommentsandt
hey
donotoccurwi
thi
nastr
ingorchar
acterl
i
ter
als.
I
dent
if
ier
s
ACi denti
fi
erisanameusedt oi dent
if
yav ari
abl
e,
functi
on,oranyot heruser
-def
ineditem.Ani denti
fi
er
start
swi t
hal et
terAt oZ,at oz,oranunder score'_
'
foll
owed by zer
o ormor elett
ers,underscor
es,and
digi
ts(0to9).
Cdoesnotal l
ow punct
uati
oncharact
erssuchas@,$,
and % wi thi
n i denti
fi
ers. C i s acase-
sensi
ti
veprogramming l
anguage.
Thus,Manpowerandmanpowerar e t wo di f
ferent
i
denti
fi
ersinC.Herearesomeexampl esofacceptable
i
dent
if
ier
s−
mohd zar a abc move_
namea_123
myname50 _
temp j a23b9 ret
Val
Keywor
ds
Thefollowi
ngli
stshowst hereser
vedwor
dsi
nC.These
reser
ved words may notbe used as const
ant
s or
vari
ablesoranyot
heridenti
fi
ernames.
aut
o El
se Long Swi
tch

br
eak Enum Regi
ster Ty
pedef

case ex
ter
n Ret
urn Uni
on

char Fl
oat Shor
t Unsi
gned

const For Si
gned Voi
d

cont
inue Got
o Si
zeof Vol
ati
l
e

def
aul
t I
f St
ati
c Whi
l
e

do I
nt St
ruct _
Packed

doubl
e

Whi
tespacei
nC
Al i
ne cont
aini
ng onl
y whit
espace,possi
bly wi
tha
comment,isknownasabl ankli
ne,andaCcompi l
er
t
otal
l
yignor
esi
t.
Whit espacei stheter
m usedi nCt odescribebl anks,
tabs,newl inecharacter
sandcomment s.Whi tespace
separ atesonepar tofast at
ementf rom anotherand
enabl esthecompi l
ertoidenti
fywhereoneel ementi na
statement ,such as int
,ends and t he nextel ement
begins.Ther efor
e,i
nthefoll
owingstatement−
i
ntage;
t
here mustbe atl eastone whitespace char
act
er
(
usual
lyaspace)betweenintandageforthecompil
er
t
obeabletodist
ingui
shthem.Ontheotherhand,i
nthe
f
oll
owingst
atement−
f
rui
t=appl
es+or
anges;/
/gett
het
otal
frui
t
nowhi t
espacechar
acter
sarenecessar
ybetweenf r
uit
and=,orbetween=andappl
es,al
thoughyouarefr
eeto
i
ncludesomeifyouwishtoi
ncr
easereadabi
li
ty.
Datatypesincr ef
ertoanex t
ensi
vesystem usedfor
decl
ari
ngv ar
iablesorf unct
ionsofdif
fer
enttypes.The
ty
pe ofa v ar
iable deter
mines how much space it
occupi
esi nstorageandhow t hebitpatt
ernstoredis
i
nterpr
eted.
Thet
ypesi
nCcanbecl
assi
fi
edasf
oll
ows−
Sr
.No. Ty
pes&Descr
ipt
ion

1 Basi
cTy
pes
They are ari
thmeti
ct ypes and ar
ef ur
ther
cl
assif
ied int
o:( a) i
nteger ty
pes and (b)
fl
oat
ing-poi
nttypes.
2 Enumer
atedt
ypes
Theyareagai
nari
thmet i
ct ypesandt heyare
usedtodefi
nevari
ablesthatcanonl yassign
cert
aindi
scr
etei
ntegervaluesthroughoutthe
progr
am.

3 Thet
ypev
oid
Thety
pespeci
ferv
i oidi
ndi
cat
est
hatnov
alue
i
savai
labl
e.

4 Der
ivedt
ypes
Theyinclude(a)Point
ert
ypes,(
b)Arr
ayty
pes,
(c)St
r ucturetypes,(
d)Uniontypesand(e)
Funct
iont ypes.
The array types and str
uct
uret ypes arer ef
err
ed
coll
ecti
vel
y as the aggr
egatetypes.The t ype ofa
funct
ionspecifi
esthet
ypeofthef
unct i
on'sr
eturnval
ue.
Wewi l
lseethebasi ctypesint
hef ol
lowi
ngsect i
on,
whereasot hertypeswil
lbecoveredi ntheupcoming
chapter
s.
I
ntegerTy
pes
Thef ol
l
owi ng t
abl
eprov
idesthedet
ail
sofstandard
i
ntegertypeswitht
hei
rstor
agesi
zesandval
ueranges

Ty
pe St
orage Val
uer
ange
size

Char 1by
te -
128t
o127or0t
o255
unsigned 1by
te 0t
o255
char

si
gned 1by
te -
128t
o127
char

-
32,768to32,
767or-
2or4
I
nt 2,
147,
483,
648to
by
tes
2,
147,
483,
647

unsi
gned 2or4 0t
o65,535or0to
i
nt by
tes 4,
294,967,
295

Shor
t 2by
tes -
32,
768t
o32,
767

unsigned 2by
tes 0t
o65,
535
short

Long 8by
tes -
9223372036854775808to
9223372036854775807

unsi
gned 8by
tes 0t
o18446744073709551615
l
ong

To gett heexactsi zeofat ypeorav ari


abl
eon a
parti
cul
arpl at
for
m,y ou can use t
hesizeofoperat
or.
Theexpr onssi
essi zeof(
type)y
ieldst
hest or
agesizeof
theobjectortypeinby tes.Gi
venbelow i
sanexampl e
to getthesi zeofv ari
oust y
peonamachi neusing
di
ff
erentconst
antdef
inedi
nli
mit
s.hheaderf
il
e−
#i
ncl
ude<stdi
o.h>
#i
ncl
ude<stdl
i
b. h>
#i
ncl
ude<l
imits.h>
#i
ncl
ude<fl
oat.h>

i
ntmai
n(i
ntar
gc,
char
**ar
gv){

pr
int
f("
CHAR_BIT :%d\ n" ,CHAR_ BI T);
pr
int
f("
CHAR_MAX :%d\ n",CHAR_ MAX) ;
pr
int
f("
CHAR_MI N :%d\ n" ,CHAR_ MIN);
pr
int
f("
INT_MAX :%d\ n",INT_ MAX) ;
pr
int
f("
INT_MIN :%d\ n", I
NT_ MI N) ;
pr
int
f("
LONG_MAX :%l d\ n",(long)LONG_ MAX) ;
pr
int
f("
LONG_MI N :%ld\ n",(long)LONG_ MIN);
pr
int
f("
SCHAR_ MAX :%d\ n", SCHAR_ MAX) ;
pr
int
f("
SCHAR_ MIN :%d\ n" ,SCHAR_ MIN);
pr
int
f("
SHRT_MAX :%d\ n",SHRT_ MAX) ;
pr
int
f("
SHRT_MI N :%d\ n",SHRT_ MI N);
pr
int
f("
UCHAR_ MAX :%d\ n", UCHAR_ MAX);
pr
int
f("
UINT_MAX :%u\ n",(unsi gnedi nt)
UINT_MAX);
pr
int
f("
ULONG_ MAX :%l u\ n",(unsi gnedlong)
ULONG_ MAX);
pr
int
f("
USHRT_MAX :%d\ n",(unsi gnedshor t
)
USHRT_MAX) ;

r
etur
n0;
}
Wheny oucompil
eandexecut
etheabov
epr
ogr
am,i
t
pr
oducesthef
oll
owingr
esul
tonLi
nux−
CHAR_
BIT :8
CHAR_ MAX :127
CHAR_ MIN :- 128
INT_MAX :2147483647
INT_MIN :- 2147483648
LONG_ MAX :9223372036854775807
LONG_ MIN :- 9223372036854775808
SCHAR_ MAX :127
SCHAR_ MIN :- 128
SHRT_ MAX :32767
SHRT_ MIN :- 32768
UCHAR_ MAX :255
UINT_MAX :4294967295
ULONG_ MAX :18446744073709551615
USHRT_ MAX :65535
Float
ing-
PointTypes
The fol
l
owing tabl
e prov
ide t
he det
ail
s ofstandard
fl
oat
ing-
poi
nttypeswithstor
agesi
zesandv al
ueranges
andthei
rpr
ecisi
on−
Ty
pe St
orage Val
uer
ange Pr
eci
sion
size

f
loat 4by
te 1.2E-38t
o 6deci
mal
3.4E+38 pl
aces

doubl
e 8by
te 2.3E-308t
o 15decimal
1.7E+308 pl
aces

l
ong 10by
te 3.4E-4932t
o 19decimal
doubl
e 1.1E+4932 pl
aces
Theheaderf il
efloat.
hdefi
nesmacr osthatal
l
owy outo
uset hesev al
uesandot herdetai
lsaboutt hebinar
y
represent
ati
onofr ealnumbersiny ourpr
ograms.The
foll
owingexampl epr i
ntsthest
oragespacetakenbya
fl
oatt y
peandi t
sr angeval
ues−

#i
ncl
ude<stdi
o.h>
#i
ncl
ude<stdl
i
b. h>
#i
ncl
ude<l
imits.h>
#i
ncl
ude<fl
oat.h>

i
ntmai
n(i
ntar
gc,
char
**ar
gv){

pr
int
f("
Storagesizeforfl
oat:%d\ n",si
zeof(f
loat)
);
pr
int
f("
FLT_ MAX :%g\ n"
,(fl
oat)FLT_ MAX) ;
pr
int
f("
FLT_ MIN :%g\ n",(
fl
oat)FLT_ MIN);
pr
int
f("
-FLT_MAX :%g\ n"
,(fl
oat )-FLT_MAX) ;
pr
int
f("
-FLT_MI N :%g\ n",(
fl
oat )-FLT_MIN) ;
pr
int
f("
DBL_ MAX :%g\ n",
(doubl e)DBL_ MAX) ;
pr
int
f("
DBL_ MI N :%g\ n",(
doubl e)DBL_ MIN) ;
pr
int
f("
-DBL_ MAX :%g\ n",
(doubl e)-DBL_MAX) ;
pr
int
f("
Precisionval
ue:%d\n",FLT_ DIG);

r
etur
n0;
}
Wheny oucompil
eandexecut
etheabov
epr
ogr
am,i
t
pr
oducesthef
oll
owingr
esul
tonLi
nux−
Storagesi
zef
orfl
oat: 4
FLT_ MAX :3. 40282e+38
FLT_ MI
N :1. 17549e-38
-FLT_MAX :- 3.40282e+38
-
FLT_MI N :- 1.
17549e-38
DBL_MAX :1. 79769e+308
DBL_MI N :2. 22507e-308
-
DBL_ MAX :- 1.79769e+308
Preci
sionv
alue:6
ThevoidType
Thevoi
dtypespeci
fi
esthatnoval
uei
sav
ail
abl
e.I
tis
usedi
nthr
eeki
ndsofsit
uati
ons−
Sr
.No. Ty
pes&Descr
ipt
ion

1 Funct
ionr
etur
nsasv
oid
Therearev ari
ousfuncti
onsinCwhi chdonot
returnanyv alueory oucansayt heyret
urn
void.Af unct
ionwi t
hnor et
urnvaluehasthe
returnt
ypeasv oi
d.Forexample,
voidexi
t(i
nt
status)
;

2 Funct
ionar
gument
sasv
oid
Therear
evariousfunct
ionsinCwhi chdonot
acceptany parameter
.A f uncti
on wi
th no
paramet
ercanacceptav oid.Forexampl
e,i
nt
rand(
voi
d);

3 Poi
nter
stov
oid
A poi nter of t
ype void *r epresentst he
addressofan obj ect,butnoti t
st y
pe.For
exampl e,a memor yall
ocati
on functionv
oi d
*malloc(size_
tsize);
retur
nsapoi ntertovoid
whichcanbecast edtoanydatat y
pe.
Av ari
ableisnot hi
ngbutanamegi vent oast oragearea
thatourpr ogramscanmani pul
ate.Eachv ari
ableinC
hasa speci fi
ct ype,whi
ch determinest he size and
l
ay outofthev ari
able'
smemor y;
therangeofv al
uesthat
can be st ored withi
nthatmemor y;and t he setof
operati
onst hatcanbeappliedtothev ar
iable.
Thenameofav ari
ablecanbecomposedofl et
ters,
digits,andtheunderscorecharacter.I
tmustbeginwith
eitheral ett
eroranunder score.Upperandl owercase
l
et tersaredist
inctbecauseCi scase- sensi
ti
ve.Based
ont hebasictypesex pl
ainedint hepr evi
ouschapter,
ther ewill
bethefoll
owingbasicv ari
abl
et y
pes−
Sr
.No. Ty
pe&Descr
ipt
ion

1 Char
Typi
call
ya singl
e oct
et(
one by
te)
.Iti
s an
i
ntegert
ype.

2 I
nt
The mostnat
uralsi
ze ofi
ntegerf
ort
he
machi
ne.

3 Fl
oat
Asi
ngl
e-pr
eci
sionf
loat
ingpoi
ntv
alue.

4 Doubl
e
Adoubl
e-pr
eci
sionf
loat
ingpoi
ntv
alue.
5 Voi
d
Repr
esent
stheabsenceoft
ype.
Cpr ogrammi nglanguageal soal
lowst odefinev ari
ous
other types of v ari
ables,which we wi l
lcov er i
n
subsequentchapt erslikeEnumer ati
on,Pointer,Array,
Struct
ure,Union,etc.Fort hi
schapter
,letusst udyonly
basicvariabl
etypes.
Var
iabl
eDef
ini
ti
oni
nC
Av ar
iabl
edefini
tiontel
lsthecompi lerwher eandhow
much storage t
o createf orthe var i
able.A var
iabl
e
def
ini
tionspecif
iesadat at y
peandcont ai
nsal i
stof
oneormor evari
ablesofthattypeasf oll
ows−
t
ypev ar i
able_l
ist
;
Here,ty pemustbeav al
i
dCdat at y
peincl
udi
ngchar ,
w_char ,i nt
,f l
oat,doubl
e,bool,orany user
-def
ined
object;andv ari
able_
li
stmayconsistofoneormor e
i
dent i
fiernames separ ated bycommas.Some v ali
d
declarationsareshownher e−
i
nt i,j
,k;
charc, ch;
fl
oatf,salary;
doubl
ed;
Theli
nei nti,j
,k;declar
esanddefi
nesthevari
abl
esi,j,
andk;whi chinst
ructthecompi
lertocreat
ev ar
iabl
es
namedi ,jandkoft ypei
nt.
Variabl
escanbei ni
ti
ali
zed(assi
gnedanini
ti
alval
ue)i
n
thei
rdeclarat
ion.Thei ni
ti
ali
zerconsi
stsofanequal
signfol
lowedbyaconst antexpr
essi
onasfol
lows−
t
ypev
ari
abl
e_name=v
alue;
Someexampl
esar
e−
intd=3, f=5; //declar
ati
onofdandf .
i
ntd=3, f=5; //defi
nit
ionandi ni
tial
izi
ngdandf .
bytez=22; //defi
nit
ionandi nit
ial
izesz.
charx=' x'; /
/thevari
ablexhast hevalue'
x'
.
Fordef i
niti
onwithoutaninit
ial
izer
:variableswithst
atic
storagedur at
ionareimpli
citl
yinit
ial
izedwi thNULL( al
l
byteshav ethev al
ue0);thei nit
ialvalueofal lother
vari
ablesar eundefi
ned.
Var
iabl
eDecl
arat
ioni
nC
A v ar
iabl e declarat
ion pr ovides assurance to the
compilert hatthereexist
sav ariabl
ewiththegiventype
andnamesot hatthecompi l
ercanpr oceedforfur
ther
compilationwi thoutr
equiri
ngt hecompl etedetai
labout
thevariable.Av ari
abledefinit
ionhasi t
smeani ngatthe
ti
meofcompi lati
on only,thecompi l
erneedsact ual
vari
abl
edef ini
ti
onatt heti
meofl i
nki
ngtheprogram.
Av ariabledeclar at i
on isusef ulwhen you areusi ng
multi
plef i
lesandy oudef i
ney ourvar
iabl
einoneoft he
fi
leswhi chwillbeav ailabl
eatt heti
meofl i
nkingoft he
program.Youwi lluset hekeywordexternt
odecl area
vari
ableatanypl ace.Thoughy oucandeclareav ari
able
multi
plet i
mesi ny ourCpr ogr
am, i
tcanbedef inedonly
oncei nafile,
af unct ion,orablockofcode.
Exampl
e
Trythefol
lowingexample,wherevar
iabl
eshavebeen
decl
aredatt hetop,buttheyhavebeendefinedand
i
niti
ali
zedi
nsi
det hemainfunct
ion−

#i
ncl
ude<st
dio.
h>
/
/Variabl
edecl
arat
ion:
i
nta,b;
i
ntc;
f
loatf;

i
ntmai
n(){

/
*v ar
iabl
edef
ini
ti
on:
*/
i
nta,b;
i
ntc;
f
loatf;

/*act
ual
ini
ti
ali
zat
ion*
/
a=10;
b=20;

c=a+b;
pr
int
f("
val
ueofc:
%d\
n",
c);

f=70.0/3.0;
pr
int
f("
valueoff:
%f\
n",
f);

ret
urn0;
}
When the abov
e code i
s compi
l
ed and ex
ecut
ed,i
t
pr
oducesthefol
lowi
ngresul
t−
val
ueofc:30
val
ueoff:23.333334
The same conceptappl i
es on funct
ion decl
arat
ion
whereyoupr ovi
deaf uncti
onnameatt heti
meofi ts
decl
arat
ion and its act
ualdefi
niti
on can be given
any
wher
eel
se.Forexampl
e−
/
/functi
ondecl
arat
ion
i
ntfunc(
);

i
ntmai
n(){

//f
uncti
oncal
l
i
nti=func(
);
}

//functi
ondef
ini
ti
on
i
ntf unc(
){
r
eturn0;
}
LvaluesandRval
uesinC
Ther
ear
etwoki
ndsofexpr
essi
onsi
nC−
 l
val
ue− Expressions that ref
er to a memor y
l
ocati
onarecalled"lv
alue"expressi
ons.Anl
v al
ue
mayappearasei t
hertheleft-
handorr i
ght
-hand
si
deofanassignment.
 r
value−Thet ermrval
uerefer
stoadat av al
uet hat
i
sst oredatsomeaddr essinmemor y.Anr val
uei s
anexpr essi
onthatcannothaveavalueassignedt o
i
twhi chmeansanr val
uemayappearont her i
ght-
hand si de butnoton the lef
t-
hand side ofan
assignment .
Variabl
esarelval
uesandsot heymayappearontheleft
-hand side ofan assignment .Numericli
ter
als are
rval
uesandsot heymaynotbeassi gnedandcannot
appearon t he lef
t-
hand side.Take a look att he
foll
owingval
idandinval
idstatement
s−
i
ntg=20;
//v
ali
dst
atement

10=20;//i
nval
i
dst
atement
;woul
dgener
atecompi
l
e-
ti
meerr
or

CDat
aTy
pes

InCprogramming, dataty
pesaredeclar
ationsf
or
vari
abl
es.Thi
sdet erminesthetypeandsizeofdat
a
associ
atedwi
thv ariabl
es.Forexample,

i
ntmy
Var
;
Her
e,myVarisavar
iabl
eofi
nt(
int
eger
)ty
pe.Thesi
ze
ofi
nti
s4by t
es.

Basi
cty
pes
Here'
sat
ablecontai
ningcommonl
yusedt
ypesi
nC
pr
ogrammingforqui
ckaccess.

Format
Ty
pe Si
ze(
byt
es)
Speci
fi
er

I
nt atl
east2,
usual
l
y4 %d

Char 1 %c

Fl
oat 4 %f
Format
Ty
pe Si
ze(
byt
es)
Speci
fi
er

Doubl
e 8 %l
f

shor
tint 2usual
l
y %hd

unsi
gnedi
nt atl
east2,
usual
l
y4 %u

l
ongi
nt atl
east4,
usual
l
y8 %l
i

l
ongl
ongi
nt atl
east8 %l
l
i

unsi
gnedl
ongi
nt atl
east4 %l
u

unsi
gnedl
ong
atl
east8 %l
l
u
l
ongint

si
gnedchar 1 %c

unsi
gnedchar 1 %c

atl
east10,
usual
l
y12
l
ongdoubl
e %Lf
or16
i
nt
Int
egersarewholenumber sthatcanhavebot
hz er
o,
posit
iveandnegati
vevaluesbutnodecimalval
ues.For
example,0,-
5,10
Wecanusei ntfordecl
aringanintegerv
ari
abl
e.
i
nti
d;
Here,i
disavar
iabl
eoftypeinteger
.
Youcandecl
aremultipl
evari
ablesatoncei
nC
progr
amming.Forexample,

i
nti
d,age;
Thesizeofinti
susuall
y4by t
es(
32bi
ts)
.And,
itcan
take232di
sti
nctst
atesfrom -
2147483648to2147483647.

f
loatanddoubl
e
f
loatanddoubl
ear
eusedt
ohol
dreal
number
s.
fl
oatsal
ary;
doubl
eprice;
InC,fl
oat
ing-
pointnumberscanal
sober
epr
esent
edi
n
exponent
ial
.Forexample,

f
loatnor
mal
i
zat
ionFact
or=22.
442e2;
What'
sthedi
ff
erencebet
weenf l
oatanddoubl
e?
Thesi
zeoffl
oat(si
ngl
epreci
sionfl
oatdat
atype)i
s4
byt
es.Andthesi
zeofdoubl
e(doubl
epr
eci
sionf
loat
dat
atype)i
s8bytes.

char
Keywordcharisusedfordecl
ari
ngchar
act
ert
ype
var
iabl
es.Forexample,
chart
est='
h'
;
Thesi
zeoft
hechar
act
erv
ari
abl
eis1by
te.

Al
lfunct
ionsl
i
kepr
int
f,scanfi
nsi
deconnect
edandcal
l
bymain
andmai
ncal
lbyoper
ati
ngsy
stem
ret
urnisusedt
ot el
lost
hatpr
ogr
am compl
eted
successf
ull
yornot
v
oid
voidisani ncompl etetype.Itmeans" nothing"or"no
type".Youcant hi
nkofv oidasabsent .
Forexampl e,i
faf uncti
oni snotreturni
ngany thi
ng,it
s
returntypeshoul dbev oid.
Not ethat,youcannotcr eatev ar
iablesofvoidt y
pe.
Voiddat at ypespecifi
est hatnov al
uedat aisavail
able
I
ti suse3ki ndofsituat
ions
Funct i
onr etur
nasv oi
d
VoidMy Function(
);
Functi
onargumentasv oi
d
I
ntMy Funct
ion(void)
;
Point
erstovoid
Void*
vauge_pointer

shor
tandl
ong
Ify
ouneedtousealargenumber
,youcanuseat
ype
speci
fi
erl
ong.Her
e'show:
l
onga;
l
ongl
ongb;
l
ongdoubl
ec;
Herevar
iablesaandbcanst oreint
egerval
ues.
And,ccanst or
eafl
oati
ng-pointnumber.
I
fyouaresur e,
onl
yasmal li
nteger([
−32,
767,
+32,
767]range)wi
llbeused,youcanuseshort.
shor
td;

Youcanalwayscheckthesi
zeofav
ari
abl
eusi
ng
thesi
zeof
()oper
ator.
#incl
ude<stdio.
h>
i
ntmai n(){
shorta;
l
ongb;
l
ongl ongc;
l
ongdoubl ed;

pr
int
f("
sizeofshor
t=%dby
tes\
n",
sizeof
(a)
);
pri
ntf
("si
zeofl
ong=%dby t
es\
n",sizeof(
b));
pri
ntf
("si
zeofl
ongl
ong=%dby tes\n",si
zeof(c)
);
pri
ntf
("si
zeofl
ongdoubl
e=%dby tes\n",
sizeof(
d))
;
ret
urn0;
}

si
gnedandunsi
gned
InC,signedandunsi
gnedar
et y
pemodi f
iers.Youcan
alt
erthedatastor
ageofadatatypebyusingthem.For
exampl e,
unsi
gnedi
ntx;
i
nty;
Here,
thevari
ablexcanholdonlyzer
oandpositi
ve
val
uesbecausewehav eusedtheunsignedmodif
ier
.
Consi
deri
ngthesizeofinti
s4by t
es,vari
abl
eycanhold
val
uesfr
om -231to231-
1,wher
easvari
ablexcanhold
32
val
uesfr
om 0t o2 -1.

Ot
herdat
aty
pesdef
inedi
nCpr
ogr
ammi
ngar
e:
 bool
Type
 Enumer
atedt
ype
 Compl
ext
ypes
Der
ivedDat
aTy
pes
Datatypesthatarederi
vedf
rom f
undament
aldatat
ypes
areder
ivedtypes.Forexampl
e:ar
rays,
poi
nter
s,f
uncti
on
ty
pes,struct
ures,et
c.

Dat
aty
pei
nc

Pri
marydatat
ype
Secondar
ydat
atype

Primarydat
aty
pe
.
integer
.
float
.
doubl e
.
char act
er
.
void

Secondar
ydat
aty
pe

Arr
ay
Point
er
Str
uctur
e
uni
on
Enum et
c
I
nt egertype(int)tostoreanumer icv al
uei nprogram i
t
takespace2by t
einmemor y
Char acterty
pe( char)tostoreachar actervaluein
progr am i
ttake1by tespaceinmemor y
Floatt y
pe ( f
loat)tostor
edecimal valuesi nour
progr am i
ttake4by tespaceinmemor y
Doubl etype(doubl e)sameasf l
oatonl ythediff
erence
i
si ttakemor espacei nmemor y8by te
Voi d( void) voidisaempt ydatat y
peweusev oid
whenwedef i
nef unction

Modifi
ers:wecanchanget hesi
zeandrangeofbasi
c
dataty
pebyusi ngmodi fi
ers
.
signmodi fi
ers:
itchangest her
angeofdatat
ype
(si
nged, unsi
nged)

.
sizemodi
fi
ers:
itchangest
hesi
zeofdat
aty
pe.(
shor
t,
l
ong)

Inta; 2by
te
Shorti
nta; 2byt
e
Longinta; 4by t
e

weusesizemodif
ier
sint
egerdat
aty
peanddoubl
enot
oncharorfl
oat
v
ari
abl
eandconst
ant
:

Var
iabl
es
I
npr
ogramming,
avar
iabl
eisacont
ainer(
stor
agear
ea)
t
ohol
ddata.
Toi ndi
catethest
oragearea,eachvari
ableshouldbe
givenauniquename( i
dentif
ier
).Vari
abl
enamesar ejust
thesy mboli
crepr
esentat
ionofamemor ylocat
ion.For
exampl e:
i
ntpl
ayer
Scor
e=95;
Here,player
Scorei
sav ari
abl
eofintt
ype.Her
e,the
var
iableisassi
gnedani nt
egerv
alue95.
Thevalueofav ari
abl
ecanbechanged,hencethename
var
iable.

charch='
a';
//somecode
ch='l'
;

Rul
esf
ornami
ngav
ari
abl
e
1.
Avar
iabl
enamecanonl yhavelet
ter
s(bothupper
case
andl
owercasel
ett
ers)
,digi
tsandunderscor
e.
2.
Thefi
rstlet
terofav
ari
abl
eshoul
dbeei
theral
ett
eror
anunderscore.
3.
Ther
eisnor uleonhowlongavar
iabl
ename( i
dent
if
ier
)
canbe.Howev er
,youmayruni
ntoprobl
emsinsome
compil
ersifthevar
iabl
enamei
slongerthan31
char
acter
s.
Note:Youshoul dalwaystr
yt ogiv
emeaningfulnames
tovari
ables.Forexample:fi
rstNameisabettervar
iabl
e
namet hanfn.
Cisast r
onglytypedlanguage.Thismeansthatthe
vari
abl
et ypecannotbechangedoncei ti
sdeclared.For
example:

i
ntnumber=5; /
/int
egerv
ari
abl
e
number=5.
5; //err
or
doubl
enumber
; //err
or
Here,thetypeofnumberv ariabl
eisint.Youcannot
assignaf l
oat i
ng-poi
nt(decimal)val
ue5. 5tothi
s
vari
able.Also,youcannotr edefi
nethedat aty
peofthe
vari
abletodoubl e.Bytheway ,
tostorethedecimal
val
uesi nC, youneedt odeclareit
stypet o
eit
herdoubl eorfloat
.

Li
ter
als
Lit
eralsaredatausedf orrepresent
ingf
ixedval
ues.
Theycanbeuseddi rectl
yinthecode.For
exampl e:1,2.
5,'
c'etc.
Here,1, 2.
5and'c'areli
teral
s.Why ?Youcannotassi
gn
dif
ferentvaluest
ot heseterms.
1.I
nteger
s
Anint
egerisanumer i
clit
eral(
associat
edwithnumber
s)
wit
houtanyfract
ional
orex ponenti
alpart
.Therear
e
thr
eetypesofint
egerli
ter
alsinCpr ogramming:
 deci
mal
(base10)
 oct
al(
base8)
 hexadeci
mal
(base16)

Var
iabl
es
I
npr
ogramming,
avar
iabl
eisacont
ainer(
stor
agear
ea)
t
ohol
ddata.
Toi ndi
catethest
oragearea,eachvari
ableshouldbe
givenauniquename( i
dentif
ier
).Vari
abl
enamesar ejust
thesy mboli
crepr
esentat
ionofamemor ylocat
ion.For
exampl e:
i
ntpl
ayer
Scor
e=95;
Here,player
Scorei
sav ari
abl
eofintt
ype.Her
e,the
var
iableisassi
gnedani nt
egerv
alue95.
Thevalueofav ari
abl
ecanbechanged,hencethename
var
iable.

charch='
a';
//somecode
ch='l'
;
Rul
esf
ornami
ngav
ari
abl
e
1.
Avar
iabl
enamecanonl yhavelet
ter
s(bothupper
case
andl
owercasel
ett
ers)
,digi
tsandunderscor
e.
2.
Thefi
rstlet
terofav
ari
abl
eshoul
dbeei
theral
ett
eror
anunderscore.
3.
Ther
eisnor uleonhowlongavar
iabl
ename( i
dent
if
ier
)
canbe.Howev er
,youmayruni
ntoprobl
emsinsome
compil
ersifthevar
iabl
enamei
slongerthan31
char
acter
s.
Note:Youshoul dalwaystr
yt ogiv
emeaningfulnames
tovari
ables.Forexample:fi
rstNameisabettervar
iabl
e
namet hanfn.
Cisast r
onglytypedlanguage.Thismeansthatthe
vari
abl
et ypecannotbechangedoncei ti
sdeclared.For
example:

i
ntnumber=5; /
/int
egerv
ari
abl
e
number=5.
5; //err
or
doubl
enumber
; //err
or
Here,thetypeofnumberv ariabl
eisint.Youcannot
assignaf l
oat i
ng-poi
nt(decimal)val
ue5. 5tothi
s
vari
able.Also,youcannotr edefi
nethedat aty
peofthe
vari
abletodoubl e.Bytheway ,
tostorethedecimal
val
uesi nC, youneedt odeclareit
stypet o
eit
herdoubl eorfloat
.
Li
ter
als
Lit
eralsaredatausedf orrepresent
ingf
ixedval
ues.
Theycanbeuseddi rectl
yinthecode.For
exampl e:1,2.
5,'
c'etc.
Here,1, 2.
5and'c'areli
teral
s.Why ?Youcannotassi
gn
dif
ferentvaluest
ot heseterms.

1.I
nteger
s
Anint
egerisanumer i
clit
eral(
associat
edwithnumber
s)
wit
houtanyfract
ional
orex ponenti
alpart
.Therear
e
thr
eetypesofint
egerli
ter
alsinCpr ogramming:
 deci
mal
(base10)
 oct
al(
base8)
 hexadeci
mal
(base16)
 Forexampl
e:

 Deci
mal
:0,
-9,
22et
c
 Oct
al:
021,
077,
033et
c
 Hexadeci
mal
:0x7f
,0x2a,
0x521et
c

 I
nCpr ogrammi
ng,oct
alst
art
swi
tha0,
and
hexadeci
malst
art
switha0x.


 2.Fl
oat
ing-
poi
ntLi
ter
als
 Afloat
ing-poi
ntli
teral
isanumer i
clit
eralt
hathas
ei
therafracti
onalform oranexponentfor
m.For
example:

 -
2.0
 0.
0000234
 -
0.22E-
5

 Not 5=10-5
e:E-

 3.Char
act
ers
 Acharacterli
ter
aliscreatedbyencl
osi
ngasingl
e
char
acterinsi
desinglequot at
ionmar
ks.For
example:'
a','
m','
F'
,'2'
,'
}'etc.

 4.EscapeSequences
 Sometimes,iti
snecessar
ytousecharact
ersthat
cannotbetypedorhasspeci
almeaninginC
progr
ammi ng.Forexampl
e:newl
ine(
enter)
,tab,
questi
onmar ketc.
 Inordert
ouset
hesechar
act
ers,
escapesequences
areused.
EscapeSequences

EscapeSequences Char
act
er

\
b Backspace

\
f For
mfeed

\
n Newl
i
ne

\
r Ret
urn

\
t Hor
izont
alt
ab

\
v Ver
ti
cal
tab

\
\ Backsl
ash

\
' Si
ngl
equot
ati
onmar
k

\
" Doubl
equot
ati
onmar
k

\
? Quest
ionmar
k

\
0 Nul
lchar
act
er


 Forexampl
e:\nisusedforanewli
ne.The
backsl
ash\causesescapefr
om thenormalway
thechar
act
ersarehandledbythecompil
er.

 5.St
ri
ngLi
ter
als
 Ast
ri
ngli
teral
isasequenceofcharact
ersencl
osed
i
ndoubl
e-quot
emarks.Forexample:

 "
good" /
/st
ri
ngconst
ant
 "
" /
/nul
lst
ri
ngconst
ant
 " " /
/st
ri
ngconst
antofsi
xwhi
tespace
 "x" /
/st
ri
ngconst
anthav
ingasi
ngl
e
charact
er.
 "
Ear
thi
sround\
n" /
/pr
int
sst
ri
ngwi
thanewl
i
ne

 Const
ant
s
 I
fyouwanttodefi
neavari
ablewhoseval
uecannot
bechanged,
youcanusetheconstkey
word.Thi
s
wil
lcr
eateaconst
ant
.Forexample,
 constdoubl
ePI=3.
14;
 Not
ice,
wehaveaddedkeywordconst
.
 Her
e,PIisasy
mboli
cconstant
;it
sval
uecannotbe
changed.
 constdoublePI=3.
14;
 PI=2.9;//
Error

InCpr ogramming,
pri
ntf(
)isoneoft
hemai
noutput
functi
on.Thefunct
ionsendsfor
matt
edout
putt
ot he
screen.Forexampl
e,

Exampl
e1:
COut
put

#i
nclude<stdio.
h>
i
ntmai n()
{
//Displ
aysthestr
inginsi
dequot
ati
ons
pri
ntf(
"CProgramming");
ret
urn0;
}
Out
put
CPr
ogr
ammi
ng
Howdoest
hispr
ogr
am wor
k?
 Allv
ali
dCpr ogr
amsmustcontai
nthemain(
)funct
ion.
Thecodeexecuti
onbegi
nsfr
om thest
artof
themain(
)funct
ion.
 Theprintf
()isalibr
aryfunctiont osendf ormat t
edout
put
tothescreen.Thef uncti
onpr intsthestringinsi
de
quotat
ions.
 Tousepr i
ntf()i
nourpr ogram, weneedt o
i
ncludestdio.hheaderfil
eusi ngt he#include
<stdi
o.h>statement.
 Thereturn0;statementinsidet hemai n()functi
onist
he
"Exi
tstat
us"oft heprogram.I t'
sopt i
onal.

Exampl
e2:
Int
egerOut
put

#i
nclude<stdio.
h>
i
ntmai n()
{
i
nttestI
nteger=5;
pri
ntf(
"Number=%d",
test
Int
eger
);
ret
urn0;
}
Out
put
Number=5
Weuse%dformatspeci
fiert
opri
nti
ntt
ypes.Her
e,
t
he%dinsi
dethequotat
ionswil
lber
epl
acedbythe
val
ueoft
est
Int
eger.
Exampl
e3:
floatanddoubl
eOut
put

#i
nclude<stdi
o.h>
i
ntmai n()
{
fl
oatnumber1=13.5;
doublenumber2=12.
4;

pri
ntf
("number
1=%f
\n",
number1)
;
pri
ntf
("number
2=%l
f"
,number
2);
ret
urn0;
}
Out
put
number
1=13.
500000
number
2=12.
400000
Topri
ntfl
oat
,weuse%fformatspeci
fi
er.Si
mil
arl
y,we
use%lft
opri
ntdoubl
eval
ues.

Exampl
e4:
Pri
ntChar
act
ers

#i
nclude<st dio.h>
i
ntmai n()
{
charchr=' a';
pri
ntf(
"charact er=%c.
",chr
);
ret
urn0;
}
Out
put
char
act
er=a
Topr
intchar
,weuse%cf
ormatspeci
fi
er.

CI
nput
InCpr ogr
ammi ng,scanf(
)isoneofthecommonlyused
functi
ontotakeinputfrom t
heuser.
Thescanf()funct
ionreadsformatt
edinputf
rom t
he
standardi
nputsuchaskey boards.

Exampl
e5:
Int
egerI
nput
/Out
put

#i
nclude<st di
o.h>
i
ntmai n()
{
i
nttestInt
eger;
pri
ntf(
"Enteraninteger:"
);
scanf(
"%d" ,
&testI
nteger)
;
pri
ntf(
"Number=%d" ,t
estI
nteger
);
ret
urn0;
}
Out
put
Ent
erani
nteger
:4
Number=4
Her
e,wehaveused%dfor
matspecif
ieri
nside
t
hescanf
()f
uncti
ontot
akeinti
nputf
rom theuser
.
Whentheuserent ersanint
eger,i
tisstoredin
thet
estI
ntegervariabl
e.
Noti
ce,t
hatwehav eused&test
Integerinsi
descanf (
).I
t
i
sbecause&t est
Integerget
stheaddr essoftestI
nteger
,
andthevalueenteredbytheuserisstoredinthat
addr
ess.

Exampl
e6:
FloatandDoubl
eInput
/Out
put

#i
nclude<stdi
o.h>
i
ntmai n()
{f loatnum1;
doublenum2;

pri
ntf
("Ent
eranumber :"
);
scanf
("%f"
,&num1) ;
pri
ntf
("Ent
eranothernumber
:")
;
scanf
("%lf
",&num2);

pr
int
f("
num1=%f
\n",
num1);
pr
int
f("
num2=%l
f"
,num2)
;

r
etur
n0;
}
Out
put
Ent
eranumber:12.
523
Ent
eranot
hernumber:
10.
2
num1=12.523000
num2=10.200000
Weuse%fand%l fformatspeci
fier
f
orf
loatanddoublerespect
ivel
y.

Exampl
e7:
CChar
act
erI
/O

#i
nclude<stdio.
h>
i
ntmai n()
{
charchr;
pri
ntf(
"Ent
eracharact
er:"
);
scanf(
"%c",
&chr)
;
pri
ntf(
"Youenter
ed%c.",
chr)
;
ret
urn0;
}
Out
put
Ent
eracharact
er:
g
Youent
eredg.
Whenachar act
erisent
eredbytheuserint
heabov
e
pr
ogram,thecharact
erit
sel
fisnotstor
ed.I
nst
ead,
an
i
ntegerv
alue(ASCIIval
ue)i
sstored.
Andwhenwedi splaythatval
ueusing%ctextfor
mat,
theenter
edcharacteri
sdispl
ayed.Ifweuse%dt o
displ
aythechar
acter,i
t'
sASCIIval
ueispri
nted.
Exampl
e8:
ASCI
IVal
ue

#i
nclude<stdio.
h>
i
ntmai n()
{
charchr;
pri
ntf(
"Ent
eracharact
er:
");
scanf(
"%c",
&chr)
;

//When%ci sused,
acharact
erisdi
spl
ayed
pri
ntf
("Youent
ered%c.
\n"
,chr
);

//When%di sused,ASCI
Ival
ueisdi
spl
ayed
pri
ntf
("ASCI
Ival
ueis%d.",
chr)
;
ret
urn0;
}
Out
put

Ent
erachar act
er:
g
Youenteredg.
ASCIIv
alueis103.

I
/OMul
ti
pleVal
ues
Here'
showyoucant
akemul
ti
plei
nput
sfr
om t
heuser
anddispl
ayt
hem.

#i
ncl
ude<st
dio.
h>
i
ntmain(
)
{
i
nta;
f
loatb;

pr
int
f("
Ent
eri
ntegerandt
henaf
loat
:")
;

//Taki
ngmultipl
einput
s
scanf(
"%d%f
",&a,&b);

pri
ntf
("Youent
ered%dand%f
",a,
b);
ret
urn0;
}
Out
put
Ent
erintegerandt
henafloat
:-3
3.
4
Youentered-3and3.
400000

I
nCpr ogrammi ng,acharact
erv
ariabl
eholdsASCII
value(anintegernumberbetween0and127)r at
her
thanthatcharacterit
sel
f.Thatv
alueisknownasit'
s
ASCIIv al
ue.
Forexample,t
heASCIIvalueof'A'
is65.
Whatthi
smeansi sthat
,ifyouassign'
A't
oachar acter
var
iabl
e,65isstor
edinthev ar
iabl
erat
herthan'
A'itsel
f.
Pr
ogr
am t
oPr
intASCI
IVal
ue

#i
nclude<stdio.
h>
i
ntmai n(){
charc;
pri
ntf(
"Ent
erachar
act
er:
");
scanf(
"%c",
&c);

//%ddi spl
aystheint
egerval
ueofachar
act
er
//%cdi spl
aystheactual
character
pri
ntf
("ASCIIval
ueof%c=%d" ,
c, c)
;

r
etur
n0;
}

Ent
eracharact
er:
G
ASCIIv
alueofG=71
I
nthispr
ogram,theuseri
saskedtoent eracharacter
.
Thechar
acteri
sstoredi
nvari
ablec.
When%df ormatst
ri
ngisused,71(theASCIIvalueofG)
i
sdispl
ayed.
When%cf or
matstri
ngisused,'
G'i
tselfisdi
splayed.

Deci
sionMaki ngandBranchi
ngstat
ementi
nc:
.
Ifst
atement
.
Switchstatement
.
Conditi
onal oper
atorst
atement
.
Gotost atement
Ci
fSt
atement
Thesy
ntaxoft
hei
fst
atementi
nCpr
ogr
ammi
ngi
s:
i
f(testexpr
essi
on)
{
//statement
stobeexecut
edi
fthet
estex
pressi
oni
s
t
rue
}

Howi
fst
atementwor
ks?
Theifstat
ementevaluat
esthetestexpressioni nsi
de
theparent
hesi
s().
 I
fthetestexpr
essi
oni seval
uatedtotrue,statements
i
nsidethebodyofifareexecut
ed.
 I
fthetestexpr
essi
oni seval
uatedtofalse,statements
i
nsidethebodyofifarenotexecut
ed.

Tolear
nmor eaboutwhent estexpressi
oni
sev
aluat
ed
totr
ue(non-zer
ov al
ue)andfalse(0),
checkr
elat
ionalandlogi
caloperators.
Exampl
e1:
ifst
atement

/
/Pr
ogr
am t
odi
spl
ayanumberi
fiti
snegat
ive

#i
nclude<st
dio.
h>
i
ntmai n(
){
i
ntnumber;

pri
ntf
("Ent
eraninteger
:")
;
scanf
("%d",&number);

/
/t r
ueifnumberislesst
han0
i
f(number<0){
pr
int
f("
Youentered%d.\
n",
number
);
}

pr
int
f("
Thei
fst
atementi
seasy
.")
;

r
etur
n0;
}
Out
put1
Ent
eraninteger:-
2
Youenter
ed- 2.
Theifst
atementiseasy
.
Whent heuserent
ers-2,
thetest
expressi
onnumber<0iseval
uatedtotrue.Hence,
You
entered-
2isdispl
ayedonthescreen.
Output2
Ent
eraninteger
:5
Theifst
atementiseasy
.
Whent heuserent er
s5,t
het
estexpressi
onnumber<0i
s
evaluat
edtof al
seandthest
atementinsi
dethebody
ofifisnotexecuted

Ci
f.
..
elseSt
atement
Theifst
atementmayhav eanopt
ional
elsebl
ock.The
synt
axoftheif
..
elsest
atementi
s:
i
f( testexpr
essi
on){
//stat
ementstobeexecut
edi
fthet
estexpr
essi
oni
s
true
}
else{
//stat
ementstobeexecut
edi
fthet
estexpr
essi
oni
s
false
}

Howi
f.
..
elsest
atementwor
ks?
I
fthet
estexpr
essi
oni
sev
aluat
edt
otr
ue,
 statementsinsidethebodyofi
far eexecuted.
 statementsinsidethebodyofelseareskippedfr
om
execution.
Ifthetestexpressi
oniseval
uatedtofalse,
 st
atement
sinsi
det
hebodyofel
seareexecut
ed
 st
atement
sinsi
det
hebodyofi
fareski
ppedfrom
execut
ion.

Exampl
e2:
if.
..
elsest
atement

/
/Checkwhet
herani
ntegeri
soddorev
en

#i
nclude<stdio.
h>
i
ntmai n(){
i
ntnumber ;
pri
ntf(
"Ent
eraninteger
:")
;
scanf(
"%d",&number);

//Trueiftheremai
nderis0
i
f( number %2==0){
pri
ntf
("%disaneveninteger
."
,number
);
}
else{
pri
ntf
("%disanoddinteger.
",
number)
;
}

r
etur
n0;
}
Out
put
Enterani
nteger:
7
7isanoddi nt
eger.
Whent heuserenters7,t
hetest
expressionnumber%2==0iseval
uatedtofalse.Hence,
thestatementinsi
dethebodyofelseisexecuted.

Ci
f.
..
elseLadder
Thei f.
..
elsestatementexecutestwodiff
erentcodes
dependi nguponwhet herthetestexpr
essionistrueor
false.Somet imes,achoi
cehast obemadef rom more
than2possi bi
li
ti
es.
Thei f.
..
elseladderal
lowsy outocheckbetweenmul ti
ple
testexpr essi
onsandexecut edif
fer
entstatements.

Sy
ntaxofi
f.
..
elseLadder

i
f(testexpr essi
on1){
//st atement(s)
}
el
sei f(t
estexpression2){
//st atement(s)
}
el
sei f(testexpressi
on3){
//st atement(s)
}
.
.
el
se{
//st
atement
(s)
}

Exampl
e3:
Cif
..
.el
seLadder

/
/Pr
ogr
am t
orel
atet
woi
nteger
susi
ng=,
>or<sy
mbol

#i
nclude<stdio.
h>
i
ntmai n(){
i
ntnumber 1,number2;
pri
ntf(
"Ent
ertwoi nt
eger
s:")
;
scanf(
"%d%d" ,&number1,
&number
2);

/
/checksift
hetwoint
egersar
eequal.
i
f(
number 1==number2){
pr
int
f("
Resul
t:%d=%d",
number
1,number
2);
}

//
checksifnumber1i
sgreatert
hannumber
2.
el
seif(number1>number2){
pr
int
f("
Resul
t:%d>%d",number1,
number
2);
}

//
checksifbot
htestexpr
essionsar
efal
se
el
se{
pr
int
f("
Resul
t:%d<%d",number1,
number
2);
}

r
etur
n0;
}
Out
put
Entert
woint
eger
s:12
23
Result
:12<23

Nest
edi
f.
..
else
I
tispossi
bletoincl
udeanif.
..
elsest
atementi
nsi
det
he
bodyofanotheri
f..
.el
sest
atement.

Exampl
e4:
Nest
edi
f.
..
else
Thisprogram gi
venbelowr
elat
est wointegersusi
ng
ei
ther<,>and=si mil
artot
heif
..
.elseladder'
sexample.
Howev er,
wewi ll
useanestedi
f..
.elsestat
ementto
sol
v et
hisproblem.
#i
nclude<stdio.
h>
i
ntmai n(){
i
ntnumber 1,number2;
pri
ntf(
"Ent
ertwoi nt
eger
s:")
;
scanf(
"%d%d" ,&number1,
&number
2);

i
f(number
1>=number
2){
i
f( number1==number2){
print
f("
Resul
t:%d=%d",
number1,
number2);
}
else{
print
f("
Resul
t:%d>%d",number
1,number2)
;
}
}
else{
print
f("
Resul
t:%d<%d",
number1,number
2);
}

r
etur
n0;
}

Ifthebodyofanif
..
.el
sest
atementhasonlyone
statement
,youdonotneedtousebracket
s{}.
Forexample,t
hiscode

i
f(a>b){
pr
int
("
Hell
o")
;
}
pr
int
("Hi
")
;
i
sequi
val
entt
o

i
f(a>b)
pr
int
("
Hell
o")
;
pr
int
("Hi
")
;
Condi
ti
onal
oper
ator
:
Sy
ntax:
(condi
ti
on)
?Expr
essi
on1:
Expr
essi
on2;
(
condi
ti
on)
?Tr
ue:
Fal
se;
Expr
intgr
eat
erv
alue

mai
n()

i
nta,
b,
c;

pr
int
f("
Ent
erf
ir
stnumber
");

scanf
("%d"
,&a)
;

pr
int
f("
Ent
ersecondnumber
");

scanf
("%d"
,&b)
;

c=(
a>b)
?a:
b;

pr
int
f("
Grat
erv
aluei
s%d"
,c)
;

r
etur
n0;

}
I
nprogramming,
aloopi
susedt
orepeatabl
ockofcode
unt
ilt
hespeci
fi
edcondi
ti
oni
smet.
Cpr
ogr
ammi
nghast
hreet
ypesofl
oops:
1.
forl
oop
2.
whi
l
eloop
3.
do.
..
whi
l
eloop
Wewi l
ll
ear
naboutforl
oopint
hist
utor
ial
.Inthenext
t
utor
ial
,wewil
ll
earnaboutwhi
l
eanddo. .
.whi
l
eloop.

forLoop
Thesy nt
axoft
hef
orl
oopi
s:
for(i
niti
ali
zati
onStat
ement
;test
Expr
essi
on;
updateStatement)
{
//statementsinsi
det
hebodyofloop
}

Howf
orl
oopwor
ks?
 Thei
nit
ial
i
zat
ionst
atementi
sexecut
edonl
yonce.
 Then,
thet
estexpr
essi
oni
sev
aluat
ed.I
fthet
est
expressi
onisevaluatedtof alse,theforloopis
terminat
ed.
 Howev er,
ift
het estexpressioni sevaluatedt
otrue,
statementsi
nsidet hebodyoff orloopareexecuted,
and
theupdateexpressionisupdat ed.
 Agai nt
hetestexpressionisev aluated.
Thi
spr
ocessgoesonunti
lthetestexpressi
onisfal
se.
Whent
hetestexpr
essi
onisfal
se,theloopterminat
es.
Tolearnmor eabouttestexpr
essi
on(whenthet
est
expressi
oni seval
uatedtotr
ueandfal
se),
check
outrelat
ionalandlogi
caloper
ator
s.
f
orl
oopFl
owchar
t

Exampl
e1:
forl
oop

//Pri
ntnumbersfr
om 1t
o10
#incl
ude<st
dio.
h>

i
ntmain(
){
i
nti
;

f
or(i=1;i<11;++i
)
{
pr
int
f("
%d",i
);
}
r
etur
n0;
}
Out
put
12345678910
1.
iisinitializedto1.
2.
Thet estexpr essioni <11i sevaluated.Since1l esst han
11i st rue, thebodyoff orloopi sexecut ed.Thiswil
l pri
nt
the1( val ueofi)ont hescreen.
3.
Theupdat estat
ement++i isexecut ed.Now, thevalue
ofi wi l
l be2.Agai n,thetestex pressionisev al
uatedt o
true,andt hebodyoff orloopi sexecut ed.Thiswill
print2( valueofi)ont hescr een.
4.
Agai n, t
heupdat estatement++i isex ecutedandthet est
expressi oni <11i sevaluated.Thispr ocessgoeson
unt i
li becomes11.
5.
Wheni becomes11, i<11wi l
lbef alse,andtheforloop
termi nat es.

Exampl
e2:
forl
oop

//Progr
am tocalcul
atethesum off
ir
stnnat
ural
numbers
//Posit
ivei
ntegers1,
2,3.
..
nareknownasnat
ural
numbers

#i
ncl
ude<st
dio.
h>
i
ntmain(
)
{
i
ntnum,
count
,sum =0;

pri
ntf
("Ent
eraposit
ivei
nteger
:")
;
scanf
("%d",&num)
;

/
/f orl
oopterminat
eswhennum i
slesst
hancount
f
or (
count=1;count<=num;
++count)
{
sum +=count;
}

pr
int
f("
Sum =%d"
,sum)
;

r
etur
n0;
}
Out
put
Ent
eraposi
ti
vei
nteger
:10
Sum =55
Thev al
ueent eredbyt heuseri sstoredi nt he
vari
ablenum.Suppose, t
heuserent ered10.
Thecounti sini
t i
alizedt o1andt hetestex pressi
onis
eval
uated.Sincet het estexpr essioncount <=num (1l
ess
thanorequal to10)i st rue,t
hebodyoff orl oopis
executedandt hev alueofsum wi l
lequal t
o1.
Then,theupdat est atement++counti sex ecutedandthe
countwillequal to2.Agai n,thet estexpr essionis
eval
uated.Since2i sal solessthan10, thet est
expressi
oni sev aluatedt otrueandt hebodyoff orl
oop
i
sexecut ed.Now, thesum wi l
lequal 3.
Thisprocessgoesonandthesum i scal
culat
edunt
il
thecountreaches11.
Whent hecountis11,t
hetestexpressi
oniseval
uat
edto
0(fal
se),andtheloopt
erminates.
Then,t
hev alueofsum i
spri
ntedont hescr
een.

whi
l
eloop
Thesy
ntaxoft
hewhi
l
eloopi
s:
whil
e(test
Expr
essi
on)
{
/
/statement
sinsi
dethebodyoft
hel
oop
}

Howwhi
l
eloopwor
ks?
 Thewhi leloopev al
uat
esthet estex pressi
oninsi
dethe
parenthesi
s( )
.
 Ift
het estexpressioni
strue,statement sinsi
dethebody
ofwhi l
eloopar eexecut
ed.Then, t
het estexpr
essi
onis
evaluatedagain.
 Thepr ocessgoesonunt ilt
het estex pressi
onis
evaluatedtofalse.
 I
fthet
estexpr
essi
oni
sfal
se,
thel
oopt
ermi
nat
es(
ends)
.
Tolearnmor eabouttestexpr
essi
on(whenthet
est
expressi
oni seval
uatedtotr
ueandfal
se),
check
outrelat
ionalandlogi
caloper
ator
s.

Fl
owchar
tofwhi
l
eloop

Exampl
e1:
whi
l
eloop
/
/Pr
intnumber
sfr
om 1t
o5

#i
nclude<st
dio.
h>
i
ntmai n(
)
{
i
nti=1;

whi
l
e(i
<=5)
{
pri
ntf
("%d\
n",
i);
++i
;
}

r
etur
n0;
}
Out
put
1
2
3
4
5
Here,wehav einitiali
zedi to1.
1.
Wheni i
s1, thet estexpr essi oni <=5i
st r
ue.Hence, t
he
bodyoft hewhi lel oopisexecut ed.Thispri
nts1ont he
screenandt hev alueofi isi ncreasedto2.
2.
Now, iis2,thet estexpr essi oni <=5isagaintrue.The
bodyoft hewhi lel oopisexecut edagain.Thisprint
s2
ont hescreenandt heval ueofi i
sincr
easedt o3.
3.
Thisprocessgoesonunt ilibecomes6.Wheni i
s6, t
he
testexpressioni <=5wi ll bef al
seandt heloop
terminates.

do.
..
whi
l
eloop
Thedo..
whil
el oopissimil
art
ot hewhi
leloopwithone
i
mpor t
antdi
fference.Thebodyofdo..
.whil
eloopis
execut
edatleastonce.Onlythen,t
hetestexpr
essi
onis
eval
uated.
Thesyntaxoft
hedo.
..
whi
l
eloopi
s:
do
{
//statementsi
nsidet
hebodyoft
hel
oop
}
whil
e(testEx
pressi
on);

Howdo.
..
whi
l
eloopwor
ks?
 Thebodyofdo..
.whi
l
eloopisexecut
edonce.Onl
ythen,
thet
estexpr
essi
oniseval
uated.
 Ift
hetestexpr
essi
onist
rue,t
hebodyoftheloopis
execut
edagainandthet
estexpr
essi
onisevaluat
ed.
 Thi
sprocessgoesonunt
ilt
het
estexpr
essi
onbecomes
fal
se.
 I
fthet
estexpr
essi
oni
sfal
se,
thel
oopends.
Fl
owchar
tofdo.
..
whi
l
eLoop

Exampl
e2:
do.
..
whi
l
eloop

/
/Pr
ogr
am t
oaddnumber
sunt
ilt
heuserent
erszer
o

#i
nclude<stdi
o.h>
i
ntmai n()
{
doublenumber,sum =0;

//thebodyoft hel
oopisexecut
edatl
eastonce
do
{
printf
("Ent
eranumber :"
);
scanf (
"%lf
",&number)
;
sum +=number ;
}
while(number! =0.
0);

pr
int
f("
Sum =%.
2lf
",
sum)
;
r
etur
n0;
}
Out
put
Ent
eranumber
:1.5
Ent
eranumber
:2.4
Ent
eranumber
:-3.
4
Ent
eranumber
:4.2
Ent
eranumber
:0
Sum =4.
70

Cbr
eak
Thebr
eakstatementendsthel
oopi
mmedi
atel
ywheni
t
i
sencount
ered.I
tssyntaxi
s:

br
eak;
Thebr
eakstat
ementisal
mostalwaysused
wit
hif
..
.el
sest
atementi
nsi
detheloop.
Howbr
eakst
atementwor
ks?

Exampl
e1:
breakst
atement

//Pr
ogr
am tocalcul
atet
hesum ofamaxi
mum of10
number
s
//I
fanegat
ivenumberisent
ered,
thel
oopter
minat
es

#include<st
dio.
h>
i
ntmai n()
{
i
nti;
doublenumber,sum =0.
0;

f
or (
i=1;i<=10;++i
)
{
print
f("
Ent
eran%d:"
,i
);
scanf("
%lf
",
&number
);
//Iftheuserent
ersanegat
ivenumber
,thel
oop
ends
if
(number<0. 0)
{
break;
}

sum +=number
;//sum =sum +number
;
}

pr
int
f("
Sum =%.
2lf
",
sum)
;

r
etur
n0;
}
Out
put
Ent
eran1:2.4
Ent
eran2:4.5
Ent
eran3:3.4
Ent
eran4:-3
Sum =10.
30
Thisprogram cal culatest
hesum ofamax imum of10
number s.Whyamaxi mum of10number s?It
'sbecause
i
ftheuserent ersanegat i
venumber ,
thebreakst atementi sexecuted.Thiswil
lend
theforloop, andt hesum isdispl
ay ed.
I
nC, breakisal sousedwi t
htheswi t
chst
atement.This
wil
lbedi scussedi nthenexttut
orial.
Ccont
inue
Thecont
inuestatementski
psthecurrentit
erat
ionofthe
l
oopandcontinueswiththenexti
ter
ation.I
tssyntaxi
s:
cont
inue;
Thecontinuest
atementi
sal
mostal
way
susedwi
th
thei
f.
..
elsestat
ement.

Howcont
inuest
atementwor
ks?

Exampl
e2:
cont
inuest
atement

//Pr
ogram t
ocalcul
atethesum ofamaximum of10
numbers
//Negat
ivenumbersareski
ppedfrom t
hecal
culat
ion
z
Out
put
Ent
eran1:1.1
Ent
eran2:2.2
Ent
eran3:5.5
Ent
eran4:4.4
Ent
eran5:-3.4
Ent
eran6:-45.5
Ent
eran7:34.5
Ent
eran8:-4.2
Ent
eran9:-1000
Ent
eran10: 12
Sum =59.
70
I
nt hi
sprogram,whent heuserentersaposit
ivenumber,
thesum iscal
culatedusi
ngsum +=number ;statement
.
Whent heuserentersanegati
venumber ,
theconti
nuestatementisexecutedanditski
psthe
negati
venumberf rom t
hecalcul
ation.

Theswi
tchst
atemental
lowsustoexecut
eonecode
bl
ockamongmanyalter
nati
ves.
Youcandothesamethingwit
hthei
f..
.el
se.
.i
fladder
.
However
,thesy
ntaxoftheswi
tchst
atementismuch
easi
ert
oreadandwrit
e.
Sy
ntaxofswi
tch.
..
case

switch(expressi
on)
{

caseconst ant
1:
//statements
break;

caseconst ant2:
//statement s
break;
.
.
.
default
:
//defaultstatement
s
}
Howdoest heswitchst atementwor k?
Theexpr essioniseval uatedonceandcompar edwith
thev al
uesofeachcasel abel .
 Ifthereisamat ch,thecor r
espondi ngstatementsafter
themat chinglabelareex ecut ed.Forexampl e,
ifthe
valueoft heexpr essioni sequal t
oconst ant
2,
statement saf t
ercaseconst ant2:areexecuted
untilbreaki sencount ered.
 Ifthereisnomat ch,thedef aultstatementsareexecuted.
I
fwedonotusebr eak,al
lstat
ementsaf
tert
hemat
chi
ng
l
abelar
eexecuted.
Bytheway,t
hedefaultcl
auseinsi
de
theswi
tchst
atementisopti
onal.
swi
tchSt
atementFl
owchar
t

Exampl
e:Si
mpl
eCal
cul
ator

/
/Pr
ogr
am t
ocr
eat
easi
mpl
ecal
cul
ator
#i
nclude<st di
o.h>
i
ntmai n(){
charoper;
doublefi
rst,second;
pri
ntf(
"Enteranoperator(
+,-
,*,
):"
);
scanf(
"%c",&oper);
pri
ntf(
"Entertwooperands:"
);
scanf(
"%lf%lf",
&fir
st,
&second);

switch( oper){
case' +'
:
printf
("%.1lf+%. 1lf=%.1l
f",f
irst
,second,f
irst+second);
break;
case' -
':
printf
("%.1lf-%.1lf=%.1lf"
,fi
rst,
second,fi
rst-second);
break;
case' *'
:
printf
("%.1lf*%.1lf=%. 1l
f"
,fi
rst,second,
fir
st*second);
break;
case' /'
:
printf
("%.1lf/%.1lf=%. 1l
f"
,fi
rst,second,
fir
st/second);
break;
//oper atordoesn' tmatchanycaseconst ant
default:
printf
("Error!operatori
snotcor r
ect");
}

r
etur
n0;
}

Out
put
Ent
eranoperator(+,
-,*
,)
:-
Ent
ertwooperands:32.5
12.
4
32.
5-12.4=20. 1
The-operatorenter
edbyt heuserisstor
edin
theoperatorv
ari
able.And,two
operands32.5and12.4arest or
edin
vari
ablesn1andn2r especti
vely
.
Sincetheoperat
oris-,t
hecont r
oloftheprogr
am j
umps
to
pr
int
f("
%.1l
f-%.
1lf=%.
1lf
",n1,
n2,
n1-
n2)
;

Final
l
y,t
hebr
eakstat
ementt
ermi
nat
es
theswit
chst
atement
.

Thegotostatemental
lowsustot
ransf
ercont
rol
oft
he
progr
am t
ot hespeci
fi
edlabel
.

C–got
ost
atement
Whenagot ostat
ementisencount
eredi
naCpr ogr
am,
thecontr
olj
umpsdirect
lyt
ot hel
abelment
ionedi
nthe
gotostat
ement
Syntaxofgot
ostatementinC

got
olabel
_name;
.
.
.
.
l
abel
_name:C-st
atement
s
Fl
owDi
agr
am ofgot
o

Sy
ntaxofgot
oSt
atement

gotolabel
;
..
.....
.
..
.....
.
l
abel :
statement
;
Thel
abel
isani
dent
if
ier
.Whent
hegot
ost
atementi
s
encounter
ed,t
hecontrolofthepr
ogram j
umps
tolabel
:andstar
tsexecuti
ngthecode.
l
abe1:
got
olabe1 St
atement
;
…………. ……….
………….
.. ……….
.
Got
olabe1;
Labe1:
St
atement
;
………….

Exampl
e:got
oSt
atement

//Program tocalculat
ethesum andav
erageofposi
ti
ve
number s
//Iftheuserentersanegati
venumber,t
hesum and
averagearedisplayed.

#i
ncl
ude<st
dio.
h>

i
ntmai
n(){

constintmaxI
nput=100;
i
nti;
doublenumber,av
erage,
sum =0.
0;
f
or(i=1; i
<=maxI nput
;++i
){
pri
ntf
("%d.Enteranumber:"
,i
);
scanf
("%lf"
,&number);

//got ojumpift
heuserent
ersanegat
ivenumber
i
f( number<0.0){
gotojump;
}
sum +=number ;
}

j
ump:
av
erage=sum /(
i-1)
;
pr
int
f("
Sum =%.
2f\
n",
sum) ;
pr
int
f("
Aver
age=%.2f
",av
erage)
;

ret
urn0;
}
Out
put
1.Enteranumber
:3
2.Enteranumber
:4.3
3.Enteranumber
:9.3
4.Enteranumber
:-2.
9
Sum =16.60
Average=5.53
#i
nclude<stdi
o.h>
i
ntmai n(
)
{
i
ntsum=0;
for
(inti=0;i
<=10;i
++)
{
sum =sum+i;
i
f(
i==5)
{
gotoaddi
ti
on;
}
}

addit
ion:
pri
ntf
("%d",
sum)
;

ret
urn0;
}

Explanati
on:Inthi
sexampl e,wehav ea
l
abel addi
ti
onandwhent hev al
ueofi (
insideloop)i
s
equal t
o5t henwearejumpi ngtothislabelusinggot
o.
Thisisreasonthesum isdisplayi
ngthesum ofnumber s
ti
l
l5ev enthoughtheloopissett orunf r
om 0t o10.

Reasonst
oav
oidgot
o
Theuseofgot
ostatementmayleadt
ocodet
hati
s
buggyandhar
dtofoll
ow.Forexampl
e,
one:
for(i=0;i
<number
;++i
)
{
test+=i
;
gototwo;
}
t
wo:
i
f(test>5){
gotothr
ee;
}
.
...
....
Also,
thegotostatementall
owsyoutodobadstuffsuch
asjumpoutoft hescope.
Thatbeingsai
d,gotocanbeusefulsomet
imes.For
example:tobr
eakf r
om nestedl
oops.

Afunct
ioni
sabl
ockofcodet
hatper
for
msaspeci
fi
c
t
ask.
Suppose,youneedtocr
eat
eaprogr
am tocr
eat
eacircl
e
andcolourit
.Youcancr
eat
etwofunct
ionst
osolv
ethis
probl
em:
 cr
eat
eaci
rcl
efunct
ion
 cr
eat
eacol
ourf
unct
ion
Div
idi
ngacomplexprobl
em int
osmal
lerchunksmakes
ourpr
ogr
am easytounderst
andandr
euse.
Ty
pesoff
unct
ion
Ther
ear
etwot
ypesoff
unct
ioni
nCpr
ogr
ammi
ng:
 Standardli
braryf
uncti
ons
 User-def
inedfunct
ions

Standardlibr
aryfunct
ions
Thest andardli
brar
yfuncti
onsar
ebui
l
t-i
nfunct
ionsi
nC
programmi ng.
Thesef
unct
ionsar
edef
inedi
nheaderf
il
es.Forexampl
e,
 Thepr i
ntf()isast andardl i
braryf unctiontosend
formattedout puttot hescr een( displayoutputonthe
screen).Thisf uncti
oni sdef i
nedi nt hestdi
o.hheader
fi
le.
Hence,t ouset hepr i
ntf()
funct i
on, weneedt oincl
ude
thestdi
o. hheaderf il
eusi ng#i nclude<st di
o.h>.
 Thesqr t()functi
oncal culatesthesquar erootofa
number .Thef unctionisdef inedi nthemat h.hheader
fi
le.

User-
definedfunct
ion
Youcanal socreat
efuncti
onsasperyourneed.Such
funct
ionscreatedbytheuserar
eknownasuser -
defi
ned
funct
ions.
Howuser
-def
inedf
unct
ionwor
ks?
#i
ncl
ude<st
dio.
h>
v
oidf
unct
ionName(
)
{
.
...
...
.
.
...
...
.
}

i
ntmai
n()
{
.
...
...
.
.
...
...
.

f
unct
ionName(
);

.
...
...
.
.
...
...
.
}

Theexecuti
onofaCpr ogram begi
nsfrom
themain(
)funct
ion.
Whenthecompilerencounter
sfuncti
onName(
);
,cont
rol
oft
hepr
ogr
am j
umpst
o
v
oidf
unct
ionName(
)

And,thecompi l
erstar
tsexecut
ingthecodes
i
nsidefuncti
onName( ).
Thecontroloftheprogram j
umpsbackt o
themain()functi
ononcecodeinsidethefunct
ion
defi
nit
ionisexecuted.

Not
e,f
unct
ionnamesar
eident
if
ier
sandshoul
dbe
uni
que.
Thisisj
ustanover
viewofuser
-def
inedf
unct
ions.Vi
sit
thesepagestol
ear
nmor eon:
 User-
def
inedFuncti
oninCprogrammi
ng
 Typesofuser
-def
inedFunct
ions

Advant
agesofuser
-def
inedfunct
ion
1.
Theprogr
am wil
lbeeasiert
ounderst
and,
mai
ntai
nand
debug.
2.
Reusabl
ecodest
hatcanbeusedi
not
herpr
ogr
ams
3.
Alargeprogram canbedi v
idedi
ntosmal
lermodul
es.
Hence,alargeprojectcanbediv
idedamongmany
programmer s.

CUser
-def
inedf
unct
ion

Afunct
ioni
sabl
ockofcodet
hatper
for
msaspeci
fi
c
t
ask.
Call
owsy outodef
inef
unct
ionsaccordingt
oy ourneed.
Thesefuncti
onsar
eknownasuser-defi
nedfuncti
ons.
Forexample:
Suppose,youneedtocreateacircl
eandcol
orit
dependi
ngupont heradiusandcolor
.Youcancreat
e
twofunct
ionstosolv
et hisprobl
em:
 cr
eat
eCi
rcl
e()f
unct
ion
 col
or(
)funct
ion

Exampl
e:User
-def
inedf
unct
ion
Her
eisanexampletoaddtwoint
egers.Toper
for
mt hi
s
t
ask,wehav
ecreatedanuser
-def
inedaddNumbers(
).
#i
ncl
ude<st
dio.h>
i
ntaddNumbers(i
nta,
intb)
; /
/funct
ionpr
otot
ype

i
ntmain(
)
{
i
ntn1,
n2,
sum;

pri
ntf
("Ent
erst
wonumbers:
");
scanf
("%d%d",
&n1,
&n2)
;

sum =addNumber s(
n1,n2)
; /
/funct
ioncal
l
pri
ntf
("sum =%d"
,sum);

r
etur
n0;
}

i
ntaddNumber s(i
nta,
intb) //f
uncti
ondef
ini
ti
on
{
i
ntresult
;
r
esult=a+b;
r
eturnresul
t; //r
etur
nstat
ement
}
Funct
ionpr
otot
ype
Afuncti
onpr ot
otypeissimplythedecl
arat
ionofa
f
unctionthatspecif
iesfunct
ion'
sname,parameter
sand
r
eturntype.I
tdoesn'tcontai
nfuncti
onbody.
Afunct
ionprotot
ypegi
vesi
nfor
mati
ontothecompi
l
er
t
hatthefunct
ionmaylat
erbeusedi
ntheprogr
am.
Sy
ntaxoff
unct
ionpr
otot
ype

retur
nTypefunct
ionName(
type1ar
gument
1,t
ype2
argument2,
...
);

Intheabov eexampl e,i


ntaddNumber s(inta,
intb)
; i
sthe
functi
onpr ot
otypewhi chprovidest
hef oll
owing
inf
ormat iontot hecompi ler
:
1.
nameoft hef uncti
onisaddNumber s(
)
2.
retur
nt ypeoft hefunctionisint
3.
twoar gument soft ypeintarepassedt othefunct
ion
Thef unctionprototypeisnotneededi ftheuser-
defined
functi
oni sdef i
nedbef orethemain()functi
on.

Cal
l
ingaf
unct
ion
Contr
oloftheprogr
am i
str
ansf
err
edt
otheuser
-def
ined
funct
ionbycal
li
ngit.
Sy
ntaxoff
unct
ioncal
l

f
unct
ionName(
argument
1,ar
gument
2,.
..
);
I
nt heaboveexampl
e,t
hef
uncti
oncall
ismade
usingaddNumbers(
n1,
n2)
;st
atementinsi
de
themain()f
uncti
on.

Funct
iondef
ini
ti
on
Functi
ondefi
nit
ioncontainst
heblockofcodeto
perf
orm aspeci
fictask.I
nourexample,
addingtwo
numbersandreturningit
.
Sy
ntaxoff
unct
iondef
ini
ti
on

retur
nTypefunct
ionName(
type1ar
gument
1,t
ype2
argument2,
...
)
{
/
/bodyoft
hef
unct
ion
}

Whenaf unct
ioniscall
ed,t
hecontroloftheprogram i
s
tr
ansfer
redtothefuncti
ondefi
nit
ion.And,thecompiler
star
tsexecut
ingthecodesinsi
dethebodyofaf unct
ion.

Passi
ngar
gument
stoaf
unct
ion
I
nprogramming,ar
gumentref
erst
othevar
iabl
epassed
t
othefunct
ion.I
ntheaboveexampl
e,t
wo
v
ari
ablesn1andn2arepassedduri
ngthef
uncti
oncall
.
Theparameter
saandbaccept st hepassedargument
s
i
nthefuncti
ondefi
nit
ion.Theseargumentsarecall
ed
for
malparameter
soft hefunct
ion.

Thetypeofar
gumentspassedtoaf uncti
onandthe
for
mal par
ameter
smustmat ch,
otherwise,t
hecompil
er
wil
lthr
owanerror.
Ifn1isofchart
ype,
aalsoshouldbeofchartype.
Ifn2isoffl
oatty
pe,var
iablebal
soshouldbeoffl
oat
type.
Af unct
ioncanal
sobecalledwit
houtpassi
ngan
argument.
Ret
urnSt
atement
Ther etur
nstatementt erminatest
heexecut i
onofa
functionandretur
nsav aluetothecall
i
ngf uncti
on.The
program contr
ol i
stransferredtothecall
i
ngf uncti
on
aftertheret
urnstatement .
I
ntheabov
eex
ampl
e,t
he

v al
ueoftheresultvari
ableisret
urnedtothemai
n
functi
on.Thesum vari
ableinthemain()f
uncti
oni
s
assignedthi
sval
ue.
Sy
ntaxofr
etur
nst
atement

r
etur
n(expr
essi
on)
;

Forexampl
e,

r
etur
na;
r
etur
n(a+b)
;

Thet y
peofvalueretur
nedfr
om thef
uncti
onandt
he
retur
ntypespecif
iedinthef
uncti
onpr
otot
ypeand
functi
ondefi
nit
ionmustmat ch

Ty
pesofUser
-def
inedFunct
ionsi
nCPr
ogr
ammi
ng

These4progr
amsbelowcheckwhet
hert
heint
eger
ent
eredbytheuseri
sapr
imenumberornot
.
Theout
putofall
thesepr
ogramsbelowisthesame,and
wehavecreat
edauser-
defi
nedfunct
ioni
neach
exampl
e.However,
theappr
oachwehav et
akenineach
exampl
eisdif
fer
ent.

Exampl
e1:
Noar
gument
spassedandnor
etur
nval
ue

#i
ncl
ude<st
dio.
h>

v
oidcheckPr
imeNumber
();
i
ntmai n(
)
{
checkPri
meNumber
();/
/ar
gumenti
snotpassed
ret
urn0;
}

/
/retur
ntypeisv
oidmeaningdoesn'
tret
urnanyv
alue
v
oidcheckPri
meNumber(
)
{
i
ntn,i
,fl
ag=0;

pri
ntf
("Ent
eraposi
ti
vei
nteger
:")
;
scanf
("%d",
&n)
;

for(
i=2;i<=n/2;
++i
)
{
if
(n%i ==0)
{
flag=1;
}
}
i
f( f
lag==1)
printf
("%di
snotapr
imenumber.
",n)
;
else
printf
("%di
sapri
menumber.
",n)
;
}
ThecheckPri
meNumber (
)funct
iont
akesinputf
rom t
he
user
,checkswhet
heriti
sapr i
menumberornotand
di
splay
sitonthescr
een.
Theemptyparent
heses
i
ncheckPrimeNumber()
;stat
ementi
nside
themain()functi
onindi
catesthatnoargumentis
passedtot hefunct
ion.
Theretur
nt ypeofthefuncti
onisvoid.Hence,
nov al
uei
s
ret
urnedfrom thefunct
ion.

Exampl
e2:
Noar
gument
spassedbutar
etur
nval
ue

#i
ncl
ude<stdi
o.h>
i
ntget
Int
eger(
);

i
ntmain()
{
i
ntn,i
,fl
ag=0;

/
/noar
gumentispassed
n=get
Int
eger
();

f
or(i
=2; i
<=n/2;
++i
)
{
i
f(
n%i ==0)
{
fl
ag=1;
break;
}
}

i
f(fl
ag==1)
pr
int
f("
%di
snotapr
imenumber.
",n)
;
el
se
pr
int
f("
%di
sapri
menumber.
",n)
;

r
etur
n0;
}

/
/retur
nsintegerent
eredbyt
heuser
i
ntgetI
nteger(
)
{
i
ntn;

pri
ntf
("Ent
eraposi
ti
vei
nteger
:")
;
scanf
("%d",
&n)
;

r
etur
nn;
}
Theempt ypar enthesesinthen=
getI
nteger(
);statementindicatest hatnoar gumenti
s
passedtot hefunct i
on.And,thev aluer et
urnedfr
om the
funct
ionisassi gnedton.
Here,thegetInteger(
)functi
ont akesi nputfrom t
heuser
andreturnsit
.Thecodet ocheckwhet heranumberis
pri
meornoti sinsidethemai n()function.

Exampl
e3:
Argumentpassedbutnor
etur
nval
ue

#incl
ude<stdio.
h>
voidcheckPri
meAndDi
spl
ay(
intn)
;

i
ntmain()
{
i
ntn;

pr
int
f("
Ent
eraposi
ti
vei
nteger
:")
;
scanf
("%d"
,&n)
;

//nispassedt
othefunct
ion
checkPr
imeAndDi
spl
ay(n)
;

r
etur
n0;
}

/
/returntypei
svoidmeani
ngdoesn'
tret
urnanyv
alue
v
oidcheckPrimeAndDi
spl
ay(
intn)
{
i
nti,
flag=0;

for(
i=2; i<=n/
2;++i
)
{
if
(n%i ==0){
flag=1;
br eak;
}
}
i
f(fl
ag==1)
printf("
%disnotapr
imenumber.
",
n);
else
printf("
%disapri
menumber.
",n)
;
}
Theintegervalueent
eredbytheuserispassedto
thecheckPrimeAndDispl
ay()f
uncti
on.
Here,t
hecheckPr i
meAndDisplay(
)funct
ionchecks
whethertheargumentpassedi sapri
menumberornot
anddisplaystheappropr
iat
emessage.
Exampl
e4:
Argumentpassedandar
etur
nval
ue

#i
nclude<st
dio.
h>
i
ntcheckPri
meNumber
(i
ntn)
;

i
ntmain()
{
i
ntn,f
lag;

pri
ntf
("Ent
eraposi
ti
vei
nteger
:")
;
scanf
("%d",
&n)
;

/
/nispassedtothecheckPrimeNumber
()f
uncti
on
/
/theret
urnedval
ueisassignedtot
hefl
agvari
able
f
lag=checkPri
meNumber (
n);

i
f(
f l
ag==1)
pri
ntf
("%di
snotapr
imenumber"
,n)
;
el
se
pri
ntf
("%di
sapri
menumber"
,n)
;

r
etur
n0;
}

/
/inti
sr et
urnedf
rom t
hefunct
ion
i
ntcheckPri
meNumber(i
ntn)
{
i
nti
;

f
or(i
=2;i<=n/2;
++i
)
{
i
f(
n%i ==0)
r
eturn1;
}

r
etur
n0;
}
Theinputf rom theuserispassedt o
thecheckPr imeNumber (
)f unction.
ThecheckPr i
meNumber ()funct i
oncheckswhet herthe
passedar gumenti spri
meornot .
I
fthepassedar gumentisapr imenumber ,thefunction
ret
urns0.I fthepassedar gumenti sanon- pri
menumber ,
thefuncti
onr etur ns1.Ther eturnvalueisassignedt o
thefl
agv ariable.
Dependingonwhet herfl
agi s0or1, anappropriate
messagei spr i
nt edfrom themai n(
)functi
on.

Whi
chappr
oachi
sbet
ter
?
Wel
l,i
tdependsontheprobl
em youar
etryi
ngt
osolv
e.
I
nthi
scase,passi
ngargumentandret
urni
ngaval
ue
f
rom t
hefuncti
on(example4)i
sbett
er.
Afunctionshoul
dperfor
m aspecif
ictask.
ThecheckPrimeNumber()f
uncti
ondoesn' ttakei
nput
fr
om theusernoritdi
spl
aystheappropriatemessage.I
t
onlycheckswhetheranumberispri
meornot .

Nest
ingofFunct
ion:
add(
) funct
ion
{
…………
…………..
mul(
);
} her
ewear ecal
l
ingmul f
unct
ion
wi
thi
naddf
uni
scall
ednest
ingoffunct
ion

main()
{
add()
;
}

Recursion:
Af unct
ionthatcal
lsi
tsel
fisknownasarecursi
ve
functi
on.And,thi
stechni
queisknownasrecursi
on.

Howr
ecur
sionwor
ks?

v
oidr
ecur
se(
)
{
.
...
...
.
r
ecur
se(
);
.
...
...
.
}
i
ntmai
n()
{
.
...
...
.
r
ecur
se(
);
.
...
...
.
}

Therecur
sioncont
inuesunt
ilsomecondi
ti
oni
smett
o
prev
entit
.
Topreventinfi
nit
erecur
sion,i
f.
..
elsestat
ement(or
simi
l
arappr oach)canbeusedwher eonebr
anchmakes
ther
ecursiv
ecal l
,andotherdoesn't
.
Exampl
e:Sum ofNat
ural
Number
sUsi
ngRecur
sion

#i
nclude<stdi
o.h>
i
ntsum(intn);

i
ntmain(){
i
ntnumber,
resul
t;

pri
ntf
("Ent
erapositi
veint
eger
:")
;
scanf
("%d",&number)
;

r
esul
t=sum(
number
);

pri
ntf
("sum =%d"
,resul
t)
;
ret
urn0;
}

i
ntsum( i
ntn){
i
f(n!=0)
/
/sum( )f
unct
ioncall
sit
sel
f
r
etur
nn+sum( n-
1);
el
se
r
etur
nn;
}
Out
put
Ent
eraposi
ti
vei
nteger
:3
sum =6

I
nit
ial
l
y,t
hesum(
)iscal
l
edf
rom t
hemai
n()f
unct
ion
withnumberpassedasanar gument.
Suppose,theval
ueofni nsi
desum( )is3ini
ti
all
y.During
thenextfunct
ioncall
,2ispassedt othesum()functi
on.
Thisprocesscont
inuesuntilnisequalto0.
Whenni sequalto0, t
heifcondit
ionfai
lsand
theelseparti
sexecutedreturni
ngthesum ofinteger
s
ult
imatel
yt ot
hemai n()f
unction.
Adv
ant
agesandDi
sadv
ant
agesofRecur
sion
Recur
sionmakespr
ogr
am el
egant
.Howev
er,
if
perf
ormancei
svit
al,
usel
oopsi
nst
eadasr
ecur
sioni
s
usual
lymuchsl
ower.
Thatbeingsaid,
recur
sionisanimpor t
antconcept
.Iti
s
fr
equentlyusedindat
ast r
uctur
eandal gor
it
hms.For
example,iti
scommont ouserecur
sioninprobl
ems
suchast reet
raver
sal
.

CSt
orageCl
ass

Ever
yvar
iabl
einCprogr
ammi
nghast
wopr
oper
ti
es:
ty
peandstor
agecl
ass.
Ty peref
erstot
hedat
atypeofavariabl
e.And,st
orage
classdeter
minest
hescope,
visi
bil
i
tyandlif
eti
meofa
var i
abl
e.
Ther
ear
e4t
ypesofst
oragecl
ass:
1.
aut
omat
ic
2.
ext
ernal
3.
stat
ic
4.
regi
ster
Local
Var
iabl
e
Thevari
ablesdeclar
edinsi
deablockareautomaticor
l
ocalvar
iables.Thel
ocalvar
iabl
esexi
stonlyinsi
dethe
bl
ockinwhi chiti
sdecl
ared.
Let
'st
akeanexampl
e.

#i
ncl
ude<st
dio.
h>

i
ntmai
n(v
oid){

f
or(i
nti=0;
i<5;++i
){
pr
int
f("
Cpr
ogr
ammi ng"
);
}

//Error:i
isnotdecl
aredatt
hispoi
nt
pri
ntf(
"%d",
i);
ret
urn0;
}
Wheny ouruntheabov epr ogram,youwil
lgetan
err
orundecl ar
edidentif
ieri.It'
sbecauseii
sdeclared
i
nsidet heforl
oopbl ock.Out si
deoftheblock,
it'
s
undeclared.
Let'
stakeanot herexampl e.

i
ntmain(
){
i
ntn1;
//n1i
sal
ocal
var
iabl
etomai
n()
}

v
oidf
unc(
){
i
ntn2;/
/n2i
sal
ocal
var
iabl
etof
unc(
)
}
Intheaboveex ampl e,n1islocalt
omai
n( )andn2is
l
ocal t
ofunc().
Thismeansy oucannotaccesst hen1v
ar i
able
i
nsidefunc()asi tonlyexist
sinsi
demai
n( ).Si
milar
ly,
you
cannotaccesst hen2v ar
iabl
einsi
demain()asitonly
exi
stsinsi
def unc().

Gl
obal
Var
iabl
e
Vari
ablesthataredeclaredoutsideofallfuncti
onsar
e
knownasext ernalorglobalvari
ables.Theyare
accessibl
efrom anyfunctioninsidetheprogram.

Exampl
e1:
Global
Var
iabl
e

#incl
ude<st
dio.
h>
voiddi
spl
ay(
);

i
ntn=5;/
/gl
obal
var
iabl
e

i
ntmai n()
{
++n;
displ
ay()
;
retur
n0;
}
v
oi ddisplay
()
{
++n;
pri
ntf("
n=%d",
n);
}
Out
put
n=7
Suppose,aglobalvari
ableisdecl
aredinfi
l
e1.Ifyoutry
tousethatvari
ableinadiffer
entfi
lefi
l
e2,thecompi l
er
wil
lcomplain.Tosolvethisprobl
em,keywordexternis
usedinfi
le2toindicat
ethattheexter
nalvari
ableis
decl
aredinanotherfil
e.

Regi
sterVar
iabl
e
Theregi sterkeywordisusedtodeclareregist
er
vari
ables.Regi st
ervari
ablesweresupposedt obefast
er
thanlocal vari
ables.
Howev er ,
moder ncompi l
ersar
ev erygoodatcode
opti
mi zation,andtherei
sar ar
echancet hatusing
regi
sterv ari
ableswillmakeyourprogram fast
er.
Unlessyouar
eworkingonembeddedsyst
emswhere
youknowhowt oopti
mizecodef
orthegiv
enappl
i
cati
on,
therei
snouseofregist
erv
ari
abl
es.
#i
ncl
ude<st
dio.
h>

i
ntmai
n(){

r
egi
stercharx='
S'
;

r
egi
steri
nta=10;

aut
ointb=8;

pr
int
f("
Thev
alueofr
egi
sterv
ari
abl
eb:
%c\
n",
x);

pr
intf
("Thesum ofaut
oandr
egi
sterv
ari
abl
e:
%d",
(a+b));

r
etur
n0;
}

St
ati
cVar
iabl
e
Astati
cvar
iabl
eisdecl
aredbyusi
ngt
hest
ati
ckey
wor
d.
Forexampl
e;
st
ati
cinti
;

Thevalueofast
ati
cvar
iabl
eper
sist
sunt
ilt
heendoft
he
progr
am.
Exampl
e2:
Stat
icVar
iabl
e

#incl
ude<st
dio.
h>
voiddi
spl
ay(
);

i
ntmai n()
{
displ
ay();
displ
ay();
}
v
oi ddisplay
()
{
stati
cintc=1;
c+=5;
print
f("
%d" ,
c);
}
Out
put
611
Duri
ngt hef i
rstf
uncti
oncal l,
thevalueofci sini
ti
ali
zed
to1.Itsvalueisincr
easedby5.Now, t
hev al
ueofci s6,
whichispr i
ntedonthescr een.
Duri
ngt hesecondf uncti
oncal l
,cisnotiniti
ali
zedto1
again.It
'sbecauseci sastaticvari
able.Thev al
ueci s
i
ncreasedby5.Now, itsvaluewill
be11, whichisprinted
onthescr een.
Theaut
oSt
orageCl
ass
Theaut
ostorageclassi
sthedef
aul
tst
oragecl
assf
or
al
ll
ocalvar
iabl
es.
{
i
ntmount;
aut
ointmont
h;
}
Theex ampl eabovedef inestwov ar
iabl
eswit
hinthe
same storage class.'auto'can onl
ybe used wi
thi
n
funct
ions,
i.e.,
localvar
iables.
Ther
egi
sterSt
orageCl
ass
Theregisterstor
age cl ass is used to define local
var
iabl
est hatshouldbest oredinaregi
sterinsteadof
RAM.Thi smeanst hatthev ariabl
ehasamaxi mum si z
e
equaltother egist
ersize( usuall
yonewor d)andcan' t
havetheunar y'&'operatorappl i
edt
oit(asitdoesnot
haveamemor ylocati
on) .
{
regi
steri
ntmi
l
es;
}
The regi
stershould onlybe used f orv ari
abl
es that
requi
requickaccesssuchascount ers.Itshouldalso
benotedthatdefi
ning'regi
ster'
doesnotmeant hatthe
vari
ablewillbestoredi nar egist
er.I tmeanst hatit
MIGHTbest or
edinar egi
sterdependi ngonhar dware
andimplementati
onrestri
cti
ons.
Thest
ati
cSt
orageCl
ass
Thest ati
cstorageclassi nst
ructsthecompi l
ertokeep
alocalv ari
abl
ei nexistencedur i
ngthelif
e-timeofthe
program inst
eadofcr eati
nganddest roy
ingiteachtime
i
tcomesi ntoandgoesoutofscope.Ther efore,maki
ng
l
ocalv ar
iabl
es stati
c allows them to mai ntai
ntheir
valuesbetweenf unct
ioncal l
s.
The st
ati
c modi
fiermay also be appl
ied t
o global
vari
abl
es.Whenthisisdone,itcausesthatvar
iabl
e'
s
scopetober
est
ri
ct edt
othefi
leinwhichi
tisdecl
ared.
In C programming,whenstati
cis used on a gl
obal
vari
able,i
tcausesonlyonecopyofthatmembert obe
sharedbyalltheobj
ectsofi
tscl
ass.
s
When the abov
e code i
s compi
l
ed and ex
ecut
ed,i
t
pr
oducesthefol
lowi
ngresul
t−
ii
s6andcountis4
ii
s7andcountis3
ii
s8andcountis2
ii
s9andcountis1
ii
s10andcountis0
Theext
ernSt
orageClass
Theexternstor
ageclassi susedt ogiveareferenceof
aglobalvar
iabl
ethatisvisi
blet oALLtheprogram fi
les.
Wheny ouuse'exter
n',t
hev ariabl
ecannotbei ni
ti
ali
zed
however,itpoint
st he v ari
able name ata st or
age
l
ocati
onthathasbeenpr eviouslydef
ined.
Wheny ouhav emultipl
ef il
esandy oudef i
neagl obal
vari
abl eorf uncti
on,whichwi l
lalsobeusedi nother
fi
les,thenext er
nwi l
lbeusedi nanotherfi
letoprovide
ther eferenceofdef i
nedv ariabl
eorf unct
ion.Justfor
under standing,exter
ni s used t o declar
e a gl obal
vari
abl eorfunct i
oninanot herfil
e.
Theexternmodif
ierismostcommonlyusedwhenthere
aretwoormor efil
esshar
ingthesameglobalv
ari
ables
orfunct
ionsasexplai
nedbel
ow.
Fi
rstFi
le:mai
n.c
#i
ncl
ude<st
dio.
h>

i
ntcount;
ext
ernvoi
dwr
it
e_ext
ern(
);

mai
n(){
count=5;
wri
te_ext
ern(
);
}
SecondFi
le:suppor
t.
c
#i
ncl
ude<st
dio.
h>

ext
erni
ntcount
;

v
oidwri
te_ext
ern(
voi
d){
pr
int
f("
countis%d\
n",
count
);
}
Here,externis bei
ng used to decl ecounti
ar n the
secondf i
le,whereasithasi
tsdef
ini
ti
oninthefi
rstf
il
e,
main.c.Now, compil
etheset
wofil
esasfoll
ows−
$gccmain.csupport.
c
Itwil
lpr
oducet heexecut
abl
eprogram a.out.Whenthi
s
progr
am isexecuted,i
tpr
oducest
hefollowingresul
t−
counti
s5

CAr
ray
s
Arraysakindofdat ast r
uctur
et hatcanstoreafixed-
sizesequent
ialcoll
ect
ionofelement soft
hesamet ype.
Anar r
ayi
susedt ost
or eacollect
ionofdata,butitis
oftenmoreusef ult
othinkofanar rayasacoll
ecti
onof
variabl
esoft
hesamet ype.
I
nstead of decl
ari
ng indi
vi
dualv ar
iables,such as
number0,number
1,...
,andnumber99,youdeclareone
arr
ayvariabl
esuchasnumber sandusenumber s[0]
,
numbers[
1],and.
..
,numbers[
99]t
or epresenti
ndiv
idual
var
iabl
es.Aspeci
fi
cel
ementi
nanar
rayi
saccessedby
anindex.
Allar
ray
sconsistofconti
guousmemorylocat
ions.The
l
owestaddresscor r
espondstot hef
ir
stelementand
thehi
ghestaddresst
othelastel
ement
.

Anarrayi
sav ar
iabl
ethatcanst
oremult
ipl
eval
ues.For
example,
ify
ouwantt ostor
e100int
egers,
youcan
creat
eanarrayf
orit.

i
ntdat
a[100]
;
Howt
odecl
areanar
ray
?

dat
aTy
pear
ray
Name[
arr
aySi
ze]
;

Forexampl
e,
f
loatmar
k[5]
;

Her e,
wedecl ar
edanarray,mark,offl
oating-
poi
ntt
ype.
Andi t
ssizeis5.Meaning,i
tcanhol d5floati
ng-
poi
nt
values.
It
'simportanttonot
ethatthesizeandt y
peofanarray
cannotbechangedoncei tisdecl
ared.

Decl
ari
ngAr
ray
s
Todeclareanar rayi
nC,apr ogr
ammerspeci
fi
esthe
type ofthe el
ements and t
he numberofel
ements
requi
redbyanarrayasfol
lows−
t
ypear r
ayName[ar raySi
ze];
Thi
s i
s called asingl
e-di
mensionalar
ray.
Thear r
aySizemustbeani ntegerconstantgr
eatert
han
zer
oandt ypecanbeanyv al
idCdatat y
pe.Forexample,
to decl
area 10- elementar raycall
edbalanceoftype
double,usethi
sst atement−
doubl
ebalance[
10]
;
Herebal
anceisav ari
abl
earraywhi
chi
ssuf
fi
cientt
o
holdupt
o10doubl enumber
s.
I
nit
ial
izi
ngAr
ray
s
Youcanini
ti
ali
zeanar r
ayinC ei
theronebyoneor
usi
ngasi
ngl
est at
ementasf
oll
ows−
doubl
ebalance[
5]={1000.
0,2.0,3.4,7.0,50.
0};
Thenumberofv al
uesbetweenbr aces{}cannotbe
lar
gerthanthenumberofelement st hatwedeclar
efor
thear
raybetweensquarebrackets[].
Ifyou omi
tthe si
ze ofthe ar
ray
,an arr
ayjustbig
enoughtohol
dtheini
ti
ali
zat
ioni
screat
ed.Ther
efor
e,i
f
youwri
te−
doubl
ebalance[]={ 1000.0,2.
0,3.
4,7.0,
50.
0};
Youwi l
lcreat
eexact lythesamear rayasyoudi
dinthe
previ
ousexampl e.Followingisanex ampl
etoassi
gna
singl
eelementoft hear r
ay−
balance[4]=50. 0;
Theabov est atementassignst he5thelementi nthe
arraywi t
hav alueof50.0.Al
larrayshav e0astheindex
oft heirf
irstelementwhichisalsocal l
edthebaseindex
andt helastindexofanar raywillbet ot
alsi
zeoft he
array mi nus 1. Shown bel ow i s t he pictor
ial
representationoft hear
raywedi scussedabove−
AccessAr
rayEl
ement
s
Youcanaccessel
ement
sofanar
raybyi
ndi
ces.
Supposeyoudeclar
edanar r
aymarkasabov
e.Thef i
rst
el
ementismark[0],
thesecondel
ementi
smar k[
1]and
soon.

Fewkey notes:
 Arrayshave0ast hefi
rstindex,not1.Int
his
example,mar k[
0]isthef i
rstel
ement .
 Ift
hesizeofanar rayi
sn, toaccessthelastelement,
then-1indexisused.Int hisexample,mark[4]
 Supposet hestarti
ngaddr essofmar k[
0]is2120d.Then,
theaddressoft hemar k[1]wil
lbe2124d.Si mi
larl
y,t
he
addressofmar k[2]wil
l be2128dandsoon.
Thisisbecauset hesizeofaf loati
s4by tes.

Howt
oini
ti
ali
zeanar
ray
?
Iti
spossi
blet
oini
ti
ali
zeanar
raydur
ingdecl
arat
ion.For
example,

i
ntmar
k[5]={
19,
10,
8,17,
9};
Youcanal
soi
nit
ial
i
zeanar
rayl
i
ket
his.
i
ntmar
k[]={
19,
10,
8,17,
9};
Here,
wehav en'
tspecif
iedthesi
ze.However,
the
compil
erknowsitssizeis5aswear ei
nit
ial
i
zingi
twi
th
5elements.

Her
e,

mar
k[0]i
sequal
to19
mar
k[1]i
sequal
to10
mar
k[2]i
sequal
to8
mar
k[3]i
sequal
to17
mar
k[4]i
sequal
to9

ChangeVal
ueofAr
rayel
ement
s

i
ntmar
k[5]={
19,
10,
8,17,
9}

/
/maket heval
ueoft
het
hir
del
ementt
o-1
mar
k[2]=-1;

/
/maket hev
alueoft
hef
if
thel
ementt
o0
mar
k[4]=0;
I
nputandOut
putAr
rayEl
ement
s
Her
e'showyoucantakei
nputf
rom t
heuserandst
orei
t
i
nanarrayel
ement
.

//takei
nputandst
oreiti
nthe3r
del
ement
scanf
​ (
"%d"
,&mark[
2])
;

//takei
nputandst
oreiti
nthei
thel
ement
scanf(
"%d"
,&mark[
i-
1])
;s
Here'
showy
oucanpr
intani
ndi
vi
dual
elementofan
ar
ray.

//pri
ntthefi
rstel
ementoft
hear
ray
pri
ntf
("%d",
mar k[
0])
;

//pri
ntthethi
rdelementoft
hear
ray
pri
ntf
("%d",
mark[2])
;

//pri
ntit
helementofthear
ray
pri
ntf
("%d",
mark[
i-
1])
;

Ar
ray
sinDet
ail
Ar
raysareimport
anttoCandshouldneedal otmor
e
at
tent
ion.Thefol
lowi
ngi
mportantconcept
srelat
edt
o
ar
rayshoul
dbecleart
oaCprogrammer−
Sr
.No. Concept&Descr
ipt
ion
1 Mul
ti
-di
mensi
onal
arr
ays

C suppor t
s mul ti
dimensi
onal ar
rays. The
simplestf
orm ofthemulti
dimensi
onalar
rayis
thetwo-di
mensionalarr
ay.

2 Passi
ngar
ray
stof
unct
ions
Youcanpasstothefunct
ionapoint
ert
oan
ar
raybyspeci
fyi
ngthearr
ay'snamewit
hout
anindex.

3 Ret
urnar
rayf
rom af
unct
ion
Cal
l
owsaf
unct
iont
oret
urnanar
ray
.

4 Poi
ntert
oanar
ray
You can generat
e a poi
nter t
ot he f
ir
st
el
ementofanar raybysi
mplyspeci
fyi
ngthe
ar
rayname,wit
houtanyi
ndex.

#i
ncl
ude<st
dio.
h>

i
ntmai
n(){

i
ntn[10]
;/*ni
sanar
rayof10i
nteger
s*/
i
nti
,j
;

/
*ini
ti
ali
zeel
ement
sofar
raynt
o0*
/
f
or(i=0;
i<10;i
++){
n[i
]=i+100;
/*setel
ementatl
ocat
ioni
toi
+100*
/
}

/
*outputeacharr
ayel
ement'
sval
ue* /
f
or(j=0; j
<10;j
++){
pr
intf
("El
ement
[%d]=%d\
n",j
,n[
j])
;
}

ret
urn0;
}
When the abov
e code i
s compi
l
ed and ex
ecut
ed,i
t
pr
oducesthefol
lowi
ngresul
t−
El
ement
[0]=100
El
ement
[1]=101
El
ement
[2]=102
El
ement
[3]=103
El
ement
[4]=104
El
ement
[5]=105
El
ement
[6]=106
El
ement
[7]=107
El
ement
[8]=108
El
ement
[9]=109

Exampl
e1:
Arr
ayI
nput
/Out
put

//Progr
am tot ake5v al
uesf
rom t
heuserandst
ore
them i
nanar ray
//Pri
nttheelement sstor
edi
nthearr
ay
#incl
ude<stdio.h>
i
ntmain(
){
i
ntv
alues[
5];

pr
int
f("
Ent
er5i
nteger
s:"
);

/
/takinginputandstori
ngi
tinanar
ray
f
or(i
nti=0; i<5;++i
){
scanf(
"%d",&val
ues[i
])
;
}

pr
int
f("
Displ
ayi
ngi
nteger
s:"
);

/
/print
ingel
ementsofanarr
ay
f
or(i
nti=0;i<5;++i){
pri
ntf
("%d\
n",
values[
i]
);
}
r
etur
n0;
}
Out
put
Enter5i
ntegers:1
-3
34
0
3
Displ
ayi
nginteger
s:1
-3
34
0
3
Her
e,wehav
eusedaf
orl
oopt
otake5i
nput
sfr
om t
he
userandst orethem inanar
ray
.Then,
using
anotherforloop,theseel
ementsar
edispl
ayedont
he
screen.

Exampl
e2:
Cal
cul
ateAv
erage

//Progr
am t
ofi
ndt
heav
erageofnnumber
susi
ng
arr
ays

#i
ncl
ude<stdi
o.h>
i
ntmain(
)
{
i
ntmarks[
10],i
,n,
sum =0,
aver
age;

pri
ntf
("Ent
ernumberofel
ement
s:"
);
scanf
("%d",&n)
;

f
or(i
=0;i
<n; ++i
)
{
pri
ntf
("Enternumber
%d: "
,i
+1)
;
scanf
("%d",&marks[
i]
);

//addi
ngi
ntegersent
eredbyt
heusert
othesum
v
ari
able
sum +=marks[
i]
;
}

av
erage=sum/n;
pr
int
f("
Aver
age=%d"
,av
erage)
;

r
etur
n0;
}
Out
put
Entern:5
Enternumber
1:45
Enternumber
2:35
Enternumber
3:38
Enternumber
4:31
Enternumber
5:49
Average=39
Here,wehavecomput
edt
heav
erageofnnumber
s
ent
eredbytheuser
.

Accessel
ement
soutofi
tsbound!
Supposey
oudecl
aredanar
rayof10el
ement
s.Let
'
ssay
,

i
ntt
est
Arr
ay[
10]
;

Youcanaccesst hearrayelement s
fr
om t estArray
[0]totestArray[9].
Nowl et
'ssayifyout rytoaccesst est
Arr
ay[
12].The
el
ementi snotav ai
lable.Thismaycauseunexpect ed
output( undefi
nedbehav i
our).Somet i
mesy oumightget
aner rorandsomeot hertimey ourprogr
am mayr un
correctl
y .
Hence, youshoul dnev eraccessel ementsofanar ray
outsideofi t
sbound.
InCprogrammi
ng,y
oucancr
eateanar
rayofar
rays.
Thesearr
aysar
eknownasmult
idi
mensi
onalar
ray
s.For
example,

f
loatx[
3][
4];
Here,
xisatwo-
dimensional(
2d)ar
ray.Thearr
aycan
hol
d12elements.Youcanthi
nkthearrayasatabl
ewit
h
3rowsandeachrowhas4col umns.

Si
milarl
y,y
oucandecl
areat
hree-
dimensi
onal
(3d)ar
ray
.
Forexample,

f
loaty
[2]
[4]
[3]
;
Her
e,t
hear
rayycanhol
d24el
ement
s.

I
nit
ial
i
zingamul
ti
dimensi
onal
arr
ay
Herei
showy oucanini
ti
ali
zet
wo-
dimensi
onal
andt
hree
-
dimensi
onal
arrays:
I
nit
ial
i
zat
ionofa2dar
ray

/
/Di
ff
erentway
stoi
nit
ial
i
zet
wo-
dimensi
onal
arr
ay

i
ntc[
2][
3]={
{1,
3,0}
,{-
1,5,
9}}
;

i
ntc[
][
3]={
{1,
3,0}
,{-
1,5,
9}}
;

i
ntc[
2][
3]={
1,3,
0,-
1,5,
9};

I
nit
ial
i
zat
ionofa3dar
ray
Youcani
nit
ial
i
zeathree-di
mensional
arr
ayi
nasimil
ar
wayli
keatwo-di
mensionalar
ray
.Here'
sanexampl
e,

i
nttest[
2][
3][
4]={
{
{3,4,2,3}
,{0,-
3,9,11}
,{23,12,
23,2}},
{
{13,4,56,3},
{5,9,
3,5},{3,
1,4,9}
}};

Exampl
e1:
Two-
dimensi
onal
arr
ayt
ost
oreandpr
int
val
ues

//Cprogram tostoret
emper
atur
eoft
woci
ti
esofa
weekanddi splayi
t.
#incl
ude<st di
o.h>
constintCITY=2;
constintWEEK=7;
i
ntmai n()
{
i
ntt
emper
atur
e[CI
TY]
[WEEK]
;

//Usingnest edloopt ost oreval


uesina2dar
ray
for(i
nti =0;i<CI TY;++i )
{
for(i
ntj =0;j <WEEK; ++j)
{
pri
ntf("
City%d, Day%d: ",i+1,j+1)
;
scanf("%d",&temperat ure[
i]
[j
])
;
}
}
print
f("
\nDisplayingvalues: \
n\n")
;

/
/Usi ngnestedloopt odispl
ayvl
uesofa2dar
ray
f
or(inti=0; i<CITY;++i)
{
f
or(intj=0; j<WEEK; ++j)
{
pr
intf
("Cit
y%d, Day%d=%d\ n"
,i+1,
j+1,
t
emper ature[
i]
[j
])
;
}
}
r
eturn0;
}
Out
put
Ci
ty1,
Day1:
33
Ci
ty1,
Day2:
34
Ci
ty1,
Day3:
35
Ci
ty1,
Day4:
33
Ci
ty1,
Day5:
32
Ci
ty1,
Day6:
31
Ci
ty1,
Day7:
30
Ci
ty2,
Day1:
23
Ci
ty2,
Day2:
22
Ci
ty2,
Day3:
21
Ci
ty2,
Day4:
24
Ci
ty2,
Day5:
22
Ci
ty2,
Day6:
25
Ci
ty2,
Day7:
26

Di
spl
ayi
ngv
alues:

Ci
ty1,
Day1=33
Ci
ty1,
Day2=34
Ci
ty1,
Day3=35
Ci
ty1,
Day4=33
Ci
ty1,
Day5=32
Ci
ty1,
Day6=31
Ci
ty1,
Day7=30
Ci
ty2,
Day1=23
Ci
ty2,
Day2=22
Ci
ty2,
Day3=21
Ci
ty2,
Day4=24
Ci
ty2,
Day5=22
Ci
ty2,
Day6=25
Ci
ty2,
Day7=26

Exampl
e2:
Sum oft
womat
ri
ces

//Cpr
ogr
am t
ofi
ndt
hesum oft
womat
ri
cesofor
der
2*2
#i
nclude<st di
o.h>
i
ntmai n()
{
f
loata[2][
2],b[
2][
2],
resul
t[
2][
2];

//Takingi nputusingnestedf
orloop
print
f("
Enterel ementsof1stmatri
x\n"
);
for(i
nti =0; i<2;++i)
for(i
ntj =0; j<2;++j)
{
pri
ntf("
Ent era%d%d: "
,i+1,j+1);
scanf("%f",&a[i
][
j]
);
}

//Takingi nputusingnestedf
orloop
print
f("
Enterel ementsof2ndmat r
ix\
n")
;
for(i
nti =0; i<2;++i)
for(i
ntj =0; j<2;++j)
{
pri
ntf("
Ent erb%d%d: "
,i+1,j+1);
scanf("%f",&b[i
][
j]
);
}

/
/addi ngcorr
espondingelement
soft
woar
ray
s
f
or(inti=0;i<2;++i )
f
or(intj=0;j<2; ++j)
{
r
esult[
i]
[j
]=a[i
][
j]+b[i]
[j
];
}

//Displ
ay i
ngthesum
pri
ntf(
"\nSum OfMatr
ix:
")
;
f
or(inti=0;i<2;++i)
f
or(intj=0;j<2;++j)
{
pr
intf
("%.
1f\
t",
resul
t[i
][
j]
);

i
f(j==1)
pr
int
f("
\n"
);
}
r
eturn0;
}
Out
put
Ent
erel
ement sof1stmat
ri
x
Ent
era11:
2;
Ent
era12:
0.5;
Ent
era21:
-1.1;
Ent
era22:
2;
Ent
erel
ement sof2ndmatr
ix
Ent
erb11:0.
2;
Ent
erb12:0;
Ent
erb21:0.
23;
Ent
erb22:23;

Sum OfMatr
ix:
2.2 0.5
-0.
9 25.0
Exampl
e3:
Thr
ee-
dimensi
onal
arr
ay

//CProgr
am t
ost
oreandpr
int12v
aluesent
eredbyt
he
user

#i
ncl
ude<stdi
o.h>
i
ntmain(
)
{
i
ntt
est[
2][
3][
2];

pr
int
f("
Ent
er12v
alues:
\n"
);

f
or( i
nti=0;i<2;++i)
{
f
or( i
ntj=0;j<3;++j)
{
f
or( i
ntk=0;k<2; ++k)
{
scanf(
"%d"
,&test
[i
][
j]
[k]
);
}
}
}

/
/Pr
int
ingv
alueswi
thpr
operi
ndex.

printf(
"\nDispl
ayi
ngv al
ues:\
n")
;
for( i
nti =0;i<2;++i)
{
for( i
ntj =0;j<3;++j)
{
for( i
ntk=0; k<2; ++k)
{
pri
ntf("
test
[%d]
[%d][%d]=%d\n"
,i
,j
,k,
test
[i
][
j]
[k]
);
}
}
}

r
etur
n0;
}
Out
put
Ent
er12v
alues:
1
2
3
4
5
6
7
8
9
10
11
12

Display
ingValues:
test[
0][
0][
0]=1
test[
0][
0][
1]=2
test[
0][
1][
0]=3
test[
0][
1][
1]x=4
test[
0][
2][
0]=5
test[
0][
2][
1]=6
test[
1][
0][
0]=7
test[
1][
0][
1]=8
test[
1][
1][
0]=9
test[
1][
1][
1]=10
t
est
[1]
[2]
[0]=11
t
est
[1]
[2]
[1]=12

Passi
ngi
ndi
vi
dual
arr
ayel
ement
s
Passi
ngarr
ayelementst
oaf unct
ioni
ssi
mil
ar
topassi
ngvar
iabl
estoafuncti
on.

Exampl
e1:
Passi
nganar
ray

#incl
ude<st dio.
h>
voiddisplay
(intage1,
intage2)
{
pri
ntf("
%d\ n",
age1)
;
pri
ntf("
%d\ n",
age2)
;
}

i
ntmain()
{
i
ntageArr
ay[
]={
2,8,
4,12}
;

//Passi
ngsecondandthi
rdel
ement
stodi
spl
ay(
)
displ
ay(
ageAr
ray[
1],
ageAr
ray[
2])
;
retur
n0;
}
Out
put
8
4
Exampl
e2:
Passi
ngar
ray
stof
unct
ions

//Program t
ocalcul
atet
hesum ofar
rayel
ement
sby
passingtoafuncti
on

#incl
ude<stdio.
h>
fl
oatcal
culateSum(f
loatage[
])
;

i
ntmai n(){
f
loatresul
t,age[
]={
23.
4,55,
22.
6,3,
40.
5,18}
;

//agear r
ayi spassedtocal
cul
ateSum(
)
resul
t=cal culat
eSum(age);
print
f("
Result=%. 2f
",r
esul
t)
;
retur
n0;
}

f
loatcal
cul
ateSum(
fl
oatage[
]){

f
loatsum =0.
0;

f
or(
inti
=0; i
<6; ++i
){
sum +=age[i
];
}

r
etur
nsum;
}
Out
put
Resul
t=162.
50
Topassanent
ir
ear
rayt
oaf
unct
ion,
onl
ythenameof
t
hear
rayi
spassedasanar
gument
.

r
esul
t=cal
cul
ateSum(
age)
;
Howev
er,
not
icet
heuseof[
]int
hef
unct
iondef
ini
ti
on.
f
loatcal
cul
ateSum(
fl
oatage[
]){
.
...
.
}
Thi
sinf
ormst hecompi
lert
hatyouar
epassi
ngaone-
di
mensional
ar r
aytot
hefunct
ion.

Passi
ngMul
ti
dimensi
onal
Arr
ayst
oaFunct
ion
Topassmulti
dimensi
onalar
ray
st oafuncti
on,onl
ythe
nameofthearr
ayispassedtothefunct
ion(
simil
arto
one-
dimensi
onalar
ray
s).
Exampl
e3:
Passi
ngt
wo-
dimensi
onal
arr
ays

#include<stdio.h>
voiddisplayNumber s(i
ntnum[2][
2])
;
i
ntmai n()
{
intnum[ 2]
[2];
printf(
"Ent
er4number s:
\n")
;
for(inti=0; i
<2; ++i)
for( i
ntj=0; j
<2; ++j)
scanf
("%d",&num[i]
[j
])
;

/
/passi
ngmul
ti
-di
mensi
onal
arr
ayt
oaf
unct
ion
displ
ayNumber
s(num)
;
retur
n0;
}

v
oi ddispl ayNumber s(i
ntnum[ 2]
[2]
)
{
pri
ntf (
"Displayi
ng:\n");
for(inti =0; i
<2; ++i){
for(intj =0; j
<2; ++j){
printf(
"%d\n",num[ i
][
j]
);
}
}
}
Out
put
Enter4number
s:
2
3
4
5
Displ
ayi
ng:
2
3
4
5
Addr
essi
nC
I
fyouhaveav ar
iablevari
nyourpr
ogram,
&varwi
llgi
ve
youi
tsaddressi
nt hememory.
Wehaveusedaddr essnumeroust
imeswhil
eusi
ng
t
hescanf(
)functi
on.
scanf
("%d"
,&v
ar)
;
Here,theval
ueenteredbytheuseri
sst
oredi
nt he
addressofvarvar
iable.Let
'st
akeawor
kingexample.
#incl
ude<stdi
o.h>
i
ntmai n(
)
{
i
ntvar=5;
pri
ntf
("v
ar:
%d\ n"
,var
);

//Noti
cet heuseof&bef
orevar
pri
ntf
("addressofv
ar:
%p",&v
ar)
;
ret
urn0;
}
Out
put
var
:5
addr
essofv
ar:
2686778
Note:
Whenwer unt
hiscodepr
obabl
ywegetdi
ff
erent
address.
CPoi
nter
s
Apointerisavari
ablewhosev al
ueistheaddressof
anot
herv ari
abl
e,i
.e.,
directaddressofthememor y
l
ocati
on.Likeanyv ar
iableorconstant
, y
oumustdecl ar
e
apoint
erbef or
eusingittostoreanyv ari
abl
eaddress.
Point
ers(
poi
nterv
ari
ables)arespeci
alvari
abl
est
hatar
e
usedtost
oreaddr
essesratherthanval
ues.
Poi
nterSy
ntax
Her
eishowwecandecl
arepoi
nter
s.

i
nt*p;
Here,
wehavedeclaredapoi
nterpofintt
ype.
Youcanal
sodeclarepoi
nter
sintheseways.

i
nt*p1;
i
nt*p2;

Let
'st
akeanot
herexampl
eofdecl
ari
ngpoi
nter
s.

i
nt*p1,
p2;
Here,wehavedecl
aredapoi
nterp1andanor
mal
var
iablep2.
Assi
gni
ngaddr
essest
oPoi
nter
s
Let
'st
akeanexampl
e.

i
nt*pc,
c;
c=5;
pc=&c;
Here,
5isassignedt
othecvari
able.And,
theaddr
ess
ofcisassi
gnedtothepcpoi
nter
.

GetVal
ueofThi
ngPoi
ntedbyPoi
nter
s
Togett
heval
ueofthethi
ngpoi
ntedbyt
hepoi
nter
s,we
uset
he*oper
ator
.Forexampl
e:
i
nt*pc,c;
c=5;
pc=&c;
pr
int
f("
%d",*
pc)
;//Out
put
:5
Here,theaddressofci sassi gnedt othepcpoi nt
er.To
getthevaluestoredint hataddr ess,weused* pc.
Note:Intheabov eexampl e,
pci sapoi nt
er,not*pc.You
cannotandshoul dnotdosomet hi
ngli
ke* pc=&c;
Bytheway ,*iscalledtheder eferenceoperator(when
workingwithpointers)
.Itoper atesonapoi nterand
giv
est hevaluestoredint hatpoi nt
er.
Changi
ngVal
uePoi
ntedbyPoi
nter
s
Let
'st
akeanexampl
e.

i
nt*pc,c;
c=5;
pc=&c;
c=1;
pr
int
f("
%d",c);//Output:
1
pr
int
f("
%d",*pc)
;//Ouptut
:1
Wehav eassi
gnedt headdressofctothepcpoint
er.
Then,wechangedt heval
ueofct o1.Sincepcandthe
addressofcisthesame, *pcgi
vesus1.
Let'
stakeanotherexample.

i
nt*pc,c;
c=5;
pc=&c;
*pc=1;
pri
ntf
("%d"
,*pc)
;//Ouptut
:1
pri
ntf
("%d"
,c);//Output:
1
Wehav eassignedtheaddr
essofctothepcpoi
nter
.
Then,wechanged* pcto1using*
pc=1;.Si
ncepcand
theaddressofcisthesame,cwil
lbeequalt
o1.
Let'
stakeonemor eexample.

i
nt*pc,
c,d;
c=5;
d=-15;

pc=&c;
pri
ntf
("%d"
,*pc)
;//Out
put
:5
pc=&d;
pri
ntf
("%d"
,*pc)
;//Oupt
ut:
-15
I
nit
ial
l
y,theaddressofcisassignedtothepcpoi
nter
usi
ngpc=&c; .Si
ncecis5,*pcgi v
esus5.
Then,t
headdressofdisassignedt ot
hepcpoint
er
usi
ngpc=&d; .Sincedi
s-15,*pcgivesus-15.

Exampl
e:Wor
kingofPoi
nter
s
Let
'st
akeawor
kingexampl
e.

#i
ncl
ude<st
dio.
h>
i
ntmain(
)
{
i
nt*pc,
c;

c=22;
pr
int
f("
Addr
essofc:%p\n"
,&c);
pr
int
f("
Val
ueofc:%d\n\
n",c)
;//22

pc=&c;
pr
int
f("
Addr
essofpoi
nterpc:%p\
n",pc);
pr
int
f("
Cont
entofpoi
nterpc:
%d\n\n",
*pc);
//22

c=11;
pr
int
f("
Addr
essofpoi
nterpc:%p\
n",pc);
pr
int
f("
Cont
entofpoi
nterpc:
%d\n\n",
*pc);
//11

*pc=2;
pri
ntf
("Addr
essofc:%p\n"
,&c);
pri
ntf
("Val
ueofc:%d\n\
n",c)
;//2
ret
urn0;
}
Out
put
Addr
essofc:2686784
Val
ueofc:22

Addr
essofpoi
nterpc:2686784
Cont
entofpoi
nterpc:
22

Addr
essofpoi
nterpc:2686784
Cont
entofpoi
nterpc:
11

Addr
essofc:2686784
Val
ueofc:2

Explanati
onoft
hepr
ogr
am
1.
int
*pc, c;

Here,apointerpcandanor mal v
ari
ablec,bothof
typeint
,iscreat
ed.
Sincepcandcar enoti ni
ti
ali
zedatini
ti
all
y,
point
erpcpoi nt
stoei t
hernoaddressorar andom
address.And,vari
ablechasanaddr essbutcontai
ns
random garbagevalue.
2.
c=22;

Thisassi
gns22tothevari
ablec.Thati
s,22i
sst
oredi
n
thememor yl
ocat
ionofvari
ablec.

3.
pc=&c;

Thi
sassi
gnst
headdr
essofv
ari
abl
ect
othepoi
nterpc.

4.
c=11;

Thi
sassi
gns11t
ovar
iabl
ec.

5.
*pc=2;

Thischangetheval
ueatt
hememor
ylocat
ionpoi
ntedby
thepoint
erpcto2.
Commonmi
stakeswhenwor
kingwi
thpoi
nter
s
Suppose,y
ouwantpoi
nterpct
opoi
ntt
otheaddr
ess
ofc.Then,
i
ntc,
*pc;

//pci
saddressbutci
snot
pc=c;//Er
ror

/
/&ci
saddr
essbut*
pci
snot
*
pc=&c;
//Err
or

//bot
h&candpcar
eaddr
esses
pc=&c;

/
/bot
hcand*
pcv
alues
*
pc=c;
Here'sanexampl
eofpoi
ntersy
ntaxbegi
nner
sof
tenf
ind
confusi
ng.

#i
ncl
ude<st
dio.
h>
i
ntmain(
){
i
ntc=5;
i
nt*p=&c;

pri
ntf
("%d"
,*p)
;//5
ret
urn0;
}
Whydidn'
twegetaner
rorwhenusi
ngi
nt*
p=&c;
?
I
t'
sbecause
i
nt*
p=&c;
i
sequi
val
entt
o

i
nt*
p:
p=&c;
Inbot
hcases,wearecreat
ingapoi
nterp(not*
p)and
assi
gni
ng&ct oi
t.
Toavoidt
hisconf
usion,wecanusethest
atementl
ike
thi
s:

i
nt*p=&c;
NULLPoi
nter
s
Iti
salwaysagoodpr act
icetoassi
gnaNULLv al
uetoa
poi
nterv ar
iabl
ei n case you do nothave an ex
act
addresstobeassi gned.Thisi sdoneatthet i
meof
var
iabledeclar
ati
on.Apoi nt
erthati
sassi
gnedNULLi s
cal
ledanullpoint
er.
TheNULLpointeri
saconstantwi t
hav
alueofzer
o
def
inedi
nsev
eralst
andar
dli
brar
ies.

#i
ncl
ude<st
dio.
h>

i
ntmai
n(){

i
nt*
ptr=NULL;

pr
int
f("
Thev
alueofpt
ris:
%x\
n",
ptr)
;
ret
urn0;
}
When the abov
e code i
s compi
l
ed and ex
ecut
ed,i
t
pr
oducesthefol
lowi
ngresul
t−
Thev alueofpt ris0
Inmostoft heoper atingsy stems,pr ogramsar enot
permi t
tedt oaccessmemor yataddr ess0becauset hat
memor yi sreservedbyt heoper ati
ngsy st
em.Howev er
,
the memor y addr ess 0 has speci alsi
gnifi
cance;it
signalst hatthepoi nteri snoti ntendedtopoi nttoan
accessi bl
ememor yl ocation.Butbyconv enti
on,ifa
pointercont ainsthenul l(zero)v alue,iti
sassumedt o
pointtonot hing.
Tocheckf
oranul
lpoi
nter
,youcanusean'
i
f'st
atement
asf
oll
ows−
i
f(ptr
) / *succeedsi
fpi
snotnul
l*/
i
f(!
ptr)/ *succeedsi
fpi
snul
l*/
Pointer
sinDetail
Point
ershavemanybuteasyconceptsandt heyare
veryimport
ant to C progr
amming. The f
oll
owing
i
mpor t
antpoi
nterconcept
sshoul
dbecl eart
oanyC
progr
ammer−
Sr
.No. Concept&Descr
ipt
ion

1 Poi
nterar
it
hmet
ic

Ther
earefourarit
hmeticoper
ator
sthatcan
beusedi
npoint
ers:++,
--,
+,-

2 Ar
rayofpoi
nter
s
Youcandef
inear
ray
stohol
danumberof
poi
nter
s.

3 Poi
ntert
opoi
nter
Call
owsy
out
ohav
epoi
nteronapoi
nterand
soon.

4 Passi
ngpoi
nter
stof
unct
ionsi
nC
Passing an ar
gumentby r ef
erence orby
addressenablethepassedargumentt obe
changedinthecall
ingfunct
ionbyt hecal
l
ed
functi
on.

5 Ret
urnpoi
nterf
rom f
unct
ionsi
nC
Callowsafunct
iontoreturnapointert
ot he
l
ocalvari
abl
e,st
ati
cvari
able,anddynamicall
y
al
locat
edmemor yaswell
.

Rel
ati
onshi
pBet
weenAr
ray
sandPoi
nter
s
Anar
rayi
sabl
ockofsequent
ial
data.Let
'swri
tea
pr
ogr
am t
opri
ntaddr
essesofar
rayelement
s.

#i
ncl
ude<st
dio.
h>
i
ntmain(
){
i
ntx[
4];
i
nti
;

f
or(
i=0;i<4;++i
){
pr
int
f("
&x[
%d]=%p\n"
,i
,&x[
i]
);
}

pr
int
f("
Addr
essofar
rayx:
%p"
,x)
;

ret
urn0;
}
Out
put
&x[
0]=1450734448
&x[
1]=1450734452
&x[
2]=1450734456
&x[
3]=1450734460
Addr
essofarr
ayx:1450734448
Thereisadi f
ferenceof4by tesbetweent wo
consecutiveelementsofarrayx.Itisbecausethesi
ze
ofintis4by t
es( onourcompi l
er).
Noticethat,t
headdr essof&x [
0]andxi sthesame.I
t'
s
becauset hevariabl
enamexpoi nt
st othefi
rstel
ement
ofthearray.

From t
heaboveexample,
iti
scl
earthat&x[
0]i
s
equi
valentt
ox.And,
x[0]i
sequi
val
entto*x.
Simi
lar
ly,
 &x[
1]i
sequi
val
entt
ox+1andx[
1]i
sequi
val
entt
o*(
x+1)
.
 &x[
2]i
sequi
val
entt
ox+2andx[
2]i
sequi
val
entt
o*(
x+2)
.
 .
..
 Basi
cal
l
y,&x[
i]i
sequi
val
entt
ox+i
andx[
i]i
sequi
val
ent
to*(
x+i
).
Exampl
e1:
Poi
nter
sandAr
ray
s

#incl
ude<st di
o.h>
i
ntmai n(){
i
nti,x[6]
,sum =0;
pri
ntf(
"Enter6numbers:"
);
for(
i=0; i<6;++i
){
//Equival
enttoscanf
("%d"
,&x[
i]
);
scanf("
%d",x+i
);

//Equi
v al
enttosum +=x[
i]
sum +=*(x+i
);
}
pri
ntf
("Sum =%d",sum);

r
etur
n0;
}
Wheny
our
unt
hepr
ogr
am,
theout
putwi
l
lbe:

Ent
er6number
s:2
3
4
4
12
4
Sum =29
Here,wehav
edecl
aredanarr
ayxof6el
ements.To
accessel
ement
softhearr
ay,wehav
eusedpoint
ers.
Inmostcont ex
ts,ar
raynamesdecayt
opointer
s.In
simplewor ds,arr
aynamesareconver
tedtopoint
ers.
That'
sther easonwhyy oucanusepoi
nter
stoaccess
elementsofar ray
s.However,
youshouldr
emember
thatpointersandarraysar
enotthesame.
Therear eaf ewcaseswherearr
aynamesdon'tdecayto
point
ers.

Exampl
e2:
Arr
aysandPoi
nter
s

#i
nclude<stdio.
h>
i
ntmai n(
){
i
ntx[5]={1,2,3,4,
5};
i
nt*ptr;

//ptri
sassignedt
headdr
essoft
het
hir
del
ement
ptr=&x[2]
;

pr
int
f("
*ptr=%d\ n"
,*ptr
);/ /3
pr
int
f("
*(ptr
+1)=%d\ n",*
(ptr+1))
;//4
pr
int
f("
*(ptr
-1)=%d",*(
ptr-
1));//2

r
etur
n0;
}
Wheny
our
unt
hepr
ogr
am,
theout
putwi
l
lbe:

*
ptr=3
*
(ptr
+1)=4
*
(ptr
-1)=2
Inthi
sexampl e, &x[
2] ,
theaddr essofthethir
delement ,
i
sassignedt ot hept rpoint
er.Hence, 3wasdisplayed
whenwepr inted* ptr.
And,pri
nti
ng* (ptr+1)gi v
esust hefourt
helement.
Simil
arl
y,pr
inting* (
pt r
-1)givesust hesecondelement .
InCprogrammi ng,itisalsopossi bl
etopassaddr esses
asargument stof unctions.
Toaccepttheseaddressesint
hefuncti
ondefi
nit
ion,
we
canusepointer
s.It
'sbecausepoi
nter
sareusedtostore
addr
esses.Let'
stakeanexample:

Exampl
e:Cal
lbyr
efer
ence

#incl
ude<stdi
o.h>
voidswap(
int*n1,i
nt*
n2)
;

i
ntmain()
{
i
ntnum1=5,
num2=10;

//addr
essofnum1andnum2i
spassed
swap(&num1,&num2)
;

pri
ntf
("num1=%d\
n",num1)
;
pri
ntf
("num2=%d"
,num2);
ret
urn0;
}

v
oidswap(
int
*n1,
int
*n2)
{
i
ntt
emp;
t
emp=*n1;
*
n1=*n2;
*
n2=temp;
}
Wheny
our
unt
hepr
ogr
am,
theout
putwi
l
lbe:

num1=10
num2=5
Theaddressofnum1andnum2ar epassedt
o
theswap()f
uncti
onusi
ngswap(&num1,&num2);
.
Point
ersn1andn2acceptt
heseargumentsi
nthe
funct
iondef
ini
ti
on.
v
oidswap(
int
*n1,
int
*n2){
.
...
.
}
When* n1and* n2arechangedi nsi
de
theswap( )functi
on,num1andnum2i nside
themai n()f
unctionarealsochanged.
I
nsidetheswap( )f
uncti
on, *
n1and* n2swapped.
Hence, num1andnum2ar ealsoswapped.
Noticethat,swap()isnotretur
ninganyt
hing;i
tsr
etur
n
typeisv oi
d.
Thistechniqueisknownascal l
byrefer
enceinC
programmi ng.
Exampl
e2:
Passi
ngPoi
nter
stoFunct
ions

#i
ncl
ude<st
dio.
h>

v
oidaddOne(i
nt*ptr
){
(
*pt
r)++;
//adding1to*
ptr
}

i
ntmain()
{
i
nt*p,i=10;
p=&i;
addOne(p)
;

printf
("%d\n"
,*p)
;//11
printf
("Addr
essofpoint
erp:
%p\
n",
p);
return0;
}
Here,theval
uest oredatp,*p,is10init
iall
y.
Wet henpassedt hepointerptotheaddOne( )funct
ion.
Thept rpoi
ntergetsthisaddressin
theaddOne()f unct
ion.
I
nsidet hef
unct i
on,weincreasedthev aluest
ored
atptrby1usi ng(*ptr
)++;
.Sinceptrandppoi nter
sbot h
havethesameaddr ess,*pinsi
demai n()isal
so11.

CDy
nami
cMemor
yAl
locat
ion
Nowy ou'
lll
earntodynamical
lyal
locat
ememor yinyour
Cprogram usingst
andardli
brar
yfuncti
ons:mal
loc(
),
cal
loc(
),f
ree()andreal
loc(
).
Asy ouknow, anarr
ayisacoll
ect
ionofafi
xednumber
ofvalues.Oncethesizeofanarr
ayisdecl
ared,
you
cannotchangei t
.
Sometimest hesi
zeofthearrayyoudecl
aredmaybe
i
nsuffi
cient
.Tosolvethi
sissue,y
oucanallocat
e
memor ymanuallydur
ingrun-t
ime.Thi
sisknownas
dynamicmemor yall
ocati
oninCpr ogr
ammi ng.
Toall
ocatememor ydynami cal
ly,
li
braryfuncti
ons
aremall
oc()
,call
oc()
,reall
oc()andfree()areused.
Thesefunct
ionsaredefinedinthe<stdli
b.h>headerf
il
e.

Cmal
l
oc(
)
Thename"
mal
l
oc"st
andsf
ormemor
yal
l
ocat
ion.
Themalloc(
)funct
ionreservesablockofmemor yoft
he
speci
fi
ednumberofby tes.And,i
tretur
ns
apoint
erofvoidwhichcanbecast edintopoi
nter
sof
anyfor
m.

Sy
ntaxofmal
l
oc(
)

pt
r=(
cast
Type*
)mal
l
oc(
size)
;
Exampl
e
pt
r=(
fl
oat
*)mal
l
oc(
100*si
zeof
(fl
oat
));
Theabov estatementall
ocates400bytesofmemory.
It
'sbecausethesi zeoff
loatis4byt
es.And, t
he
point
erptrholdstheaddressofthefi
rstbyteint
he
all
ocatedmemor y .
Theexpressi
onr esultsi
naNULLpoi nteri
fthememory
cannotbeall
ocat ed.

Ccal
l
oc(
)
Thename"
cal
l
oc"st
andsf
orcont
iguousal
l
ocat
ion.
Themal l
oc(
)functi
onallocatesmemor yandleav
esthe
memor yuni
nit
ial
ized.Wher eas,
thecal
loc(
)funct
ion
al
locat
esmemor yandi nit
iali
zesal
lbit
stozero.

Sy
ntaxofcal
l
oc(
)

pt
r=(
cast
Type*
)cal
l
oc(
n,si
ze)
;
Exampl
e:
pt
r=(
fl
oat
*)cal
l
oc(
25,
sizeof
(fl
oat
));
Theabov
est at
emental
locat
esconti
guousspacei
n
memoryfor25element
softypefl
oat.
Cf
ree(
)
Dynamicall
yall
ocatedmemorycreat
edwi t
h
ei
thercal
loc()ormall
oc(
)doesn'
tgetfr
eedont hei
rown.
Youmustexpl i
cit
lyusef
ree(
)torel
easethespace.

Sy
ntaxoff
ree(
)

f
ree(
ptr
);
Thi
sstatementfr
eest
hespaceal
l
ocat
edi
nthememor
y
poi
ntedbyptr.

Exampl
e1:
mal
l
oc(
)andf
ree(
)

//Progr
am t
ocal
cul
atet
hesum ofnnumber
sent
ered
bytheuser

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

i
ntmain()
{
i
ntn,i
,*pt
r,sum =0;

pri
ntf
("Ent
ernumberofel
ement
s:"
);
scanf
("%d",&n)
;

pt
r=(
int
*)mal
l
oc(
n*si
zeof
(i
nt)
);
/
/i fmemor ycannotbeal
locat
ed
i
f(
pt r==NULL)
{
print
f("
Err
or!memorynotall
ocat
ed.
")
;
exit(
0);
}

pri
ntf(
"Enterelement
s:"
);
for(
i=0; i
<n; ++i)
{
scanf(
"%d" ,
ptr+i)
;
sum +=* (pt
r+i);
}

pr
int
f("
Sum =%d"
,sum)
;

/
/deall
ocat
ingt
hememor
y
f
ree(
ptr
);

r
etur
n0;
}
Her
e,wehav
edynamical
l
yal
l
ocat
edt
hememor
y
f
ornnumberofi
nt.

Exampl
e2:
cal
l
oc(
)andf
ree(
)

//Progr
am t
ocal
cul
atet
hesum ofnnumber
sent
ered
bytheuser
#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

i
ntmai n()
{
i
ntn, i
,*pt
r,sum =0;
pri
ntf(
"Ent
ernumberofel
ement
s:"
);
scanf(
"%d",&n)
;

pt
r=( i
nt*
)call
oc(
n,si
zeof
(i
nt)
);
i
f(
pt r==NULL)
{
print
f("
Err
or!memorynotal
l
ocat
ed.
")
;
exit(
0);
}

pri
ntf(
"Enterelement
s:"
);
for(
i=0; i
<n; ++i)
{
scanf(
"%d" ,
ptr+i)
;
sum +=* (pt
r+i);
}

print
f("
Sum =%d"
,sum)
;
free(
ptr)
;
retur
n0;
}

Cr
eal
l
oc(
)
I
fthedy
nami
cal
l
yal
l
ocat
edmemor
yisi
nsuf
fi
cientor
moret
hanrequi
red,y
oucanchangethesizeof
pr
evi
ousl
yall
ocatedmemoryusi
ngthereall
oc(
)funct
ion.

Sy
ntaxofr
eal
l
oc(
)

pt
r=r
eal
l
oc(
ptr
,x)
;
Her
e,pt
risr
eal
l
ocat
edwi
thanewsi
zex.

Exampl
e3:
real
l
oc(
)

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

i
ntmai n()
{
i
nt*ptr,i,
n1, n2;
pri
ntf(
"Entersize:"
);
scanf(
"%d",&n1) ;

pt
r=(
int
*)mal
l
oc(
n1*si
zeof
(i
nt)
);

pri
ntf
("Addressesofprev
iousl
yal
l
ocat
edmemor
y:"
);
for
(i=0;i<n1; ++i)
pri
ntf("
%u\ n"
,pt
r+i)
;

pri
ntf
("\
nEntert
henewsi
ze:
");
scanf
("%d"
,&n2);
//rel
l
ocati
ngthememor y
ptr=real
l
oc(pt
r,n2*si
zeof(
int
));

pri
ntf
("Addressesofnewlyal
l
ocat
edmemor
y:"
);
for
(i=0;i<n2; ++i
)
pri
ntf("
%u\ n"
,pt
r+i);

f
ree(
ptr
);

r
etur
n0;
}
Wheny
our
unt
hepr
ogr
am,
theout
putwi
l
lbe:

Entersi
ze:2
Addressesofpr
evi
ousl
yal
l
ocat
edmemor
y:26855472
26855476

Enterthenewsize:4
Addressesofnewlyall
ocat
edmemor
y:26855472
26855476
26855480
26855484

Exampl
e
Thef ol
lowi
ngexampl
eshowst
heusageofr
eal
l
oc(
)
funct
ion.

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>
i
ntmain(){
char*
str;

/*Init
ialmemor yal
locat
ion*
/
str=( char*)mall
oc(15)
;
strcpy(str
,"gh"
);
pri
nt f
("Str
ing=%s,Address=%u\
n",
str
,st
r);

/*Real locatingmemory* /
str=( char* )real
l
oc(st
r,25);
strcat(str,
".com");
pri
nt f
("Stri
ng=%s,Addr ess=%u\
n",
str
,st
r);

f
ree(
str
);

ret
urn(
0);
}
Letuscompil
eandruntheabov
epr
ogr
am t
hatwi
l
l
producet
hef
oll
owi
ngr
esul
t−
St
ri
ng=gh,
Address=355090448
St
ri
ng=gh.com,Addr
ess=355090448

Pr
ogr
am t
oSwapEl
ement
sUsi
ngCal
lbyRef
erence
#include<st di
o.h>
voidcy cli
cSwap( i
nt*
a,i
nt*
b,i
nt*
c);
i
ntmai n(){
inta, b,c;

pri
ntf
("Ent
era,
bandcrespect
ivel
y:"
);
scanf
("%d%d%d",&a,
&b,&c);
pr
int
f("
Val
uebef
oreswappi
ng:
\n"
);
pr
int
f("
a=%d\nb=%d\ nc=%d\n"
,a,
b,c)
;

cy
cli
cSwap(
&a,
&b,
&c)
;

pr
int
f("
Val
ueaf
terswappi
ng:
\n"
);
pr
int
f("
a=%d\nb=%d\ nc=%d",a,
b,c)
;

r
etur
n0;
}

voi
dcy cl
i
cSwap(int*n1,i
nt*n2,
int*
n3){
i
nttemp;
/
/swappi ngi
ncy cl
icorder
t
emp=* n2;
*
n2=* n1;
*
n1=* n3;
*
n3=t emp;
}
Output
Ent
era,
bandcr espect
ivel
y:1
2
3
Val
uebefor
eswapping:
a=1
b=2
c=3
Val
ueaft
erswapping:
a=3
b=1
c=2
Her
e,t
het
hreenumber
sent
eredbyt
heuserar
est
ored
i
nvari
abl
esa,
bandcrespect
ivel
y.Theaddr
essesof
t
hesenumber
sar
epassedtothecycli
cSwap(
)funct
ion.
cy
cli
cSwap(
&a,
&b,
&c)
;
Inthefuncti
ondefi
nit
ionofcy
cli
cSwap(
),wehav
e
assignedtheseaddr
essestopoi
nter
s.
cy
cli
cSwap(
int*
n1,
int*
n2,
int*
n3){
.
..
}
Whenn1, n2andn3insidecycli
cSwap()arechanged,
the
val
uesofa,bandci nsidemain()ar
ealsochanged.
Note:Thecycl
icSwap()funct
ionisnotret
urni
ng
anyt
hing.

Fi
ndt
heLar
gestEl
ementi
naDy
nami
cal
l
yAl
l
ocat
ed
Memor
y
#i
nclude<st di
o.h>
#i
nclude<st dl
ib.h>
i
ntmai n(){
i
ntnum;
fl
oat*data;
pri
ntf(
"Enterthetot
alnumberofel
ement
s:"
);
scanf(
"%d" ,
&num) ;

//All
ocatingmemor yfornum elements
data=( f
loat*)
call
oc(num,sizeof(
fl
oat)
);
i
f(data==NULL){
pri
ntf(
"Err
or!
!!memor ynotall
ocated.
")
;
exi
t(0)
;
}

/
/St ori
ngnumbersenteredbytheuser
.
f
or( i
nti=0;i<num;++i){
pri
ntf
("Ent
erNumber%d: "
,i+1);
scanf(
"%f"
,dat
a+i);
}

//Findingthelargestnumber
for(i
nti =1;i<num; ++i){
if(*
data<* (data+i))
*data=* (
dat a+i);
}
pri
ntf("
Largestnumber=%. 2f
",*
dat
a);

r
etur
n0;
}
Output
Ent
erthetot
alnumberofel
ement
s:5
Ent
erNumber1: 3.4
Ent
erNumber2: 2.4
Ent
erNumber3: -5
Ent
erNumber4: 24.2
Ent
erNumber5: 6.7
Lar
gestnumber=24. 20
Intheprogram,theuserisaskedt oent erthenumberof
elements,whichisstoredinvari
ablenum.Wewi ll
all
ocatememor yf ornum numberoff loatv al
ues.
Then,theuserisaskedt oenternum number s.These
number sarestoredinthedynamicallyallocated
memor y.
Final
ly
,thelar
gestnumberamongt hesenumber sis
det
ermi
nedandpr
int
edont
hescr
een.

CPr
ogr
ammi
ngSt
ri
ngs

Inthi
stutor
ial
,you'
l
llearnaboutstr
ingsi nC
progr
ammi ng.You'
lll
earntodeclar
et hem, i
nit
ial
i
ze
them andusethem forvar
iousI/
Ooper ati
onswitht
he
helpofexamples.
I
nCprogramming,
astri
ngisasequenceofcharact
ers
t
ermi
natedwi
thanull
charact
er\0.Forexampl
e:
charc[
]="
cst
ri
ng"
;
Whenthecompi l
erencount
ersasequenceofcharact
ers
encl
osedinthedoublequot
ati
onmar ks,
itappendsa
nul
lchar
acter\0attheendbydefaul
t.

Howt
odecl
areast
ri
ng?
Her
e'showy
oucandecl
arest
ri
ngs:

chars[
5];
Her
e,wehav
edecl
aredast
ri
ngof5char
act
ers.

Howt
oini
ti
ali
zest
ri
ngs?
Youcani
nit
ial
i
zest
ri
ngsi
nanumberofway
s.

charc[
]="
abcd"
;

charc[
50]="
abcd"
;

charc[
]={
'a'
,'
b'
,'
c'
,'
d'
,'
\0'
};

charc[
5]={
'a'
,'
b'
,'
c'
,'
d'
,'
\0'
};

Let
'st
akeanot
herexampl
e:

charc[
5]="
abcde"
;
Here,wearetry
ingtoassi
gn6characters(t
helast
charact
eris'
\0'
)toachararr
ayhaving5character
s.
Thisisbadandy oushoul
dneverdothis.

Assi
gni
ngVal
uest
oSt
ri
ngs
Arr
aysandstr
ingsar
esecond-
classci
tizensi
nC;they
donotsuppor
ttheassi
gnmentoperat
oronceiti
s
decl
ared.Forexampl
e,

charc[
100]
;
c="Cprogrammi
ng"
;//Er
ror
!ar
rayt
ypei
snot
assi
gnabl
e.
Not
e:Uset
hest
rcpy
()f
unct
iont
ocopyt
hest
ri
ng
i
nst
ead.

ReadSt
ri
ngf
rom t
heuser
Youcanuset hescanf
()funct
iontoreadastri
ng.
Thescanf(
)functi
onreadsthesequenceofcharact
ers
unt
ili
tencounter
swhitespace(space,newl
i
ne,tab,
etc.
).

Exampl
e1:
scanf
()t
oreadast
ri
ng

#i
nclude<stdio.h>
i
ntmai n()
{
charname[ 20];
pri
ntf(
"Entername:"
);
scanf(
"%s",name);
pri
ntf(
"Yournameis%s."
,name)
;
ret
urn0;
}
Out
put
Ent
ername:
Denni
sRi
tchi
e
Yournamei
sDenni
s.
EventhoughDennisRi
tchi
ewasenteredintheabove
pr
ogram, onl
y"Denni
s"wasst
oredinthenamest r
ing.
I
t'
sbecauset her
ewasaspaceafterDennis.

Howt
oreadal
i
neoft
ext
?
Youcanuset
hefget
s()f
uncti
ontoreadalineofst
ri
ng.
And,
youcanuseput
s()t
odisplayt
hestr
ing.

Exampl
e2:
fget
s()andput
s()

#i
nclude<st dio.h>
i
ntmai n()
{
charname[ 30] ;
pri
ntf (
"Ent
ername: "
);
fgets(name, sizeof
(name),stdi
n);/
/readst
ri
ng
pri
ntf (
"Name: ");
puts(name) ;/ /di
splayst
ring
return0;
}
Out
put
Ent
ername:Tom Hanks
Name:Tom Hanks
Her
e,wehav
eusedf
get
s()f
unct
iont
oreadast
ri
ngf
rom
theuser.
fget
s(name, sizeof(
name) ,st
dli
n);//readstri
ng
Thesizeof(name)r esultsto30.Hence, wecant akea
maximum of30char acter
sasinputwhi chisthesizeof
thenamest r
ing.
Toprintthest r
ing,wehav eusedput s(name);
.
Note:Theget s()functioncanalsobet otakeinputfrom
theuser.Howev er
,itisremovedfrom theCst andard.

It
'sbecausegets()all
owsyoutoi
nputanyl
engthof
charact
ers.Hence,theremi
ghtbeabuff
erover
flow.

Passi
ngSt
ri
ngst
oFunct
ions
St
ringscanbepassedt
oaf uncti
oni
nasimi
larwayas
ar
rays.Lear
nmoreaboutpassingar
ray
stoafunct
ion.

Exampl
e3:
Passi
ngst
ri
ngt
oaFunct
ion

#incl
ude<st
dio.h>
voiddi
spl
ayStr
ing(charst
r[
])
;

i
ntmai n()
{
charst r[
50];
print
f (
"Enterstr
ing:");
fgets(str
,sizeof(str
),st
din)
;
displayStri
ng(st
r) ; //Passingst
ri
ngt
oaf
unct
ion.
r
etur
n0;
}
v
oi ddisplay
Stri
ng(
charstr
[]
)
{
pri
ntf("
Stri
ngOutput
:")
;
puts(st
r);
}

St
ri
ngsandPoi
nter
s
Simil
arli
kearray
s, stri
ngnamesare"decay
ed"to
point
ers.Hence,youcanusepoi nt
erstomanipul
ate
el
ement softhestring.Werecommendedy outo
checkCAr r
aysandPoi nt
ersbef
oreyoucheckthi
s
example.

Exampl
e4:
Str
ingsandPoi
nter
s

#i
ncl
ude<st
dio.
h>

i
ntmai n(
voi
d){
charname[]="
Har
ryPot
ter
";

pr
int
f("
%c"
,*name); //Out
put
:H
pr
int
f("
%c"
,*(name+1)
);//Out
put
:a
pr
int
f("
%c"
,*(name+7)
);//Out
put
:o

char*
namePt
r;
namePt r=name;
pri
ntf
("%c",
*namePtr
); //Out
put
:H
pri
ntf
("%c",
*(namePt
r+1)
);//Out
put
:a
pri
ntf
("%c",
*(namePt
r+7)
);//Out
put
:o
}

Commonl
yUsedSt
ri
ngFunct
ions
 st
rl
en()-cal
culatesthelengthofast r
ing
 st
rcpy(
)-copiesast ri
ngtoanot her
 st
rcmp()-compar estwost r
ings
 st
rcat
()-concatenatestwost r
ings

St
ri
ngMani
pul
ati
onsI
nCPr
ogr
ammi
ngUsi
ngLi
brar
y

Funct
ions

Int
hisarti
cle,you'l
llear
ntomani pul
atest
ringsinC
usi
nglibr
aryf uncti
onssuchasget s(),
put
s, st
rl
en(
)and
more.You'l
llearntogetst r
ingfrom t
heuserand
per
form operationsont hestr
ing.
Youneedt ooftenmanipulatestr
ingsaccor di
ngt othe
needofapr oblem.Most,i
fnotall,ofthet i
mest ri
ng
manipul
ationcanbedonemanual lybut,thismakes
progr
ammi ngcompl exandl ar
ge.
Tosolvethis,
Csuppor t
sal argenumberofst ri
ng
handl
ingfuncti
onsinthest andar
dl i
brary"str
ing.
h".
Fewcommonl yusedstri
nghandlingf uncti
onsar e
di
scussedbel
ow:

Funct
ion Wor
kofFunct
ion

st
rl
en(
) comput
esst
ri
ng'
slengt
h

st
rcpy
() copi
esast
ri
ngt
oanot
her

st
rcat
() concat
enat
es(
joi
ns)t
wost
ri
ngs

st
rcmp(
) compar
est
wost
ri
ngs

st
rl
wr(
) conv
ert
sst
ri
ngt
olower
case

st
rupr
() conv
ert
sst
ri
ngt
oupper
case

Str
ingshandl
i
ngfuncti
onsaredef
ined
under"st
ri
ng.
h"headerf
il
e.
#i
ncl
ude<st
ri
ng.
h>

Note:Youhavetoincl
udet
hecodebel
owt
orunst
ri
ng
handli
ngfunct
ions.
gets(
)andputs()
Functi
onsgets(
)andput s()ar
etwost r
ingfuncti
onsto
takestr
ingi
nputfrom t
heuseranddi splayi
trespect
ivel
y
asment i
onedinthepreviouschapt
er.
#i
ncl
ude<st
dio.
h>

i
ntmai
n()
{
charname[30]
;
pri
ntf
("Ent
ername: "
);
gets(
name); / /
Functi
ontor
eadstr
ingfrom user
.
pri
ntf
("Name:")
;
puts(
name) ;//Functi
ont
odispl
aystr
ing.
ret
urn0;
}
Note:Though,gets(
)andputs()f
uncti
onhandlestr
ings,
bot
ht hesefunct
ionsaredef
inedin"st
dio.
h"headerfi
le.

Cst
ruct

Inthi
stutor
ial
,you'
l
llear
naboutst
ructt
ypesi
nC
Programming.Youwilll
ear
ntodefi
neanduse
str
uctureswit
hthehelpofexampl
es.
I
nCpr ogr
amming,
astruct(orst
ruct
ure)i
sacoll
ect
ion
ofvar
iabl
es(
canbeofdiff
erentt
ypes)underasi
ngl
e
name.

Howt
odef
inest
ruct
ures?
Beforey oucancreatest
ructur
evari
abl
es,
youneedt
o
defi
nei t
sdatatype.Todefineastr
uct,
thestructkeywordisused.
Syntaxofstruct

st
ructst
ruct
ureName
{
dat
aTy
pemember
1;
dat
aTy
pemember
2;
.
..
}
;

Her
eisanexampl
e:

st
ructPer
son
{
charname[
50]
;
i
ntci
tNo;
f
loatsal
ary
;
}
;

Here,
aderiv
edtypest
ructPersoni
sdef
ined.Now,
you
cancreat
evari
abl
esofthi
stype.

Cr
eat
est
ructv
ari
abl
es
Whenast r
uctt
ypeisdecl
ared,nost
orageormemor yi
s
al
locat
ed.Toal
locat
ememor yofagivenstruct
uret
ype
andworkwithi
t,weneedtocreatev
ariabl
es.
Her
e'showwecr
eat
est
ruct
urev
ari
abl
es:

st
ructPer
son
{
charname[
50]
;
i
ntci
tNo;
f
loatsal
ary
;
}
;

i
ntmai
n()
{
st
ructPer
sonper
son1,
per
son2,
p[20]
;
r
etur
n0;
}

Anot
herwayofcr
eat
ingast
ructv
ari
abl
eis:

st
ructPer
son
{
charname[
50]
;
i
ntci
tNo;
f
loatsal
ary
;
}per
son1,
per
son2,
p[20]
;

I
nbot hcases,twovari
abl
esper
son1,
person2,andan
ar
rayv ar
iabl
ephav i
ng20element
softy
pest r
uct
Personarecreated.
Accessmember
sofast
ruct
ure
Ther
ear
etwot
ypesofoper
ator
susedf
oraccessi
ng
member
sofast
ruct
ure.
1.
.-Memberoper ator
2.
->-St
ruct
ur epointeroper
ator(
wil
lbediscussedint
he
nextt
utor
ial)
Suppose,
y ouwantt oaccessthesal
aryofperson2.
Here'
showy oucandoi t.
per
son2.
sal
ary

Exampl
e:Addt
wodi
stances

//Pr ogr
am t oaddtwodi
stances(
feet
-i
nch)
#include<st dio.
h>
structDistance
{
intfeet;
floatinch;
}dist1,dist2,sum;

i
ntmai n()
{
pri
ntf(
"1stdistance\n"
);
pri
ntf(
"Enterfeet:"
);
scanf(
"%d",&dist1.f
eet)
;
pri
ntf
("Ent
eri
nch:");
scanf
("%f"
,&di
st1.i
nch);
pri
ntf
("2nddi
stance\n"
);

pri
ntf
("Ent
erfeet
: "
);
scanf
("%d",&di
st2.
feet
);

pri
ntf
("Ent
eri
nch:"
) ;
scanf
("%f"
,&di
st2.
inch)
;

//addingfeet
sum.feet=dist
1.f
eet+dist
2.f
eet;
//addingi
nches
sum.inch=dist1.
inch+di
st2.
inch;

//changi
ngt ofeeti
finchi
sgreat
ert
han12
whil
e(sum.inch>=12)
{
++sum.f
eet;
sum.i
nch=sum. i
nch-12;
}

pri
ntf(
"Sum ofdi
stances=%d\
'-
%.1f
\""
,sum.
feet
,
sum.inch);
ret
urn0;
}
Out
put
1stdistance
Enterfeet:12
Enterinch:7.
9
2nddistance
Enterfeet:2
Ent
erinch:9.
8
Sum ofdist
ances=15'
-
5.7"

Key
wor
dty
pedef
Weuset het
ypedefkeywor dtocr
eateanal
iasnamef
or
dat
atypes.I
tiscommonl yusedwithstr
uct
uresto
si
mpli
fythesyntaxofdeclari
ngvari
abl
es.
Thi
scode
st
ructDi
stance{
i
ntf
eet
;
f
loati
nch;
}
;

i
ntmai
n(){
st
ructDi
stanced1,
d2;
}

i
sequi
val
entt
o
t
ypedefst
ructDi
stance{
i
ntf
eet
;
f
loati
nch;
}di
stances;
i
ntmai
n(){
di
stancesd1,
d2;
}

Nest
edSt
ruct
ures
Youcancr
eatestruct
ureswit
hinast
ruct
urei
nC
progr
amming.Forexample,

st
ructcompl
ex
{
i
nti
mag;
f
loatr
eal
;
}
;

st
ructnumber
{
st
ructcompl
excomp;
i
nti
nteger
s;
}num1,
num2;

Suppose,
youwantt
oseti
magofnum2v
ari
abl
eto11.
Her
e'showy
oucandoi
t:
num2.
comp.
imag=11;

Whyst
ruct
sinC?
Suppose, youwantt ostoreinfor
mat ionaboutaper son:
his/ hername, citizenshipnumber ,
andsalary.Youcan
creat edi ffer
entv ar i
ablesname, citNoandsal aryt o
stor ethisi nfor
mat ion.
Whati fy ouneedt ostoreinf
or mationofmor et hanone
per son?Now, youneedt ocreatediffer
entvariablesfor
eachi nformat i
onper
per son: name1, citNo1, sal
ary1,name2, ci
tNo2, salary2,
e
tc.
Abet terappr oachwoul dbet ohaveacol l
ecti
onofal l
relatedi nformat ionunderasi ngle
namePer sonstr uctureandusei tforever
yper son.

Mor
eonst
ruct
 Str
uct
uresandpoint
ers
 Passi
ngstr
uctur
estoaf unct
ion

Cst
ruct
sandPoi
nter
s
I
nthi
stutori
al,
you'
lll
earntousepoi
nter
stoaccess
membersofstruct
sinCpr ogr
amming.Youwillalso
l
ear
ntody namical
lyal
locat
ememoryofstructtypes.
Befor
ey oul
ear
nabouthowpointerscanbeusedwi
th
st
ructs,
besuretocheckt
hesetutori
als:
 CPoi
nter
s
 Cst
ruct

CPoi
nter
stost
ruct
Her
e'showy
oucancr
eat
epoi
nter
stost
ruct
s.

str
uctname{
member1;
member2;
.
.
};

i
ntmai n(
)
{
st
ructname*
ptr
,Har
ry;
}
Her
e,pt
risapoi
ntert
ost
ruct
.
Exampl
e:Accessmember
susi
ngPoi
nter
Toaccessmembersofast
ruct
ureusi
ngpoi
nter
s,we
uset
he->oper
ator
.
#include<stdi
o.h>
structper
son
{
intage;
floatweight;
};

i
ntmai n()
{
str
uctperson*personPt
r,per
son1;
personPtr=&person1;

pri
ntf
("Ent
erage:")
;
scanf
("%d",&per
sonPt
r-
>age)
;

pri
ntf
("Ent
erwei
ght:"
);
scanf
("%f"
,&per
sonPtr
->wei
ght
);

pr
int
f("
Displ
ayi
ng:
\n")
;
pr
int
f("
Age:%d\n"
,personPt
r-
>age);
pr
int
f("
weight
:%f"
,personPt
r-
>weight)
;

r
etur
n0;
}
I
nthi
sexample,t
headdressofperson1i
sstoredin
t
hepersonPt
rpoi
nterusingper
sonPtr=&person1;
.
Now,y
oucanaccesst hemembersofperson1using
t
hepersonPt
rpoi
nter.
Byt
heway
,
 per
sonPt
r-
>ageisequi
val
entt
o(*personPt
r).
age
 per
sonPt
r-
>weighti
sequi
val
entt
o( *
personPtr
).
wei
ght

Dy
nami
cmemor
yal
l
ocat
ionofst
ruct
s
Befor
ey ouproceedthissect
ion,wer ecommendy outo
checkCdy namicmemor yall
ocat i
on.
Sometimes,thenumberofst ructvar
iablesyoudecl
ared
maybei nsuff
ici
ent
.Youmayneedt oall
ocatememor y
duri
ngrun-ti
me.Here'showy oucanachi evethi
sinC
progr
ammi ng.
Exampl
e:Dy
nami
cmemor
yal
l
ocat
ionofst
ruct
s

#include<stdio.
h>
#include<stdli
b.h>
structper
son{
intage;
floatweight;
charname[ 30]
;
};

i
ntmain()
{
st
ructperson*
ptr
;
i
nti,n;

pri
ntf
("Ent
erthenumberofper
sons:
");
scanf
("%d",&n)
;
//al
locati
ngmemoryfornnumber
sofstr
uctperson
ptr=(str
uctper
son*
)mall
oc(n*si
zeof
(st
ructper
son))
;

f
or(i=0;i<n;++i
)
{
pr
int
f("
Enterf
ir
stnameandager
espect
ivel
y:"
);

/
/Toaccessmembersof1ststr
uctper
son,
/
/pt
r-
>nameandptr
->ageisused

//Toaccessmember sof2ndst r
uctperson,
//(pt
r+1)
->nameand(ptr+1)
->ageisused
scanf(
"%s%d",(
ptr
+i)
->name,&(ptr+i
)-
>age);
}

pri
ntf
("Displ
ayingInf
ormat
ion:
\n"
);
for
(i=0; i<n;++i)
pri
ntf(
"Name: %s\t
Age:%d\n"
,(pt
r+i
)-
>name,
(pt
r+i
)
-
>age);

ret
urn0;
}
Wheny
our
unt
hepr
ogr
am,
theout
putwi
l
lbe:

Entert
henumberofper sons:2
Enterf
irstnameandager espect
ivel
y:Har
ry24
Enterf
irstnameandager espect
ivel
y:Gar
y32
Displ
ayi
ngI nf
ormati
on:
Name: Harry Age:24
Name: Gary Age:32
I
ntheabov
eex
ampl
e,nnumberofst
ructv
ari
abl
esar
e
cr
eat
edwherenisent
eredbytheuser
.
Toal
locat
ethememoryfornnumberofst
ructper
son,
weused,
pt
r=(
str
uctper
son*
)mal
l
oc(
n*si
zeof
(st
ructper
son)
);
Then,
weusedt
hept
rpoi
ntert
oaccessel
ement
s
ofper
son.

CSt
ruct
ureandFunct
ion

Inthi
stutor
ial,
you'l
llear
ntopassst r
uctvari
abl
esas
argumentstoaf unct
ion.Youwil
llearntoret
urnst
ruct
from af
unctionwiththehelpofexamples.
Si
milartov
ari
abl
esofbuil
t-
intypes,
youcanal
sopass
st
ructur
evari
abl
est
oaf uncti
on.

Passi
ngst
ruct
stof
unct
ions
Werecommendedy
outolearntheset
utori
alsbef
ore
youl
earnhowt
opassst
ructstofunct
ions.
 Cstruct
ures
 Cfuncti
ons
 User-
defi
nedFunct
ion
Here'
showy oucanpassst
ruct
urest
oaf
unct
ion

#i
nclude<stdio.
h>
st
ructstudent{
charname[ 50]
;
i
ntage;
}
;

/
/functi
onprot
otype
v
oiddispl
ay(
str
uctstudents)
;

i
ntmain(){
st
ructstudents1;

pr
int
f("
Ent
ername:
");

//readst
ri
ngi nputfr
om theuserunt
il\
nisent
ered
//\nisdi
scarded
scanf(
"%[
^\n]
%* c",
s1.name);

pri
ntf
("Ent
erage:")
;
scanf
("%d",&s1.
age);

di
spl
ay(
s1)
;//passi
ngst
ructasanar
gument

ret
urn0;
}

v
oiddi
splay(
str
uctst udents){
pr
int
f("
\nDi
splayi
ngi nfor
mation\
n")
;
pr
int
f("
Name: %s",
s. name);
pr
int
f("
\nAge:%d",s.age);
}
Out
put
Ent
ername:Bond
Ent
erage:
13

Di
spl
ayi
ngi
nfor
mat
ion
Name:Bond
Age:
13
Here,astr
uctvar
iables1oftypest
ructst
udenti
s
creat
ed.Thevari
ableispassedtot
hedisplay
()f
unct
ion
usingdi
splay
(s1)
;statement.

Ret
urnst
ructf
rom af
unct
ion
Her
e'showy
oucanr
etur
nst
ruct
uref
rom af
unct
ion:

#include<stdi
o.h>
structstudent
{
charname[ 50];
intage;
};

//funct
ionprotot
ype
str
uctstudentgetI
nfor
mat
ion(
);

i
ntmai n(
)
{
st
ructstudents;

s=get
Inf
ormat
ion(
);

pr
int
f("
\nDi
splayi
nginfor
mation\
n")
;
pr
int
f("
Name: %s",
s.name);
pr
int
f("
\nRol
l:
%d" ,
s.age)
;
r
etur
n0;
}
str
uctstudentgetI
nfor
mat
ion(
)
{
str
uctstudents1;

pri
ntf
("Ent
ername:")
;
scanf("%[
^\n]
%*c"
,s1.
name)
;

pri
ntf
("Ent
erage:")
;
scanf
("%d",&s1.
age);

r
etur
ns1;
}
Here,thegetInformation()functi
oni scal
ledusings=
getI
nformat i
on();stat
ement .Thef uncti
onr et
urnsa
str
uctureoft ypestructstudent.Ther et
urnedst r
uct
ure
i
sdisplay edfrom themai n(
)f unct
ion.
Noticethat,t
her eturntypeofget I
nformation()i
s
al
sost ructstudent.

Passi
ngst
ructbyr
efer
ence
Youcanal sopassstr
uctsbyr eference( i
nasi mil
arway
l
ikeyoupassv ari
abl
esofbuilt-i
nty pebyr ef
erence).We
suggestyoutoreadpassbyr eferencet utor
ialbef
or e
youproceed.
Duri
ngpassbyr efer
ence,t
hememor yaddressesof
str
uctvari
ablesarepassedtot hef uncti
on.
#incl
ude<stdi
o.h>
ty
pedefstr
uctComplex
{
fl
oatr
eal;
fl
oati
mag;
}complex;

v
oidaddNumber
s(compl
exc1,
compl
exc2,
compl
ex
*
resul
t)
;

i
ntmain(
)
{
compl
exc1,
c2,
resul
t;

pri
ntf
("Forfir
stnumber ,
\n"
);
pri
ntf
("Enterrealpart
:")
;
scanf
("%f",&c1.r
eal);
pri
ntf
("Enterimaginarypar
t:"
);
scanf
("%f",&c1.i
mag) ;

pri
ntf
("Forsecondnumber ,\n")
;
pri
ntf
("Enterrealpart
:")
;
scanf
("%f",&c2.r
eal);
pri
ntf
("Enteri
magi narypar
t:")
;
scanf
("%f",&c2.i
mag) ;

addNumber s(c1,c2,&r
esul
t);
pri
ntf
("\
nresult.
real=%.1f
\n",result
.r
eal
);
pri
ntf
("r
esult.
imag=%. 1f"
,result.
imag);

r
etur
n0;
}
v
oidaddNumber
s(compl
exc1,
compl
exc2,
compl
ex
*
result)
{
resul
t->r
eal
=c1.
real
+c2.
real;
resul
t->i
mag=c1.
imag+c2.i
mag;
}
Out
put
Forfir
stnumber ,
Enterreal
par t
:1.1
Enterimaginarypar
t:-
2.4
Forsecondnumber ,
Enterreal
par t
:3.4
Enterimaginarypar
t:-
3.2

r
esul
t.
real
=4.
5
r
esul
t.
imag=-
5.6
Int heabov eprogr am, t
hreestruct
ure
variablesc1, c2andt headdr essofresul
tispassedto
theaddNumber s()f unction.Here,
resul
tispassedby
reference.
Whent her esul
tv ariableinsidetheaddNumber s(
)is
altered, t
heresultv ariabl
ei nsi
dethemain()funct
ionis
alsoal teredaccordi ngly.

CUni
ons

Inthist
utor
ial
,you'
lll
earnaboutuni
onsinC
programming.Morespecifi
cal
ly,
howtocreat
eunions,
accessitsmember sandlear
nthedif
fer
encesbet
ween
unionsandstruct
ures.
Auni
oni
sauser
-def
inedt
ypesi
mil
art
ost
ruct
sin
Cexceptforonekeydif
ference.Str
uctsal
l
ocateenough
spacetostor
ealli
tsmember swher esuni
onsall
ocat
e
thespacetostor
eonlythelargestmember.

Howt
odef
ineauni
on?
Weusetheuni
onkey
wor
dtodef
ineuni
ons.Her
e'san
exampl
e:
unioncar
{
charname[50]
;
i
ntprice;
};
Theabov
ecodedef
inesader
ivedt
ypeuni
oncar
.

Cr
eat
euni
onv
ari
abl
es
Whenauni onisdefi
ned,i
tcreatesauser-
defi
nedt
ype.
Howev er,
nomemor yisal
located.Toal
locat
ememory
foragivenuniont
ypeandwor kwi t
hit
,weneedto
creat
ev ar
iabl
es.
Her
e'showwecr
eat
euni
onv
ari
abl
es.

unioncar
{
charname[50]
;
i
ntprice;
}
;

i
ntmai n(
)
{
uni
oncarcar
1,car
2,*
car
3;
ret
urn0;
}
Anot
herwayofcr
eat
inguni
onv
ari
abl
esi
s:

unioncar
{
charname[50];
i
ntprice;
}car1,car
2,*car
3;

I
nbot hcases,
unionvari
abl
escar
1,car
2,andauni
on
poi
ntercar3ofunioncart
ypear
ecreat
ed.

Accessmember
sofauni
on
Weuset he.operat
ortoaccessmember
sofauni
on.To
accesspoi
ntervari
abl
es,weuseal
sousethe-
>oper
ator
.
Intheaboveexample,
 Toaccesspr
iceforcar
1,car
1.pri
ceisused.
 Toaccesspr
iceusingcar
3,ei
ther(*
car3).
pri
ceorcar
3
-
>pri
cecanbeused.
Di
ff
erencebet
weenuni
onsandst
ruct
ures
Let
'st
akeanexampl
etodemonstr
atet
hedi
ff
erence
bet
weenuni
onsandstr
uct
ures:

#include<st dio.
h>
unionuni onJob
{
/ /
def i
ningauni on
charname[ 32]
;
floatsal ar
y;
intwor kerNo;
}uJob;

str
uctstructJob
{
charname[ 32]
;
floatsalar
y;
intworkerNo;
}sJob;

i
ntmain()
{
pri
ntf
("sizeofunion=%dbytes"
,si
zeof
(uJob)
);
pri
ntf
("\nsizeofstr
uct
ure=%dby t
es"
,si
zeof(
sJob)
);
ret
urn0;
}
Out
put
si
zeofuni
on=32
si
zeofstr
uct
ure=40
Whyt
hisdi
ff
erencei
nthesi
zeofuni
onandst
ruct
ure
variabl
es?
Her e,t
hesi zeofsJobi s40by tesbecause
 thesizeofname[ 32]i
s32by tes
 thesizeofsal aryi s4bytes
 thesizeofwor kerNois4by tes
Howev er
, thesiz eofuJobi s32by t
es.It
'
sbecausethe
sizeofauni onv ari
abl
ewi l
lalwaysbethesiz
eofits
l
ar gestelement .Intheaboveex ample,t
hesi
zeofit
s
l
ar gestelement ,(name[32]
),i
s32by tes.
Wi thauni on, al
l member ssharethesamememor y.

Exampl
e:Accessi
ngUni
onMember
s

#incl
ude<stdio.
h>
unionJob{
floatsal
ary;
intworkerNo;
}j;

i
ntmain(){
j
.sal
ary=12.
3;

/
/whenj .wor
kerNoisassignedaval
ue,
/
/j.sal
arywil
lnolongerhold12.
3
j
.worker
No=100;

pri
ntf
("Sal
ary=%.1f
\n",
j.
sal
ary
);
pri
ntf
("Numberofworkers=%d",
j.
wor
ker
No)
;
ret
urn0;
}
Out
put
Sal
ary=0.
0
Numberofwor
ker
s=100

CFi
leHandl
ing

Inthi
stutori
al,
youwilll
earnaboutfi
lehandl
i
nginC.
Youwi l
ll
earntohandlestandar
dI/OinCusingfpr
int
f()
,
fscanf
(),f
read()
,fwr
it
e(),f
seek(
)etc.wit
hthehel
pof
examples.
Afi
l
ei sacont
aineri
ncomput
erst
oragedev
icesused
f
orstori
ngdat
a.

Whyf
il
esar
eneeded?
 Whenaprogram i
st erminated,
theenti
redat
aislost
.
St
ori
nginafil
ewillpreserveyourdat
aev eni
fthe
pr
ogram t
erminat
es.
 Ify
ouhav et oenteralargenumberofdat a,i
twi
llt
akea
l
otoft i
met oenterthem all.
Howev er,i
fyouhav eafilecontai
ningal
lthedat
a,you
caneasilyaccessthecont entsofthefi
l
eusingafew
commandsi nC.
 Youcaneasi lymov eyourdataf r
om onecomputerto
anotherwithoutanychanges.
Ty
pesofFi
l
es
Whendeali
ngwi
thfi
les,
ther
ear
etwot
ypesoff
il
esy
ou
shoul
dknowabout
:
1.
Textf
il
es
2.
Binar
yfi
l
es
1.Textf
il
es
Textfi
lesaret
henormal .
txtfi
les.Youcaneasil
ycreate
textf
il
esusinganysi
mpl etextedit
orssuchasNot epad.
Wheny ouopenthosefi
les,you'l
lseeal
lthecontents
withi
nthefi
leasplai
ntext.Youcaneasilyedi
tordelete
thecontent
s.
Theyt akeminimum ef
for
ttomaintai
n,ar
eeasil
y
readable,andprov
idet
heleastsecur
it
yandtakesbi
gger
storagespace.
2.Bi
nar
yfi
l
es
Bi
naryfil
esaremostl
ythe.bi
nfi
lesinyourcomputer.
I
nsteadofstori
ngdatai
nplai
ntext,
theystor
eiti
nt he
bi
naryform(0'sand1'
s).
Theycanhol
dahigheramountofdata,arenotreadabl
e
easi
ly
,andpr
ovi
desbettersecur
it
ythantextfi
l
es.

Fi
l
eOper
ati
ons
InC,youcanperfor
mfourmaj
oroper
ati
onsonf
il
es,
eit
hertextorbi
nary
:
1.
Creat
inganewf
il
e
2.
Openi
nganexi
sti
ngf
il
e
3.
Closi
ngaf
il
e
4.
Readi
ngf
rom andwr
it
ingi
nfor
mat
iont
oaf
il
e

Wor
kingwi
thf
il
es
Whenwor ki
ngwi t
hfil
es,y
ouneedt odeclar
eapoint
erof
ty
pef i
le.Thisdecl
arati
onisneededforcommunicat
ion
betweent hefi
leandtheprogram.

FI
LE*
fpt
r;

Openi
ngaf
il
e-f
orcr
eat
ionandedi
t
Openingafil
eisperf
ormedusingthefopen(
)funct
ion
def
inedinthestdi
o.hheaderf
il
e.
Thesy nt
axforopeni
ngaf i
lei
nstandardI
/Ois:

pt
r=f
open(
"fi
l
eopen"
,"
mode"
);
Forexampl
e,

f
open(
"E:
\\cpr
ogr
am\
\newpr
ogr
am.
txt
",
"w"
);

f
open(
"E:
\\cpr
ogr
am\
\ol
dpr
ogr
am.
bin"
,"
rb"
);
 Let'
ssupposet hef i
l
enewpr ogram. t
xtdoesn'texistin
thelocati
onE: \cprogram.Thef ir
stfuncti
oncr eatesa
newf il
enamednewpr ogr am.txtandopensi tforwr i
ting
aspert hemode' w'.
Thewr it
ingmodeal lowsy outocreateandedi t
(overwri
te)thecont entsoft hef i
l
e.
 Nowl et'
ssupposet hesecondbi nary
fi
leoldprogram. bi
nexi stsinthelocationE:\
cpr ogram.
Thesecondf unctionopenst heexisti
ngfil
eforr eading
i
nbi narymode' r
b'.
Ther eadingmodeonl yal l
owsy out oreadthef i
le,you
cannotwr it
eintot hefile.
Openi
ngModesi
nSt
andar
dI/
O

Mod Duri
ngI
nex
ist
enceof
Meani
ngofMode
e fi
l
e

I
fthef
il
edoesnotexi
st,
R Openf
orr
eadi
ng.
f
open(
)ret
urnsNULL.

Openforr
eadi
ngi
n I
fthef
il
edoesnotexi
st,
Rb
bi
narymode. f
open(
)ret
urnsNULL.

Ift
hef i
l
eex i
sts,i
ts
content
sar e
cW Openf
orwr
it
ing. overwri
tten.
Ift
hef i
l
edoesnotex i
st,
i
twillbecr eated.
Openi
ngModesi
nSt
andar
dI/
O

Ift
hef i
l
eex i
sts,i
ts
content
sar e
Openf
orwr
it
ingi
nbi
nar
y
wb overwri
tten.
mode.
Ift
hef i
l
edoesnotex i
st,
i
twillbecr eated.

Openforappend.
I
fthefi
l
edoesnotex
ist
,
A Datai
saddedt ot
heend
i
twil
lbecr
eat
ed.
oft
hefil
e.

Openforappendi
n
bi
narymode. I
fthefi
l
edoesnotex
ist
,
Ab
Datai
saddedt ot
heend i
twil
lbecr
eat
ed.
oft
hefil
e.

Openf
orbothr
eadi
ng I
fthef
il
edoesnotexi
st,
r
+
andwr
it
ing. f
open(
)ret
urnsNULL.

Openf
orbot
hreadi
ng
I
fthef
il
edoesnotexi
st,
r
b+ andwr
iti
ngi
nbinar
y
f
open(
)ret
urnsNULL.
mode.

Ift
hef i
l
eex i
sts,i
ts
content
sar e
Openf
orbothr
eadi
ng
w+ overwri
tten.
andwr
it
ing.
Ift
hef i
l
edoesnotex i
st,
i
twillbecr eated.
Openi
ngModesi
nSt
andar
dI/
O

Ift
hef i
l
eex i
sts,i
ts
Openf
orbot
hreadi
ng content
sar e
wb+ andwr
iti
ngi
nbinar
y overwri
tten.
mode. Ift
hef i
l
edoesnotex i
st,
i
twillbecr eated.

Openforbot
hreadi
ng I
fthefi
l
edoesnotex
ist
,
a+
andappendi
ng. i
twil
lbecr
eat
ed.

Openforbot
hreadi
ng
I
fthefi
l
edoesnotex
ist
,
ab+ andappendi
nginbi
nar
y
i
twil
lbecr
eat
ed.
mode.

Cl
osi
ngaFi
l
e
Thefil
e(bothtextandbi
nar
y)shoul
dbecl
osedaf
ter
readi
ng/wri
ti
ng.
Cl
osi
ngaf
il
eisper
for
medusi
ngt
hef
close(
)funct
ion.
f
close(
fpt
r);
Here,
fpt
risaf
il
epoi
nterassoci
atedwi
tht
hef
il
etobe
cl
osed.
Readi
ngandwr
it
ingt
oat
extf
il
e
Forreadingandwr i
tingtoat extfi
l
e,weuset he
funct
ionsf pri
ntf
()andf scanf().
Theyarej ustthefil
ev ersi
onsofpr i
ntf(
)andscanf(
).The
onlydif
ferenceisthatf pri
nt(
)andf scanf(
)expect
sa
point
ertot hestructureFILE.

Exampl
e1:
Wri
tet
oat
extf
il
e

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

i
ntmain()
{
i
ntnum;
FI
LE* f
ptr;

//useappropri
atel
ocati
onifyouareusi
ngMacOSor
Li
nux
fpt
r=fopen("C:
\\pr
ogram.t
xt"
,"
w")
;

i
f(
fptr==NULL)
{
pri
ntf(
"Er
ror
!"
);
exi
t(1)
;
}

pri
ntf
("Ent
ernum:"
);
scanf
("%d",
&num)
;
f
print
f(f
ptr
,"
%d"
,num)
;
f
close(f
ptr
);

ret
urn0;
}
Thisprogram takesanumberf r
om theuserandstores
i
nt hefilepr
ogram. t
xt.
Afteryoucompi l
eandr unthi
sprogr
am, youcanseea
textfi
leprogram.txtcreatedi
nCdr i
veofy ourcomputer
.
Wheny ouopent hefil
e,youcanseet hei
ntegeryou
entered.

Exampl
e2:
Readf
rom at
extf
il
e

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

i
ntmain()
{
i
ntnum;
FI
LE* f
ptr;

i
f((f
ptr=fopen("
C:\\
program.t
xt"
,"
r"
))==NULL)
{
pr
int
f("
Err
or!openi
ngf i
l
e");

//Progr
am exi
tsi
fthef
il
epoi
nterr
etur
nsNULL.
exi
t(
1);
}

f
scanf
(fpt
r,
"%d"
,&num)
;
pri
ntf
("Val
ueofn=%d"
,num)
;
fcl
ose(fpt
r);

ret
urn0;
}
Thisprogram readstheintegerpresenti n
theprogram.txtfi
leandpr i
ntsitontot hescreen.
I
fy ousuccessf ul
l
ycreat
edt hef i
lefrom Exampl e1,
runni
ngt hi
spr ogram wi
l
l getyout heintegeryouenter
ed.
Otherfuncti
onsl i
kefget
char (
),fputc()etc.canbeused
i
nasi milarway .

Readi
ngandwr
it
ingt
oabi
nar
yfi
l
e
Funct
ionsfr
ead(
)andf
writ
e()ar
eusedforreadi
ngfrom
andwrit
ingtoafi
l
eonthediskr
espect
ivel
yincaseof
bi
naryfi
les.

Wr
it
ingt
oabi
nar
yfi
l
e
Towrit
eintoabinaryfi
le,youneedt
ouse
thef
writ
e()funct
ion.Thefuncti
onstakefourar
gument
s:
1.
addr
essofdat at
obewr i
tt
eninthedisk
2.
sizeofdat
atobewr
it
teni
nthedi
sk
3.
numberofsucht
ypeofdat
a
4.
poi
ntert
othef
il
ewher
eyouwantt
owr
it
e.
fwr
it
e(addr
essDat
a,si
zeDat
a,number
sDat
a,
poi
nter
ToFil
e);

Exampl
e3:
Wri
tet
oabi
nar
yfi
l
eusi
ngf
wri
te(
)

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

str
uctthreeNum
{
intn1,n2,n3;
};

i
ntmain()
{
i
ntn;
st
ructthr
eeNum num;
FI
LE* f
ptr;

i
f((f
ptr=fopen("
C:\\
program.bi
n",
"wb"
))==NULL)
{
pr
int
f("
Err
or!openi
ngf i
l
e");

//Progr
am exi
tsi
fthef
il
epoi
nterr
etur
nsNULL.
exi
t(
1);
}

f
or(n=1;n<5;++n)
{
num.n1=n;
num.n2=5*n;
num.n3=5* n+1;
fwri
te(&num,si
zeof
(st
ructt
hreeNum)
,1,
fpt
r);
}
f
close(f
ptr)
;

ret
urn0;
}
Inthispr ogr am, wecr eat eanewf ileprogram.binint he
Cdr ive.
Wedecl ar east ructuret hreeNum wi t
hthreenumber s-
n1, n2andn3, anddef inei tinthemai nfunct i
onasnum.
Now, insi det heforloop, west orethev al
uei ntothefile
usingf wr it
e().
Thef irstpar amet ertakest headdr essofnum andt he
secondpar amet ertakest hesizeoft he
structuret hreeNum.
Sincewe' reonlyi nserti
ngonei nst
anceofnum, t
het hir
d
paramet eris1.And, thel astpar ameter*fptrpointsto
thef i
l
ewe' rest ori
ngt hedat a.
Finall
y ,wecl oset hef i
le.

Readi
ngf
rom abi
nar
yfi
l
e
Functi
onfread(
)alsot
ake4argument
ssi
mil
art
o
thefwri
te(
)functi
onasabov
e.
fr
ead(addressDat
a,si
zeDat
a,number
sDat
a,
point
erToFil
e);
Exampl
e4:
Readf
rom abi
nar
yfi
l
eusi
ngf
read(
)

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

str
uctthreeNum
{
intn1,n2,n3;
};

i
ntmain()
{
i
ntn;
st
ructthr
eeNum num;
FI
LE* f
ptr;

i
f((f
ptr=fopen("
C:\\
program.bi
n",
"r
b")
)==NULL)
{
pr
int
f("
Err
or!openi
ngf i
l
e");

//Progr
am exi
tsi
fthef
il
epoi
nterr
etur
nsNULL.
exi
t(
1);
}

for(n=1; n<5; ++n)


{
fread(
&num, sizeof
(st
ructthr
eeNum)
,1,f
ptr
);
print
f("
n1:%d\ t
n2:%d\tn3:
%d" ,
num.
n1,
num.n2,
num. n3);
}
fclose(f
ptr)
;

ret
urn0;
}
Inthi
spr ogr
am, youreadthesamef i
lepr
ogr am.bi
nand
l
oopt hroughtherecordsonebyone.
Insimpleterms,youreadonethreeNum record
ofthreeNum sizefr
om thefi
lepoint
edby* fptri
ntothe
str
ucturenum.
You'l
lgetthesamer ecordsyoui
nsertedi
nExampl e3.

Get
ti
ngdat
ausi
ngf
seek(
)
I
fy ouhav
emanyr ecordsi
nsideafi
leandneedto
accessarecor
dataspecifi
cposit
ion,y
ouneedtoloop
thr
oughallt
herecordsbef
oreitt
ogettherecor
d.
Thiswillwastealotofmemor yandoperat
ionti
me.An
easierwaytogettother equi
reddatacanbeachi
eved
usi
ngf seek()
.
Asthenamesuggest s,
fseek()seekst
hecursort
othe
gi
venr ecordint
hef i
l
e.

Sy
ntaxoff
seek(
)

f
seek(
FILE*st
ream,
longi
ntof
fset
,intwhence)
;
Thefir
stparamet erst
r eam i
sthepoi
nt ert ot
hefi
le.The
secondparamet eristhepositi
onofther ecordt
obe
found,andthethirdpar amet
erspeci
fiest hel
ocati
on
wheretheof f
setstart
s.
Di
ff
erentwhencei
nfseek(
)

Whence Meani
ng

SEEK_
SET St
art
stheof
fsetf
rom t
hebegi
nni
ngoft
hef
il
e.

SEEK_
END St
art
stheof
fsetf
rom t
heendoft
hef
il
e.

Star
tstheoff
setf
rom t
hecur
rentl
ocat
ionof
SEEK_
CUR
thecur
sorinthef
il
e.

Exampl
e5:
fseek(
)

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

str
uctthreeNum
{
intn1,n2,n3;
};

i
ntmain()
{
i
ntn;
st
ructthr
eeNum num;
FI
LE* f
ptr;

i
f((f
ptr=fopen("
C:\\
program.bi
n",
"r
b")
)==NULL)
{
pr
int
f("
Err
or!openi
ngf i
l
e");
//Progr
am exi
tsi
fthef
il
epoi
nterr
etur
nsNULL.
exi
t(
1);
}

/
/Mov esthecursort
otheendofthefil
e
f
seek(
fptr
,-si
zeof(
str
uctt
hreeNum),SEEK_
END)
;

for(n=1; n<5; ++n)


{
fread(
&num, sizeof(str
uctthreeNum),1,fptr
);
print
f("
n1:%d\ t
n2: %d\tn3:%d\ n"
,num.n1,num.n2,
num. n3);
fseek(f
ptr
,-2*sizeof(st
ructthreeNum),SEEK_CUR);
}
fclose(f
ptr)
;

ret
urn0;
}
Thisprogram wi
llst
artreadi
ngtherecordsfr
om the
fi
l
epr ogram.bi
ninthereverseor
der(lastt
ofir
st)and
pri
ntsit.
CFi
lesExampl
es

I
nthi
sart
icl
e,y
ou'
llf
indali
stofexampl
est
ohandl
efi
l
e
i
nput
/out
putoper
ati
onsinCprogrammi
ng.
Tounder
standall
progr
amsont hi
spage,youshoul
d
hav
etheknowledgeofthef
oll
owingt
opics.
 CArray
s
 CPoint
ers
 Ar
rayandPoi
nterRel
ati
on
 Fi
l
eI/O

CFi
l
eExampl
es
1.Cpr ogr
am toreadnameandmarksofnnumberof
studentsandstoret
hem i
nafi
le.
#i
nclude<stdio.h>
i
ntmai n(
)
{
charname[ 50];
i
ntmar ks,
i, num;

pri
ntf
("Ent
ernumberofst
udent
s:"
);
scanf
("%d",&num)
;

FILE*f
ptr;
fptr=(
fopen(
"C:
\\st
udent
.t
xt"
,"w"
));
i
f(
f pt
r==NULL)
{
pri
ntf
("Er
ror
!"
);
}

f
or(i=0;i<num; ++i
)
{
pri
ntf
("Forstudent
%d\
nEnt
ername:
",i
+1)
;
scanf(
"%s",name);

pri
ntf
("Ent
ermarks:
");
scanf
("%d",&mar
ks);

fpri
ntf
(fpt
r,
"\
nName:
%s\
nMar
ks=%d\
n",
name,
marks)
;
}

fcl
ose(
fpt
r);
ret
urn0;
}
2.Cpr ogr
am toreadnameandmar ksofnnumberof
studentsfr
om andstoret
hem inafil
e.I
fthefi
le
previ
ouslyexi
ts,
addt hei
nfor
mationtothefi
l
e.
#i
nclude<stdio.h>
i
ntmai n(
)
{
charname[ 50];
i
ntmar ks,
i, num;

pri
ntf
("Ent
ernumberofst
udent
s:"
);
scanf
("%d",&num)
;
FILE*fptr;
fptr=(fopen("
C:\\
student
.t
xt"
,"a"
));
i
f(fpt
r==NULL)
{
pri
ntf("
Error
!"
);

f
or(i=0;i<num; ++i
)
{
pri
ntf
("Forstudent
%d\
nEnt
ername:
",i
+1)
;
scanf(
"%s",name);

pri
ntf
("Ent
ermarks:
");
scanf
("%d",&mar
ks);

fpri
ntf
(fpt
r,
"\
nName:
%s\
nMar
ks=%d\
n",
name,
marks)
;
}

fcl
ose(
fpt
r);
ret
urn0;
}
3.Cprogram towri
teal
lthemember sofanarr
ayof
str
uctur
estoaf i
leusi
ngfwri
te()
.Readthearr
ayfr
om
thefi
leanddispl
ayonthescreen.
#include<stdio.
h>
structstudent
{
charname[ 50]
;
intheight;
};
i
ntmai n(
){
st
ructstudentst
ud1[
5],
stud2[
5];
FI
LE* f
ptr;
i
nti;

f
ptr=f open("f
il
e.txt
",
"wb")
;
f
or(i=0; i<5;++i)
{
ff
lush(stdi
n);
pri
ntf("
Entername: ")
;
gets(st
ud1[i]
.name);

pri
ntf
("Ent
erheight
:")
;
scanf
("%d",&st
ud1[i
].
hei
ght
);
}

f
wr i
te(
stud1,si
zeof
(st
ud1)
,1,
fpt
r);
f
close(f
ptr)
;

f
ptr=f open("
fi
le.
txt
","
rb"
);
f
read(stud2,si
zeof(
stud2)
,1,
fpt
r);
f
or(i=0; i<5;++i
)
{

Cenums

I
nthi
stut
ori
al,
youwi
lll
earnaboutenum (
enumer
ati
on)
i
nCprogr
ammi ngwi
ththehel
pofexamples.
InCprogr
amming,anenumer ati
ontype(al
socall
ed
enum)isadat
atypethatconsistsofi
ntegr
alconst
ant
s.
Todefi
neenums,theenum keywordisused.
enum f
lag{
const
1,const
2,.
..
,const
N};

Bydefault
,const1is0,const
2is1andsoon.Youcan
changedefaultval
uesofenum el
ementsdur
ing
decl
arati
on(ifnecessar
y).
/
/Changi
ngdef
aul
tval
uesofenum const
ant
s
enum sui
t{
cl
ub=0,
di
amonds=10,
hear
ts=20,
spades=3,
}
;

Enumer
atedTy
peDecl
arat
ion
Wheny oudefi
neanenum type,
thebluepr
intfort
he
var
iabl
eiscreat
ed.Her
e'showy oucancreatevar
iabl
es
ofenum ty
pes.

enum bool
ean{
fal
se,
true}
;
enum bool
eancheck;
//decl
ari
nganenum v
ari
abl
e

Here,av
ari
abl
echeckoft
het
ypeenum bool
eani
s
cr
eated.
Youcanal
sodecl
areenum v
ari
abl
esl
i
ket
his.

enum bool
ean{
fal
se,
true}check;

Her
e,theval
ueoffal
sei
sequal
to0andt
hev
alue
oft
rueisequal
to1.

Exampl
e:Enumer
ati
onTy
pe

#i
ncl
ude<st
dio.
h>

enum week{Sunday,Monday
,Tuesday
,Wednesday
,
Thur
sday,Fr
iday,Sat
urday
};

i
ntmai n()
{
//creat
ingt
odayv ar
iabl
eofenum weekt
ype
enum weektoday;
today=Wednesday ;
pri
ntf(
"Day%d",
today+1)
;
retur
n0;
}
Out
put
Day4
Whyenumsar
eused?
Anenum v
ari
abl
ecantakeonl
yonev
alue.Her
eisan
exampl
etodemonst
rat
eit,

#i
ncl
ude<st
dio.
h>

enum suit{
cl
ub=0,
diamonds=10,
heart
s=20,
spades=3
}card;

i
ntmain()
{
car
d=cl ub;
pri
ntf("
Sizeofenum v
ari
abl
e=%dby
tes"
,
si
zeof(
card));
retur
n0;
}
Out
put
Si
zeofenum v
ari
abl
e=4by
tes
Her
e,wear
egett
ing4becausethesi
zeofi
nti
s4bytes.
Thi
smakesenum agoodchoi
cetoworkwi
thfl
ags.

Howt
ouseenumsf
orf
lags?
Letust
akeanexampl
e,
enum desi
gnFl
ags{
ITALICS=1,
BOLD=2,
UNDERLINE=4
}but
ton;
Supposey ouar edesi
gni
ngabut tonforWindows
appl
icati
on.Youcanset
fl
agsITALICS, BOLDandUNDERLI NEtoworkwithtext
.
Thereisar easonwhyalltheint
egralconst
antsarea
powerof2i ntheabovepseudocode.

/
/Inbi
nar
y

I
TALI
CS=00000001
BOLD=00000010
UNDERLI
NE=00000100

Sincetheint
egralconstant
sareapowerof2,y oucan
combinetwoormor efl
agsatoncewi t
houtoverl
appi
ng
usingbit
wiseOR| operator
.Thi
sallowsyoutochoose
twoormor eflagsatonce.Forexample,
#i
ncl
ude<st
dio.
h>

enum desi
gnFl
ags{
BOLD=1,
ITALICS=2,
UNDERLINE=4
};
i
ntmai
n(){
i
ntmyDesi
gn=BOLD|
UNDERLI
NE;

/
/ 00000001
/
/|00000100
/
/____
_____
__
/
/ 00000101

pr
int
f("
%d"
,my
Desi
gn)
;

r
etur
n0;
}
Out
put
5
Whentheout
puti
s5,
youal
way
sknowt
hatbol
dand
under
li
nei
sused.
Al
so,
youcanaddf
lagsaccor
dingt
oyourr
equi
rement
s.

i
f(my
Desi
gn&I
TALI
CS){
/
/codef
ori
tal
i
cs
}

Here,wehav eaddedital
icstoourdesi
gn.Note,onl
y
codef ori
tali
csiswri
tt
eni nsi
dethei
fstatement.
Youcanaccompl i
shalmostanythi
nginCpr ogr
ammi ng
withoutusingenumerati
ons.However,t
heycanbe
prett
yhandyi ncer
tai
nsituati
ons.
CPr
epr
ocessorandMacr
os

Inthi
stutor
ial
,youwi l
lbeintroducedtoc
prepr
ocessors,andyouwi l
llearntouse#incl
ude,
#defi
neandcondi t
ionalcompi l
ati
onwiththehel
pof
examples.

TheCpr eprocessori
samacr opr
eprocessor(al
lowsyou
todefi
nemacr os)thattr
ansformsyourprogram bef
ore
i
tiscompi l
ed.Thesetransf
ormationscanbet he
i
nclusi
onofheaderf il
e,macroexpansionsetc.
Allpr
eprocessi
ngdi
rect
ivesbegi
nwi
tha#sy
mbol
.For
example,
#def
inePI3.
14
Someoft
hecommonusesofCpr
epr
ocessorar
e:
I
ncl
udi
ngHeaderFi
l
es:
#incl
ude
The#i
ncl
udeprepr
ocessori
susedtoi
ncl
udeheader
fi
l
estoCprogr
ams.Forexample,
#i
ncl
ude<st
dio.
h>
Here,stdio.hi saheaderf il
e.The#incl
udepreprocessor
dir
ecti
v ereplacest heabov eli
newit
hthecontents
ofstdio.hheaderf i
le.
That'
st her easonwhyy ouneedtouse#incl
ude
<stdi
o.h>bef or eyoucanusef uncti
ons
l
ikescanf ()andpr intf()
.
Youcanal socr eatey ourownheaderfil
econtai
ning
functi
ondecl arat
ionandi ncludeiti
nyourpr
ogram using
thi
sprepr ocessordi rectiv
e.

#i
ncl
ude"
my_
header
.h"
Vi
sitt
hispaget
olear
nmor
eaboutusi
ngheaderf
il
es.

Macr
osusi
ng#def
ine
Amacr oisafr
agmentofcodethati
sgi
venaname.You
candefineamacroi
nCusingthe#defi
nepr
eprocessor
dir
ect
ive.
Here'
sanexample.

#def
inec299792458/
/speedofl
i
ght
Here,
whenweuseci
nourpr
ogr
am,
iti
srepl
aced
wit
h299792458.

Exampl
e1:
#def
inepr
epr
ocessor

#i
ncl
ude<stdi
o.h>
#def
inePI3.
1415

i
ntmai n()
{
fl
oatradius,area;
pri
ntf(
"Enterther adi
us:
");
scanf(
"%f",&radius);

//Noti
ce,t
heuseofPI
area=PI*
radi
us*
radi
us;

pri
ntf
("Ar
ea=%.
2f"
,ar
ea)
;
ret
urn0;
}

Funct
ionl
i
keMacr
os
Youcanalsodefi
nemacr ost
hatwor
kinasi mil
arway
l
ikeafuncti
oncal
l.Thisi
sknownasfunct
ion-l
i
ke
macros.Forex
ampl e,

#def
ineci
rcl
eAr
ea(
r)(
3.1415*
(r)
*(r
))
Everyti
met heprogram
encountersci
rcl
eArea(ar
gument),
iti
sreplaced
by(3.1415*(
argument)*(
argument
)).
Suppose,wepassed5asanar gumentthen,itexpands
asbelow:

ci
rcl
eAr
ea(
5)expandst
o(3.
1415*
5*5)

Exampl
e2:
Usi
ng#def
inepr
epr
ocessor

#i
ncl
ude<stdi
o.h>
#def
inePI3.
1415
#def
ineci
rcl
eArea(
r)(
PI*
r*r
)

i
ntmai n(){
f
loatradi
us,
area;

pri
ntf
("Enterther adi
us:"
);
scanf
("%f",&radius);
area=circleArea(radi
us)
;
pri
ntf
("Area=%. 2f "
,ar
ea);

r
etur
n0;
}
Vi
sitt
hispagetol
ear
nmor
eaboutmacr
osand#def
ine
pr
eprocessor
.
Condi
ti
onal
Compi
l
ati
on
InCprogrammi ng,youcaninst
ructpr
epr
ocessor
whethertoincl
udeabl ockofcodeornot
.Todoso,
condit
ional
direct
ivescanbeused.
It
'ssimil
artoai fst
atementwi thonemajordi ff
er ence.
Thei fst
atementistesteddur i
ngtheexecutiont i
met o
checkwhet herablockofcodeshoul dbeexecut edor
notwher eas,t
heconditionalsareusedtoinclude( or
skip)ablockofcodei ny ourprogr
am beforeex ecution.

UsesofCondi
ti
onal
 usedif
fer
entcodedependi
ngont
hemachi
ne,
oper
ati
ng
syst
em
 compi
l
esamesour
cef
il
eint
wodi
ff
erentpr
ogr
ams
 toexcludecer
tai
ncodefrom thepr
ogr
am butt
okeepi
t
asreferencef
orfut
urepurpose

Howt
ousecondi
ti
onal
?
Touse
condi
ti
onal
,#i
fdef
,#i
f,#def
ined,
#el
seand#el
sei
fdi
rect
i
vesareused.
#i
fdefDi
rect
ive

#i
fdefMACRO
//condi
ti
onal
codes
#endi
f
Her
e,thecondi
ti
onal
codesar
eincl
udedi
nthepr
ogr
am
onl
yifMACROisdefi
ned.

#i
f,#el
i
fand#el
seDi
rect
ive

#i
fexpression
//condit
ionalcodes
#endi
f
Here,expressioni sanexpr essionofi
ntegerty
pe( canbe
i
ntegers,charact ers,
arit
hmet i
cexpression,
macr osand
soon).
Thecondi ti
onal codesar eincludedi
ntheprogram only
i
ftheexpr essioni sevaluatedtoanon-zerovalue.
Theopt i
onal #elsedi r
ectiv
ecanbeused
wit
h#i fdirecti
ve.
#i
fexpression
condi
tionalcodesifexpr
essi
oni
snon-
zer
o
#el
se
condi
tionali
fexpressi
onis0
#endi
f
Youcanalsoaddnest
edcondi
ti
onal
to
your#i
f.
..
#elseusi
ng#el
i
f
#i
fexpressi
on
/
/conditi
onalcodesifexpr
essi
onisnon-
zer
o
#el
ifexpr
ession1
/
/conditi
onalcodesifexpr
essi
onisnon-
zer
o
#el
ifexpr
ession2
/
/conditi
onalcodesifexpr
essi
onisnon-
zer
o
#el
se
/
/conditi
onali
fallexpr
essi
onsare0
#endif

#def
ined
Thespeci
aloperat
or#defi
nedisusedtot
estwhet
hera
cer
tai
nmacr oisdef
inedornot
.It
'sof
tenused
wit
h#ifdi
recti
ve.
#i
fdef
inedBUFFER_
SIZE&&BUFFER_
SIZE>=2048
/
/codes

Pr
edef
inedMacr
os
Her
ear
esomepr
edef
inedmacr
osi
nCpr
ogr
ammi
ng.

Macr
o Val
ue

_
_DATE_
_ Ast
ri
ngcont
aini
ngt
hecur
rentdat
e
Macr
o Val
ue

_
_FI
LE_
_ Ast
ri
ngcont
aini
ngt
hef
il
ename

_
_LI
NE_
_ Ani
ntegerr
epr
esent
ingt
hecur
rentl
i
nenumber

I
ffoll
owsANSIst andar
dC,
thent
hev
aluei
sa
_
_STDC_
_
nonzeroi
nteger

_
_TI
ME_
_ Ast
ri
ngcont
aini
ngt
hecur
rentdat
e.

Exampl
e3:
Getcur
rentt
imeusi
ng_
_TI
ME_
_
Thefol
l
owingpr
ogr
am out
put
sthecur
rentt
ime
usi
ng__TI
ME__macro.
#i
nclude<st
dio.h>
i
ntmai n(
)
{
pri
ntf("
Cur
rentti
me:
%s"
,_
_TI
ME_
_);
}
Out
put
Cur
rentt
ime:
19:
54:
39

CSt
andar
dLi
brar
yFunct
ions
I
nt hi
stutori
al,
you'l
llearnaboutthestandardl
ibrar
y
funct
ionsinC.Mor especifi
call
y,whatarethey
,
dif
fer
entlibr
aryfunctionsi
nCandhowt ousethem in
yourprogram.
CStandar
dli
brar
yfuncti
onsorsimpl
yCLibr
ary
f
uncti
onsarei
nbuil
tfunct
ionsi
nCprogr
ammi ng.
Thepr ot
otypeanddatadefi
nit
ionsoft
hesefunct
ions
arepresentint
heirr
especti
veheaderf
il
es.Tousethese
funct
ionsweneedt oincl
udetheheaderfi
l
einour
progr
am.Forexampl e,
I
fyouwanttouset
hepr
int
f()funct
ion,
theheader
f
il
e<st
dio.
h>shoul
dbei
ncluded.
#i
nclude<st
dio.
h>
i
ntmai n(
)
{
pri
ntf("
Cat
chmeify
oucan.
")
;
}
I
fyoutr
ytousepr i
ntf(
)withouti
ncl
uding
t
hestdi
o.hheaderfi
le,youwil
lgetanerr
or.

Adv
ant
agesofUsi
ngCl
i
brar
yfunct
ions
1.Theywork
Oneoft hemostimport
antr
easonsy oushoul
duse
l
ibrar
yfuncti
onsissi
mplybecausetheywork.These
funct
ionshavegonethr
oughmul t
ipl
erigor
oustesti
ng
andareeasytouse.
2.Thef uncti
onsar eopti
mi zedforperf
ormance
Since,thefunct
ionsare"standardli
brar
y"functi
ons,
a
dedicatedgroupofdev el
oper sconst
antl
ymaket hem
better.I
ntheprocess,theyareabletocreatethemost
effi
cientcodeoptimizedformax imum perf
ormance.
3.Itsavesconsiderabl
edev el
opmentti
me
Sincethegeneralfunct
ionsli
kepri
nti
ngtoascreen,
calcul
ati
ngthesquar eroot
,andmanymor earealr
eady
writt
en.Youshouldn'tworr
yaboutcreat
ingt
hem once
again.
4.Thef uncti
onsareportabl
e
Withev er
-changi
ngreal-
worl
dneeds,yourappli
cat
ioni
s
expectedtowor kever
ytime,ever
ywhere.And,t
hese
l
ibrar
yf uncti
onshel
py ouinthatt
heydot hesamethi
ng
onever ycomputer.

Exampl
e:Squar
erootusi
ngsqr
t()f
unct
ion
Suppose,
youwantt
ofi
ndt
hesquar
erootofanumber
.
Tocancomputethesquarer ootofanumber,y
oucan
usethesqr
t()l
i
brar
yf unct
ion.Thefunct
ioni
sdefi
nedi
n
themath.
hheaderfi
le.
#i
nclude<st
dio.
h>
#i
nclude<math.
h>
i
ntmai n(
)
{
fl
oatnum,root
;
pri
ntf
("Ent
eranumber
:")
;
scanf
("%f"
,&num)
;

/
/Computesthesquar
erootofnum andst
oresi
nroot
.
r
oot=sqr
t(num);

pri
ntf
("Squar
erootof%.
2f=%.
2f"
,num,
root
);
ret
urn0;
}
Wheny
our
unt
hepr
ogr
am,
theout
putwi
l
lbe:

Enteranumber:12
Squarerootof12.
00=3.
46

Li
brar
yFunct
ionsi
nDi
ff
erentHeaderFi
l
es

CHeaderFi
l
es

<asser
t.
h> Pr
ogr
am asser
ti
onf
unct
ions

<ct
ype.
h> Char
act
ert
ypef
unct
ions

<l
ocal
e.h> Local
i
zat
ionf
unct
ions

<mat
h.h> Mat
hemat
icsf
unct
ions

<set
jmp.
h> Jumpf
unct
ions
CHeaderFi
l
es

<si
gnal
.h> Si
gnal
handl
i
ngf
unct
ions

<st
dar
g.h> Var
iabl
ear
gument
shandl
i
ngf
unct
ions

<st
dio.
h> St
andar
dInput
/Out
putf
unct
ions

<st
dli
b.h> St
andar
dUt
il
it
yfunct
ions

<st
ri
ng.
h> St
ri
nghandl
i
ngf
unct
ions

<t
ime.
h> Dat
eti
mef
unct
ions

Li
nkedLi
st|
Set1(
Int
roduct
ion)
Li
kear r
ays,Li
nkedListisali
neardat
astruct
ure.Unl
i
ke
arr
ays,li
nkedli
stelementsarenotst
oredata
conti
guouslocati
on;theelement
sareli
nkedusing
point
ers.

WhyLinkedList?
Arr
ayscanbeusedt ostoreli
neardataofsi
mil
artypes,
butarr
ayshavethefol
lowingli
mitat
ions.
1)Thesizeofthearr
aysisfi
xed:Sowemustknowt he
upperl
imitonthenumberofelement si
nadvance.Al
so,
generall
y,t
heallocatedmemor yisequaltotheupper
l
imitir
respecti
veoft heusage.
2)Insert
inganewel ementi nanarrayofelementsi
s
expensivebecausether oom hastobecreatedfort
he
newel ementsandt ocreateroom exi
sti
ngelements
havetobeshi f
ted.

Forexampl
e,i
nasy st
em,
ifwemai
ntai
nasor
tedl
i
stof
I
Dsinanarrayi
d[]
.
i
d[]=[
1000,
1010,
1050,
2000,
2040]
.
Andifwewantt oinser
tanewI D1005,thentomaintain
thesortedor der,wehavet omoveallt
heelementsafter
1000( excluding1000).
Delet
ioni salsoexpensivewitharr
aysunti
lunl
esssome
speci
al techniquesareused.Forexample,t
odelete
1010ini d[]
,ev er
ythi
ngafter1010hastobemov ed.
Advantagesov erar r
ay s
1)Dynami csize
2)Easeofi nserti
on/del eti
on
Drawbacks:
1)Random accessi snotal lowed.Wehav etoaccess
el
ement ssequent ial
lyst ar
ti
ngf rom t
hef i
rstnode.Sowe
cannotdobi narysear chwi t
hl i
nkedlist
sef f
icient
lywit
h
i
tsdefaultimplement ation.Readabouti there.
2)Extr
amemor yspacef orapointerisrequiredwith
eachelementoft helist.
3)Notcachef r
iendly.Sincear r
ayelement sar e
conti
guousl ocati
ons, thereislocali
tyofreferencewhich
i
snott hereincaseofl i
nkedl i
sts.
Represent ati
on:
Alinkedlistisrepr esentedbyapoi ntertot hefir
stnode
ofthel i
nkedl i
st.Thef i
rstnodei scalledthehead.I fthe
l
inkedl i
stisempt y,thent hevalueoft heheadi sNULL.
Eachnodei nal i
stconsi stsofatleastt wopar t
s:
1)data
2)Pointer( OrRef erence)t othenex tnode
InC,wecanr epr esentanodeusi ngst r
uctures.Belowis
anexampl eofal inkedl istnodewi thintegerdata.
InJavaorC#, LinkedLi stcanber epresentedasacl ass
andaNodeasasepar ateclass.TheLi nkedListclass
containsar eferenceofNodecl asst ype.
fi
lt
er_none
bri
ght
ness_
4
//Ali
nkedl
istnode
st
ructNode{
i
ntdat
a;
st
ructNode*next
;
}
;
Fir
stSimpl eLi
nkedLi
sti
nCLetuscr
eat
easi
mpl
e
l
inkedlistwit
h3nodes.
fi
lt
er_none
bri
ght
ness_
4
//Asi
mpleCpr
ogr
am t
oint
roduce
/
/al
i
nkedl
i
st
#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>
st
ructNode{
i
ntdat
a;
st
ructNode*next
;
}
;

/
/Pr
ogr
am t
ocr
eat
easi
mpl
eli
nked
/
/li
stwi
th3nodes
i
ntmai
n()
{
st
ructNode*head=NULL;
st
ructNode*second=NULL;
st
ructNode*t
hir
d=NULL;

/
/al
l
ocat
e3nodesi
ntheheap
head=(
str
uctNode*
)mal
l
oc(
siz
eof
(st
ructNode)
);
second=(
str
uctNode*
)mal
l
oc(
siz
eof
(st
ructNode)
);
t
hir
d=(
str
uctNode*
)mal
l
oc(
sizeof
(st
ructNode)
);

/
*Thr
eebl
ockshav
ebeenal
l
ocat
eddy
nami
cal
l
y.
Wehav
epoi
nter
stot
heset
hreebl
ocksashead,
secondandt
hir
d
head second t
hir
d
| | |
| | |
+-
--
+--
--
-+ +-
--
-+-
--
-+ +-
--
-+-
--
-+
|
#|#| |
#|# | |#|#|
+-
--
+--
--
-+ +-
--
-+-
--
-+ +-
--
-+-
--
-+

#r
epr
esent
sanyr
andom v
alue.
Dat
aisr
andom becausewehav
en’
tassi
gned
any
thi
ngy
et*
/

head-
>dat
a=1;
//assi
gndat
ainf
ir
stnode
head-
>next=second;
//Li
nkf
ir
stnodewi
th
/
/thesecondnode

/
*dat
ahasbeenassi
gnedt
othedat
apar
toft
hef
ir
st
bl
ock(
blockpoi
ntedbyt
hehead)
.Andnext
poi
nteroff
ir
stbl
ockpoi
ntst
osecond.
Sot
heybot
har
eli
nked.

head second t
hir
d
| | |
| | |
+-
--
+--
-+ +-
--
-+-
--
-+ +-
--
--
+--
--
+
|
1|o-
--
--
>|#|
# | |# |
#|
+-
--
+--
-+ +-
--
-+-
--
-+ +-
--
--
+--
--
+
*
/

/
/assi
gndat
atosecondnode
second-
>dat
a=2;

/
/Li
nksecondnodewi
tht
het
hir
dnode
second-
>next=t
hir
d;

/*dat
ahasbeenassi
gnedt
othedat
apar
toft
he
second
bl
ock(
blockpoi
ntedbysecond)
.Andnext
poi
nteroft
hesecondbl
ockpoi
ntst
othet
hir
d
bl
ock.Soal
lthr
eebl
ocksar
eli
nked.

head second t
hir
d
| | |
| | |
+-
--
+--
-+ +-
--
+--
-+ +-
--
-+-
--
-+
|
1|o-
--
--
>|2|
o--
--
->|#|#|
+-
--
+--
-+ +-
--
+--
-+ +-
--
-+-
--
-+ *
/

t
hir
d->dat
a=3;
//assi
gndat
atot
hir
dnode
t
hir
d->next=NULL;

/
*dat
ahasbeenassi
gnedt
odat
apar
toft
hir
d
bl
ock(
blockpoi
ntedbyt
hir
d).Andnextpoi
nter
oft
het
hir
dbl
ocki
smadeNULLt
oindi
cat
e
t
hatt
henkedl
i
sti
ster
minat
edher
e.

Wehav
ethel
i
nkedl
i
str
eady
.

head
|
|
+-
--
+--
-+ +-
--
+--
-+ +-
--
-+-
--
--
-+
|
1|o-
--
--
>|2 |
o--
--
->|3|
NULL|
+-
--
+--
-+ +-
--
+--
-+ +-
--
-+-
--
--
-+

Not
ethatonl
yheadi
ssuf
fi
cientt
orepr
esent
t
hewhol
eli
st.Wecant
rav
erset
hecompl
ete
l
i
stbyf
oll
owi
ngnextpoi
nter
s. *
/

r
etur
n0;
}
Alinkedli
stisasequenceofdat
ast
ruct
ures,
whi
char
e
connectedtoget
hervi
alinks.
LinkedListi
sasequenceoflinkswhi
chcontainsitems.
Eachl i
nkcontainsaconnecti
ontoanot
herlink.Linked
l
isti st
hesecondmost -
useddatastr
uct
ureaf terarray
.
Followi
ngar etheimportantter
mst ounderstandt he
conceptofLinkedLi
st.
 Li
nk−Eachl i
nkofal
i
nkedl
i
stcanst
oreadat
a
cal
ledanel
ement
.
 Next−Eachli
nkofal i
nkedl
i
stcont
ainsal
i
nkt
o
thenextl
i
nkcal
ledNext
.
 Li
nkedList−ALinkedLi
stcontai
nst
heconnect
ion
li
nktothefi
rstl
i
nkcall
edFi
rst.
Li
nkedLi
stRepr
esent
ati
on
Li
nkedli
stcanbevi
sual
i
zedasachainofnodes,
wher
e
ev
erynodepoint
stot
henextnode.

As per the above i


l
lust
rat
ion,fol
l
owi
ng ar
e t
he
i
mportantpoi
ntst
obeconsi
dered.
 Li
nkedLi
stcont
ainsal
i
nkel
ementcal
l
edf
ir
st.
 Eachli
nkcarr
iesadat
afi
eld(
s)andal
i
nkf
iel
d
call
ednext
.
 Eachli
nki
sli
nkedwi
thi
tsnextl
i
nkusi
ngi
tsnext
li
nk.
 Lastl
inkcar
ri
esal
i
nkasnul
ltomar
ktheendoft
he
li
st.
Ty
pesofLi
nkedLi
st
Fol
l
owi
ngar
ethev
ari
oust
ypesofl
i
nkedl
i
st.
 Si
mple Li
nked Li
st− I
tem nav
igat
ion i
sfor
war
d
onl
y.
 Doubl
y Linked Li
st− It
ems can be nav
igat
ed
for
wardandbackward.
 Cir
cul
arLinkedList−Lasti
tem cont
ainsl
inkoft
he
fi
rstel
ementasnextandt hefir
stelementhasa
li
nktothelastel
ementasprevi
ous.
Basi
cOper
ati
ons
Fol
l
owi
ngar
ethebasi
coper
ati
onssuppor
tedbyal
i
st.
 I
nsert
ion−Addsanel
ementatt
hebegi
nni
ngoft
he
l
ist
.
 Delet
ion−Del
etesanel
ementatt
hebegi
nni
ngof
theli
st.
 Di
spl
ay−Di
spl
ayst
hecompl
etel
i
st.
 Sear
ch−Sear
chesanel
ementusi
ngt
hegi
venkey
.
 Del
ete−Del
etesanel
ementusi
ngt
hegi
venkey
.
I
nser
ti
onOper
ati
on
Addi
nganewnodei
nli
nkedl
i
sti
samor
ethanonest
ep
acti
vi
ty.Weshalllear
nt hi
swithdiagramsher
e.Fi
rst
,
creat
eanodeusi ngt hesamest r
uctureandfi
ndthe
l
ocationwher
eithastobeinser
ted.

I
magi ne t
hatwe ar einser
ti
ng a nodeB(
NewNode),
betweenA( Lef
tNode)andC( Ri
ght
Node).Then poi
nt
B.nextt
oC−
NewNode.next−>Right
Node;
Itshoul
dlookli
kethi
s−

Now,thenextnodeatt
hel
eftshoul
dpoi
ntt
othenew
node.
Lef
tNode.
next−>NewNode;
Thi
swillputt
henewnodei
nthemi
ddl
eoft
het
wo.The
newli
stshoul
dlookl
i
kethi
s−

Simil
arsteps should be t
aken i
ft he node is being
i
nsertedatthebeginni
ngoftheli
st.Whi l
einsert
ingitat
theend,t
hesecondl astnodeofthelistshouldpointto
thenewnodeandt henewnodewi llpointtoNULL.
Del
eti
onOper
ati
on
Deleti
onisalsoamorethanonest eppr
ocess.Weshall
l
ear n wit
h pict
ori
alr
epresentat
ion.Fi
rst
,locat
et he
target node to be r
emov ed,by using searchi
ng
algori
thms.

Thelef
t(prev
ious)nodeofthetar
getnodenowshoul
d
poi
nttothenextnodeofthetar
getnode−
Lef
tNode.
next−>Tar
get
Node.
next
;

Thi
swi l
lremov ethel
i
nkthatwaspointi
ngt
othetar
get
node.Now,usi ngthefol
lowingcode,wewil
lremove
whatthetargetnodei
spoint
ingat
.
Tar
get
Node.
next−>NULL;

Weneedtousethedel
etednode.Wecankeept
hati
n
memoryot
herwi
sewecansi mplydeall
ocat
ememor
y
andwi
peofft
hetar
getnodecomplet
ely
.

Rev
erseOper
ati
on
Thisoperat
ioni
sat hor
oughone.Weneedt
omakethe
l
astnodet obepointedbytheheadnodeandr
ever
se
thewholeli
nkedl
ist
.

Fi
rst,wetrav
erset
otheendoftheli
st.Itshoul
dbe
point
ingtoNULL.Now,weshal
lmakei tpoi
nttoit
s
previ
ousnode−

Wehav et
omakesur
ethatthel
astnodei
snotthel
ast
node.Sowe'
l
lhav
esomet empnode,whi
chlooksl
ike
theheadnodepoi
nti
ngtot
helastnode.Now,weshal
l
makealll
eftsi
denodespoi
nttotheirpr
evi
ousnodes
onebyone.

Exceptthenode(fi
rstnode)poi
ntedbytheheadnode,
allnodesshould pointtothei
rpredecessor
,making
them thei
rnew successor
.Thefir
stnodewi l
lpoi
ntto
NULL.

We'l
lmaketheheadnodepoi
ntt
othenewf
ir
stnodeby
usi
ngthet
empnode.

DoublyLinkedListisavari
ationofLi nkedl
istinwhich
navi
gationispossiblei
nbothway s,eit
herforwardand
backward easi
lyascompar ed to SingleLinked Li
st.
Fol
lowingar ethei mpor
tantt er
mst ounderstandthe
conceptofdoublyli
nkedli
st.
 Li
nk−Eachl i
nkofal
i
nkedl
i
stcanst
oreadat
a
cal
ledanel
ement
.
 Next−Eachli
nkofal i
nkedl
i
stcont
ainsal
i
nkt
o
thenextl
i
nkcal
ledNext
.
 Pr
ev−Eachli
nkofal
i
nkedl
i
stcont
ainsal
i
nkt
othe
pr
evi
ousl
inkcal
l
edPrev
.
 Li
nkedLi
st−ALinkedListcontai
nst
heconnect
ion
li
nktothefir
stl
i
nkcal
ledFirstandt
othelastl
ink
call
edLast
.
Doubl
yLi
nkedLi
stRepr
esent
ati
on

Aspert
heabovei
ll
ustrat
ion,
fol
l
owi
ngar
ethei
mpor
tant
poi
ntst
obeconsi
dered.
 DoublyLi
nkedLi
stcont
ainsal
i
nkel
ementcal
l
ed
fi
rstandl
ast.
 Eachli
nkcarri
esadataf
iel
d(s)andt
wol
i
nkf
iel
ds
call
ednextandpr
ev.
 Eachli
nki
sli
nkedwi
thi
tsnextl
i
nkusi
ngi
tsnext
li
nk.
 Eachli
nkisl
inkedwi
thi
tspr
evi
ousl
i
nkusi
ngi
ts
prev
iousl
i
nk.
 Thel
astl
inkcar
ri
esal
i
nkasnul
ltomar
ktheendof
thel
i
st.
Basi
cOper
ati
ons
Fol
l
owi
ngar
ethebasi
coper
ati
onssuppor
tedbyal
i
st.
 I
nsert
ion−Addsanel
ementatt
hebegi
nni
ngoft
he
l
ist
.
 Delet
ion−Del
etesanel
ementatt
hebegi
nni
ngof
theli
st.
 I
nser
tLast−Addsanel
ementatt
heendoft
hel
i
st.
 Delet
eLast−Del
etesanel
ementf
rom t
heendof
theli
st.
 I
nsertAf
ter−Addsanel
ementaf
terani
tem oft
he
l
ist
.
 Del
ete−Del
etesanel
ementf
rom t
hel
i
stusi
ngt
he
key
.
 Displ
ayforward−Di
spl
ayst
hecompl
etel
i
sti
na
forwardmanner.
 Di
splaybackwar
d−Di
spl
ayst
hecompl
etel
i
sti
na
backwar
dmanner.
I
nser
ti
onOper
ati
on
Foll
owingcodedemonstr
atest
heinser
ti
onoper
ati
onat
thebeginni
ngofadoubl
yli
nkedl
ist
.
Example
//i
nser
tli
nkatthefirstl
ocat
ion
voi
dinser
tFi
rst
(intkey,i
ntdata){

//creat
ealink
structnode*l
ink=(st
ructnode*
)mal
l
oc(
sizeof
(st
ruct
node));
li
nk->key=key;
li
nk->data=data;

i
f(i
sEmpty()
){
//makeitthel
astl
i
nk
last=li
nk;
}else{
//updatefi
rstpr
evli
nk
head->prev=li
nk;
}

/
/pointi
ttool
df i
rstl
i
nk
l
i
nk->next=head;

//pointf
ir
sttonewf
ir
stl
i
nk
head=l i
nk;
}
Del
etionOperati
on
Foll
owingcodedemonstr
atesthedelet
ionoper
ati
onat
thebeginni
ngofadoubl
yli
nkedli
st.
Example
//
delet
efir
stit
em
str
uctnode*delet
eFi
rst
(){

//
saverefer
encetofi
rstl
i
nk
st
ructnode*tempLi
nk=head;

//
ifonlyonelink
i
f(head->nex
t==NULL){
last=NULL;
}else{
head->next-
>prev=NULL;
}

head=head-
>next
;

//r
etur
nthedel
etedl
i
nk
ret
urntempLi
nk;
}
I
nser
ti
onatt
heEndofanOper
ati
on
Foll
owingcodedemonstratesthei
nsert
ionoper
ati
onat
thelastposi
ti
onofadoublyli
nkedl
ist
.
Example
//i
nser
tli
nkatthelastlocat
ion
voi
dinser
tLast
(intkey,
intdata){

//creat
ealink
structnode*l
ink=(st
ructnode*
)mal
l
oc(
sizeof
(st
ruct
node));
li
nk->key=key;
li
nk->data=data;

i
f(i
sEmpt y
()){
//makeitthelastl
i
nk
last=li
nk;
}else{
//makelinkanewl astl
i
nk
last-
>next=li
nk;

//markoldl
astnodeaspr
evofnewl
i
nk
l
ink-
>prev=last
;
}

//
poi
ntlastt
onewl
astnode
l
ast=l
ink;
}

Circul
arLinkedListisav ari
ati
onofLinkedl
isti
nwhi ch
thef i
rstel
ementpoi nt
stot helastel
ementandthelast
elementpoi nt
stot hefir
stelement.BothSi
nglyLi
nked
ListandDoubl yLinkedListcanbemadei nt
oaci r
cular
l
i
nkedl
i
st.
Si
ngl
yLi
nkedLi
stasCi
rcul
ar
I
nsingl
ylinkedl i
st,t
henextpoi
nteroft
hel
astnode
poi
ntst
othef i
rstnode.

Doubl
yLi
nkedLi
stasCi
rcul
ar
I
ndoubl yl
inkedl i
st,t
henextpoint
erofthelastnode
point
stothef i
rstnodeandt hepr
evi
ouspoint
erofthe
fi
rstnodepoint
st othelastnodemaki
ngthecir
cul
arin
bothdir
ect
ions.

Aspert
heabovei
ll
ustrat
ion,
fol
l
owi
ngar
ethei
mpor
tant
poi
ntst
obeconsi
dered.
 Thelastl
ink'
snextpoint
stot
hefir
stli
nkoftheli
st
inbothcasesofsi
nglyaswel
lasdoubl
yli
nkedli
st.
 Thefir
stl
ink'
sprev
iouspoint
stot
hel
astoft
hel
i
st
incaseofdoubl
yli
nkedli
st.
Basi
cOper
ati
ons
Foll
owingaret
hei
mpor
tantoper
ati
onssuppor
tedbya
ci
rcularl
i
st.
 i
nser
t−I
nser
tsanel
ementatt
hest
artoft
hel
i
st.
 del
ete−Del
etesanel
ementf
rom t
hest
artoft
he
li
st.
 di
spl
ay−Di
spl
ayst
hel
i
st.
I
nser
ti
onOper
ati
on
Fol
l
owingcodedemonstrat
est
heinsert
ionoperat
ioni
n
aci
rcul
arl
i
nkedli
stbasedonsi
ngl
elinkedli
st.
Exampl e
i
nser t
Fir
st(data):
Begin
createanewnode
node- >dat a:=data
ifthelisti
sempt y
, t
hen
head: =node
nextofnode=head
else
temp: =head
whilenextoft empi snothead,
do
temp: =nextoft emp
done
nextofnode: =head
nextoft emp: =node
head: =node
endi f
End
Deleti
onOper at
ion
Fol
l
owingcodedemonstrat
est
hedelet
ionoperat
ioni
n
aci
rcul
arl
i
nkedl
istbasedonsi
ngl
eli
nkedli
st.
deleteFir
st(
):
Begin
ifheadi snull
,then
itisUnderfl
owandretur
n
elsei fnextofhead=head,t
hen
head: =null
deal
locat
ehead
else
ptr:
=head
whil
enextofptrisnothead,
do
ptr:=nextofptr
nextofptr=nextofhead
deal
locat
ehead
head:=nextofptr
endi f
End
Displ
ayListOperati
on
Fol
l
owingcodedemonst
rat
est
hedi
spl
ayl
i
stoper
ati
on
i
nacir
cularl
i
nkedl
ist
.
di
splay()
:
Begin
ifheadi snul
l,
then
Nothingtopri
ntandr et
urn
else
pt
r:=head
whil
enextofpt ri
snothead,do
displaydat
aofpt r
ptr:=nextofptr
di
splaydataofptr
endif
End

Li
nkedLi
stTr
aver
sal

I
nt heprev
iouspr ogram,
wehav ecreatedasi mple
l
inkedli
stwiththreenodes.Letustr
av ersethecreated
l
istandpri
ntt hedataofeachnode.Fort raversal
,l
etus
writ
eagener al-
purposef
unctionpr
intList()t
hatprint
s
anygi
venl
i
st.

f
il
ter
_none
edi
t
pl
ay_arrow
bri
ghtness_4

/
/Asi
mpl
eCpr
ogr
am f
ort
rav
ersal
ofal
i
nkedl
i
st
#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

st
ructNode{
i
ntdat
a;
st
ructNode*next
;
}
;

//Thisf
uncti
onpr
int
scont
ent
sofl
i
nkedl
i
st
star
ti
ngfrom
/
/thegi
vennode
v
oidpr
int
List
(st
ructNode*n)
{
whi
l
e(n!
=NULL){
pr
int
f("%d"
,n-
>dat
a);
n=n-
>next
;
}
}

i
ntmai
n()
{
st
ructNode*head=NULL;
st
ructNode*second=NULL;
st
ructNode*t
hir
d=NULL;

/
/al
l
ocat
e3nodesi
ntheheap
head=(st
ructNode*
)mal
l
oc(
siz
eof
(st
ruct
Node));
second=(
str
uctNode*
)mal
l
oc(
siz
eof
(st
ruct
Node));
t
hir
d=(st
ructNode*
)mal
l
oc(
sizeof
(st
ruct
Node))
;

head-
>dat
a=1;
//assi
gndat
ainf
ir
stnode
head-
>next=second;
//Li
nkf
ir
stnodewi
th
second

second-
>dat
a=2;
//assi
gndat
atosecondnode
second-
>next=t
hir
d;

t
hir
d->dat
a=3;
//assi
gndat
atot
hir
dnode
t
hir
d->next=NULL;

pr
int
List
(head)
;

r
etur
n0;
}

Out
put
:
123

Li
nkedLi
stOper
ati
ons:Tr
aver
se,
Inser
tandDel
ete

Nowt hatyouhav egotanunderst


andingofthebasi
c
conceptsbehindli
nkedli
standtheirty
pes,i
t'
sti
met o
di
veintothecommonoper at
ionsthatcanbeperfor
med.
Twoimpor tantpoint
storemember :
 headpoi ntst
othefi
rstnodeoft hel
inkedli
st
 nextpointeroft
helastnodeisNULL, soift
henext
currentnodeisNULL,wehaver eachedtheendoft he
l
inkedlist.
Inalloftheexampl
es,wewi l
lassumet hattheli
nkedli
st
hast hr
eenodes1--->2--
->3wit
hnodest ructur
eas
below:
str
uctnode
{
i
ntdata;
str
uctnode*
next
;
};
Howt
oTr
aver
seaLi
nkedLi
st
Displ
ayi
ngthecontent
sofal
inkedli
stisver
ysi
mple.We
keepmov i
ngthetempnodet
ot henextoneanddi
splay
i
tscontent
s.
WhentempisNULL,weknowthatwehav
ereachedthe
endofthel
i
nkedl
istsowegetoutoft
hewhi
leloop.
st
ructnode*temp=head;
pr
intf
("\
n\nLi
stelementsar
e-\n"
);
whil
e(t
emp! =NULL)
{
pri
ntf(
"%d---
>",
temp-
>dat
a);
temp=t emp->next
;
}
Theout
putoft
hispr
ogr
am wi
l
lbe:

Li
stelement
sare-
1--
->2--
->3-
--
>

Howt
oAddEl
ement
stoaLi
nkedLi
st
Youcanaddel
ement
stoei
thert
hebegi
nni
ng,
middl
eor
endoft
heli
nkedl
i
st.
Addt
othebegi
nni
ng
 Al
l
ocat
ememor
yfornewnode
 St
oredat
a
 Changenextofnewnodet
opoi
ntt
ohead
 Changeheadt
opoi
ntt
orecent
lycr
eat
ednode

str
uctnode*newNode;
newNode=mal l
oc(
sizeof
(st
ructnode)
);
newNode->dat
a=4;
newNode->next=head;
head=newNode;
Addt
otheEnd
 Al
l
ocat
ememor
yfornewnode
 St
oredat
a
 Tr
aver
set
olastnode
 Changenextofl
astnodet
orecent
lycr
eat
ednode

str
uctnode*newNode;
newNode=mal l
oc(
sizeof
(st
ructnode)
);
newNode->dat
a=4;
newNode->next=NULL;

st
ructnode*temp=head;
whil
e(t
emp->next!=NULL)
{
t
emp=t emp- >next
;
}

t
emp-
>next=newNode;
Addt
otheMi
ddl
e
 Al
l
ocat
ememor
yandst
oredat
afornewnode
 Trav
erset
onodej
ustbef
oret
her
equi
redposi
ti
onof
newnode
 Changenextpoi
nter
stoi
ncl
udenewnodei
nbet
ween

str
uctnode*newNode;
newNode=mal loc(
sizeof
(st
ructnode)
);
newNode->dat
a=4;

st
ructnode*
temp=head;

for
(i
nti=2; i
<positi
on;i
++){
i
f(t
emp- >next!
=NULL){
t
emp=t emp->next
;
}
}
newNode- >nex
t=t emp->next
;
temp->next=newNode;

Howt
oDel
etef
rom aLi
nkedLi
st
Youcandel
eteei
therf
rom begi
nni
ng,
endorf
rom a
par
ti
cul
arposi
ti
on.
Del
etef
rom begi
nni
ng
 Poi
ntheadt
othesecondnode

head=head-
>next
;
Del
etef
rom end
 Tr
aver
set
osecondl
astel
ement
 Changei
tsnextpoi
ntert
onul
l

structnode*t emp=head;
whi l
e(temp->next->next
!=NULL)
{
temp=t emp- >next;
}
temp- >next=NULL;
Del
etef
rom mi
ddl
e
 Tr
aver
set
oel
ementbef
oret
heel
ementt
obedel
eted
 Changenextpoi
nter
stoexcl
udet
henodef
rom t
he
chai
n

f
or(i
nti=2;
i<posit
ion;i
++){
i
f(
temp->nex
t!=NULL){
t
emp=t emp->next;
}
}

t
emp-
>next=t
emp-
>next
->next
;

Compl
etePr
ogr
am f
orLi
nkedLi
stOper
ati
ons
/
/Li
nkedl
i
stoper
ati
onsi
nC

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>
//Createanode
str
uctNode{
i
ntitem;
str
uctNode*next
;
};

voidi
nsert
AtBeginni
ng(str
uctNode**r
ef,
intdat
a){
//All
ocat
ememor ytoanode
str
uctNode*new_ node=( st
ruct
Node*)mall
oc(si
zeof(st
ructNode))
;

//i
nsertt
heitem
new_node-
>it
em =data;
new_node-
>next=(
*ref)
;

/
/Mov eheadtonewnode
(
*ref
)=new_node;
}

/
/I nsertanodeafteranode
v
oi dinsertAf
ter
(st
ructNode*node,i
ntdata){
i
f( node==NULL){
print
f (
"t
hegiv
enpr ev
iousnodecannotbeNULL"
);
return;
}

str
uctNode*new_ node=( str
uct
Node*)mall
oc(
sizeof(st
ructNode))
;
new_node-
>it
em =dat a;
new_node-
>next=node- >next;
node-
>next=new_ node;
}
voi
dinser
tAtEnd(st
ructNode**ref,i
ntdat
a){
st
ructNode*new_ node=( st
ruct
Node*)mal
loc(si
zeof(str
uctNode))
;
st
ructNode*last=*r ef
;

new_
node-
>it
em =dat
a;
new_
node-
>next=NULL;

i
f(*r
ef==NULL){
*
ref=new_node;
r
etur
n;
}

whil
e(l
ast-
>next!=NULL)
l
ast=last
->next
;

l
ast-
>nex
t=new_
node;
r
etur
n;
}

v
oiddelet
eNode(st
ructNode*
*ref
,intkey
){
st
ructNode*t
emp=* r
ef,
*pr
ev;

i
f( temp! =NULL&&t emp->i
tem ==key){
*ref=t emp->next
;
free(temp) ;
return;
}
//Fi ndt hekeytobedeleted
whi le(temp! =NULL&&t emp->i
tem !
=key){
prev=t emp;
temp=t emp->next
;
}

/
/Ifthekeyi
snotpresent
i
f(t
emp==NULL)r etur
n;

//Remov et
henode
prev
->next=temp-
>next
;

f
ree(
temp)
;
}

/
/Pr i
nttheli
nkedl i
st
v
oi dpri
ntLi
st(
structNode*node){
whil
e(node!=NULL){
pri
ntf
("%d",node->i
tem);
node=node- >next
;
}
}

/
/Dr i
verpr
ogram
i
ntmain(){
st
ructNode*head=NULL;

i
nser
tAt
End(&head,1);
i
nser
tAt
Beginni
ng(&head,2)
;
i
nser
tAt
Beginni
ng(&head,3)
;
i
nser
tAt
End(&head,4);
i
nser
tAf
ter
(head->next
,5)
;

pr
int
f("
Linkedl
ist
:")
;
pr
int
List
(head)
;

pr
int
f("
\nAf
terdel
eti
nganel
ement
:")
;
del
eteNode(&head,
3);
pri
ntLi
st(
head);
}

Ty
pesofLi
nkedLi
st-Si
ngl
yli
nked,
doubl
yli
nkedand

ci
rcul
ar

I
nthistut
ori
al,
youwi l
llear
ndif
ferentt
ypesofli
nked
l
ist
.Also,
youwi l
lfi
ndimplementati
onofli
nkedli
sti
nC.
Ther
ear
ethr
eecommont
ypesofLi
nkedLi
st.
1.
SinglyLinkedList
2.
Doubl yLinkedList
3.
Circul
arLi nkedList

Si
ngl
yLi
nkedLi
st
I
tisthemostcommon.Eachnodehasdat
aanda
poi
ntert
othenextnode.

Si
ngl
yli
nkedl
i
st
Nodei
srepr
esent
edas:

st
ructnode{
intdata;
structnode*
next
;
}
At
hree-
membersi
ngl
yli
nkedl
i
stcanbecr
eat
edas:

/*Ini
ti
ali
zenodes*/
str
uctnode*head;
str
uctnode*one=NULL;
str
uctnode*two=NULL;
str
uctnode*thr
ee=NULL;

/*All
ocat
ememor y*/
one=mal l
oc(si
zeof(
str
uctnode)
);
two=mal l
oc(si
zeof(
str
uctnode)
);
thr
ee=mal l
oc(si
zeof(
str
uctnode)
);

/*Assigndat
aval
ues*
/
one->dat
a=1;
two->dat
a=2;
thr
ee->dat
a=3;

/*Connectnodes*/
one->next=two;
two->next=thr
ee;
thr
ee->next=NULL;

/*Sav
eaddressoff
ir
stnodei
nhead*
/
head=one;

Doubl
yLi
nkedLi
st
Weaddapoi
ntert
othepr
evi
ousnodei
nadoubl
y-
li
nked
l
ist
.Thus,wecangoi
nei
therdi
rect
ion:
for
war
dor
backwar
d.

Doubl
yli
nkedl
i
st
Anodei
srepr
esent
edas

st
ructnode{
i
ntdata;
st
ructnode*
next
;
st
ructnode*
prev
;
}
At
hree-
memberdoubl
yli
nkedl
i
stcanbecr
eat
edas

/*Ini
ti
ali
zenodes*/
str
uctnode*head;
str
uctnode*one=NULL;
str
uctnode*two=NULL;
str
uctnode*thr
ee=NULL;

/*All
ocat
ememor y*/
one=mal l
oc(si
zeof(
str
uctnode)
);
two=mal l
oc(si
zeof(
str
uctnode)
);
thr
ee=mal l
oc(si
zeof(
str
uctnode)
);

/*Assigndat
aval
ues*
/
one->dat
a=1;
two->dat
a=2;
thr
ee->dat
a=3;
/*Connectnodes*
/
one-
>next=two;
one-
>prev=NULL;

t
wo-
>next=thr
ee;
t
wo-
>prev=one;

t
hree-
>next=NULL;
t
hree-
>prev=t
wo;

/*Sav
eaddressoff
ir
stnodei
nhead*
/
head=one;

Ci
rcul
arLi
nkedLi
st
Aci
rcularli
nkedl
i
stisavari
ati
onofalinkedl
isti
nwhi
ch
t
helastelementi
sli
nkedtothefi
rstel
ement.Thi
sfor
ms
aci
rcul
arloop.

Ci
rcul
arl
i
nkedl
i
st
Acircul
arl
i
nkedl
i
stcanbeei
thersi
ngl
yli
nkedordoubl
y
l
inked.
 f
orsi
nglyli
nkedl
i
st,
nextpoi
nterofl
asti
tem poi
ntst
o
t
hefi
rsti
tem
 Int
hedoublyl
inkedli
st,
prevpoi
nterofthefi
rsti
tem
poi
ntstothel
astit
em aswell
.
Athree-
membercircul
arsi
nglyl
i
nkedlistcanbecreat
ed
as:

/*Ini
ti
ali
zenodes*/
str
uctnode*head;
str
uctnode*one=NULL;
str
uctnode*two=NULL;
str
uctnode*thr
ee=NULL;

/*All
ocat
ememor y*/
one=mal l
oc(si
zeof(
str
uctnode)
);
two=mal l
oc(si
zeof(
str
uctnode)
);
thr
ee=mal l
oc(si
zeof(
str
uctnode)
);

/*Assigndat
aval
ues*
/
one->dat
a=1;
two->dat
a=2;
thr
ee->dat
a=3;

/*Connectnodes*/
one->next=two;
two->next=thr
ee;
thr
ee->next=one;

/*Sav
eaddressoff
ir
stnodei
nhead*
/
head=one;
A stackisanAbst r
actDataType( ADT),commonly
used in mostpr ogr
amming l
anguages.Itis named
stackasitbehavesli
keareal
-worl
dstack,forexampl
e
–adeckofcar dsorapil
eofplat
es,et
c.

Ar eal
-wor
ldstackallowsoper ati
onsatoneendonl y
.
Forexample,wecanpl aceorr emov eacardorpl ate
fr
om t hetopoft hestackonl y.Likewi
se,StackADT
al
lowsalldat
aoper at
ionsatoneendonl y.Atanygiv en
ti
me, wecanonlyaccesst het
opelementofast ack.
Thisf eatur
emakesi tLIFOdat astructur
e.LIFOstands
forLast -
in-
fi
rst
-out
.Her e,theelementwhi chispl aced
(i
nserted oradded)l ast,is accessed fir
st.In stack
ter
mi nology, insert
ion oper
ation i
s
call
edPUSHoper ati
on and r emov al operat
ion i s
call
edPOPoper ati
on.
St
ackRepr
esent
ati
on
The fol
lowi
ng di
agr
am depi
cts a st
ack and i
ts
oper
ati
ons−
A st ack can be impl
emented by means ofAr ray
,
Struct ur
e,Point
er,
andLinkedLi
st.St
ackcaneitherbea
fi
xed si ze one oritmayhav e a sense ofdy namic
resizing.Here,wear egoi
ngtoimplementstackusi ng
array s, which makes i t a f i
xed si ze st ack
i
mpl ementati
on.
Basi
cOper
ati
ons
Stack oper
ati
ons may i nvolv
ei ni
tial
i
zing the stack,
using i
tand then de-
ini
tial
izi
ng it
.Apar tfr
om t hese
basic st
uff
s,a stack is used f
ort he fol
l
owing t wo
pri
maryoperat
ions−
 push(
)−Pushi
ng(
stor
ing)anel
ementont
hest
ack.
 pop()−Remov
ing(
accessi
ng)anel
ementf
rom t
he
stack.
Whendat
aisPUSHedont
ost
ack.
Touseast
ackeff
ici
entl
y,weneedt
ocheckthestat
us
ofst
ackaswel
l.Forthesamepurpose,t
hefol
l
owing
f
unct
ional
i
tyi
saddedt
ost
acks−
 peek()− gett
hetop dat
ael
ementoft
hest
ack,
withoutr
emovingi
t.
 i
sFul
l(
)−checki
fst
acki
sful
l
.
 i
sEmpt
y()−checki
fst
acki
sempt
y.
Atallti
mes,wemai ntai
napoi ntertothelastPUSHED
dataonthest ack.Asthi
spointeralwaysrepresent
sthe
top oft he stack,hence namedt op.Thet oppoint
er
provi
des top v alue of t
he st ack wit
hout actuall
y
removingit
.
Fir
stweshoul
dlear
naboutpr
ocedur
est
osuppor
tst
ack
funct
ions−
peek(
)
Al
gor
it
hm ofpeek(
)funct
ion−
beginprocedurepeek
r
etur
nst ack[t
op]
endprocedur e
Implement at
ionofpeek(
)funct
ioni
nC pr
ogr
ammi
ng
language−
Exampl
e
i
ntpeek(
){
ret
urnst
ack[
top]
;
}
i
sful
l(
)
Al
gor
it
hm ofi
sful
l
()f
unct
ion−
begi
npr
ocedur
eisf
ull

i
ftopequal
stoMAXSI
ZE
ret
urnt
rue
el
se
ret
urnf
alse
endi
f

endpr
ocedur
e
I
mplement
ati
onofi
sful
l
()f
unct
ioni
nC pr
ogr
ammi
ng
l
anguage−
Exampl
e
bool i
sfull
(){
if
(top==MAXSI ZE)
returntrue;
else
returnfalse;
}
i
sempt y(
)
Al
gor
it
hm ofi
sempt
y()f
unct
ion−
begi
npr
ocedur
eisempt
y

i
ftoplessthan1
ret
urntrue
el
se
ret
urnfalse
endi
f

endpr
ocedur
e
I
mplementat
ionofisempty (
)funct
ioninCpr ogr
ammi ng
l
anguageissli
ght
lydi f
fer
ent.Wei ni
ti
ali
zet opat-1,as
t
heindexinarr
ayst art
sfrom 0.Sowechecki fthetop
i
sbelow zer
oor-1t odeterminei
fthest ackisempt y
.
Her
e'st
hecode−
Exampl
e
bool i
sempty(){
if
(top==- 1)
retur
ntrue;
else
retur
nfalse;
}
PushOper ation
Theprocessofputt
inganew datael
ementont
ostack
i
sknownasaPushOper at
ion.Pushoper
ati
oni
nvol
ves
aser
iesofsteps−
 St
ep1−Checksi
fthest
acki
sful
l
.
 Step2−I
fthest
acki
sful
l
,pr
oducesaner
rorand
exit
.
 St
ep3−I ft
hestackisnotf
ull
,incr
ement
stopt
o
poi
ntnextempt
yspace.
 St
ep4−Addsdataelementt
othest
ackl
ocat
ion,
wher
etopi
spoi
nti
ng.
 St
ep5−Ret
urnssuccess.
Ifthel
i
nkedlisti
susedtoimplementt
hestack,t
heni
n
step3,weneedtoal
locat
espacedynamical
l
y.
Al
gor
it
hm f
orPUSHOper
ati
on
Asimpleal
gor
it
hm f
orPushoper
ati
oncanbeder
ived
asf
oll
ows−
begi
npr
ocedur
epush:
stack,
dat
a

i
fstacki
sful
l
ret
urnnul
l
endi
f

top← top+1
stack[
top]← dat
a

endpr
ocedur
e
I
mpl
ement
ati
onoft
hisal
gor
it
hm i
nC,i
sver
yeasy
.See
t
hef
oll
owi
ngcode−
Exampl
e
voi
dpush( intdat
a){
if
(!isFul
l()){
top=t op+1;
stack[top]=data;
}else{
print
f("Couldnoti
nser
tdat
a,St
acki
sful
l
.\n"
);
}
}
PopOper ation
Accessi
ngthecont
entwhi
l
eremovingitf
rom t
hest
ack,
i
s known as a Pop Oper at
ion. In an array
i
mplementati
onofpop(
)oper
ati
on,thedatael
ementis
notactual
l
yr emoved,insteadtopisdecrementedt oa
l
owerpositioninthest acktopointt othenextvalue.
But in linked-
li
st impl ementat
ion, pop(
) act ual
ly
removesdataelementanddeal l
ocatesmemor yspace.
APopoper
ati
onmayi
nvol
vet
hef
oll
owi
ngst
eps−
 St
ep1−Checksi
fthest
acki
sempt
y.
 St
ep2−I ft
hest
acki
sempt
y,pr
oducesaner
ror
andexi
t.
 St
ep3−Ifthestacki
snotempty,accessest
he
dat
ael
ementatwhi
cht
opi
spoi
nti
ng.
 St
ep4−Decr
easest
hev
alueoft
opby1.
 St
ep5−Ret
urnssuccess.

Al
gor
it
hm f
orPopOper
ati
on
Asimpl
eal
gor
it
hm f
orPopoper
ati
oncanbeder
ivedas
f
oll
ows−
begi
npr
ocedur
epop:
stack

i
fstacki
sempt
y
ret
urnnul
l
endi
f
data← stack[
top]
top← top-1
ret
urndata

endpr
ocedur
e
I
mpl
ement
ati
onoft
hisal
gor
it
hm i
nC,
isasf
oll
ows−
Exampl
e
i
ntpop(
intdat
a){

i
f(!
isempt y(
)){
dat a=stack[t
op];
top=t op-1;
returndata;
}else{
pr i
ntf
("Couldnotr
etr
iev
edat
a,St
acki
sempt
y.\
n")
;
}
}

You might also like