Professional Documents
Culture Documents
C Programming Course Ware
C Programming Course Ware
C Programming Course Ware
seCode: CSC203
Cour
seTi
tl
e: COMPUTERPROGRAMMI
NGI
Cour
seUni
t: 3Uni
ts
Cour
seDurat
ion: 2HOURS
COURSEDETAI
LS
Cour
seWr
it
er/
Dev
eloper
: Prof.O.Folor
unso
Depar t
mentofComput erScience
Federal Uni versi
ty of
Agricul
ture Abeokuta,
Ogun
State,Niger
ia
Emai
l
: f
olor
unsoo@f
unaab.
edu.
ng
COURSECONTENT
WEEK10–11&12
Str
ings.Def
ini
ngstruct
ures,accessi
ngstructuremembers.
Whatarepointer
s,howtousepoi nter
s,pointerar
it
hmet
ic,et
c.
Openingandclosi
ngsf i
le,r
eadingandwr i
tingafil
e
Lear
ningObj
ect
ives
To f ami l
iari
ze t he st udent with basi
c concept
s of comput er
programmi nganddev el
opmentt ool
s.
Topr esentt hesy ntaxandsemant i
csofthe“C”languageaswel las
dataty pesofferedbyt helanguage
Toal low t hest udentst owr i
tethei
rownpr ogr
amsusi ngst andard
l
anguage i nfr
ast r
ucturer egardl
ess of t
he hardware or software
pl
atform.
Ref
erences/
Fur
therReadi
ng
CSC203
NOTE
1
MODULETI TLE: STRI NG, STRUCTUREANDPOI NTERS
Unit1: String
Introduct ion
Char act ersar et hef undament albui ldi
ngblocksofsour cepr ograms.Ev ery
progr am i scomposedofasequenceofchar act erst hat—whengr ouped
toget hermeani ngf ull
y —isi nt erpr eted by t he comput eras a ser ies of
i
nst ruct i
onsusedt oaccompl ishat ask.Apr ogram maycont ainchar act er
const ant s.A char acterconst anti s an integerv alue repr esented as a
char act eri nsi ngl equot es.Thev alueofachar act erconst anti st heint eger
valueoft hechar acteri nt hemachi ne’schar act erset .Forexampl e,' z'
represent st hei nt egerv alueofz, and' \
n'theintegerv alueofnewl ine.
Stringi saser i
esofchar act er st reat edasasi ngl
euni t.Ast ringmayi ncl ude
l
et t
er s,di gitsandv ariousspeci alchar acterssuchas+,- ,*,/and$.St ri
ng
l
iterals,orst r
ingconst ant s,i nC st ri
ngsar ewr itteni ndoubl equot at i
on
mar ksasf ollows:
Forexampl e:“ JohnQ.Doe”i sanamest r i
ng;“ 99999Mai nSt reet”isan
addr essst ringet c.
Ast r
ingi nCi sanar rayofchar act erstypeendi ngi nt henul lchar acter( '
\ 0'
).
Ast ringi saccessedv iaapoi nt ert ot hefi
rstcharact eri nthest r
ing.
Decl ar ationofAr rayofchart ype
Ast r
ingv ariabl ei sanyv alidCv ariablenameandi sal way sdecl aredasan
array .Thesy ntaxofdecl ar ationofast ri
ngv ari
ablei s:
charst ring-name[ si ze];
Thesi zedet ermi nest henumberofchar acterint hest ri
ngname.Exampl e:
Anar rayofchart y pet ost or et heabov estri
ngi stobedecl aredasf ol
lows:
charst r[8];
Anar rayofcharisalsocall
edasastringv ar
iable,si
nceitcanst
oreast r
ing
and itper mits us to change i
ts contents.I n contr
ast,a sequence of
characters
enclosedwi t
hinapairofdoublequot
esi scalledast ri
ngconst
ant.
Example:“Pr
ogram”isastri
ngconst ant.
Ini
ti
ali
z at
ionofArraysofcharType
CSC203
NOTE
2
Thesy ntaxofi niti
alizingast r
ingv ariablehast wov ariations:
Var iation1
charst r1[ 6]={‘ H’,‘
e’,‘l’
,‘
l’
, ‘
o’,‘\
0’};
Her e,st r1i sdecl aredt o beast ri
ngv ariablewi t
hsi zesi x.Itcanst ore
maxi mum si xchar act ers.Thei niti
alizer–l istconsi stsofcommasepar ated
char act erconst ant s.
Not et hatt henul lchar acter‘\ 0’i
scl earlyl i
st ed.Thi sis
requi redi nt hisv ari
at i
on.
Var iation2
charst r2[ 6]={“ Hello”} ;
Her e, st r2i sal sodecl aredt obeast ringv ar iableofsi zesi x.Itcanst ore
maxi mum si xchar act ersincl udingnul lchar acter.Thei nitiali
zer-l
istconsi sts
ofast r i
ngconst ant .Int hi
sv ari
at i
on,nul lchar acter‘\0’wi llbeaut omat icall
y
added
tot heendofst ringbyt hecompi ler.Inei theroft hesev ariati
ons,t hesi zeof
thechar act erar raycanbeski pped, inwhi chcase, t
hesiz eandt henumberof
char act er si nt he i niti
al i
zer-li
stwoul d be aut omat i
cal ly suppl i
ed by t he
compi ler.
Exampl e
charst r1[]={“ Hel l
o”} ;
Thesi zeofst r
1woul dbesi x,f i
v echar acterspl usonef ort henul l
char act er‘\ 0’.
charst r
2[]={‘ H’, ‘
e’,‘
l’,‘
l’
,‘o’,
‘\0’};
Thesi zeofst r2woul dbesi x,fivechar act ersplusonef ornull character
‘
\ 0’.
Exampl e1
Pr ogr am t osor tal istofnumber s.
#incl ude<st dio.h>
#incl ude<coni o.h>
voi dmai n()
{
i
ntx[ 6], n,i, j
,tmp;
clrscr () ;
pr i
ntf( “ Ent ert heno.ofel ement s\ n”);
scanf( “%d” ,&n) ;
pr i
ntf( “ Ent er%dnumber s\ n” ,n)
;
for( i=0; i<n; i
++)
scanf (“%d” ,&x[ i]);
/*sor tingbegi ns* /
for( i=0; i<n; i
++)
for( j=i +1; j<n; j
++)
CSC203
NOTE
3
i
f(x[i]
>x[j
])
{
tmp=x[ i
];
x[i]=x[ j
];
x[j]=tmp;
}
/*sorti
ngends* /
pri
ntf(“sort
edli
st\n”
);
for(i
=0; i
<n;i
++)
pri
ntf(“%d”,
x[ i
])
;
getch();
}
I
nput–Out put
Entertheno.ofelement
s
5
Enter5number s
1030205040
Sortedli
st
1020304050
Exampl e2:
Cpr ogr am foraddi t
ionoftwomat r
ices.
#include<st dio.h>
#include<coni o.h>
#include<pr ocess.h>
voidmai n()
{
i
ntx[ 5][5]
,y[ 5][5]
,z[5][
5],m,n,p,q,i
,j
;
clr
scr() ;
printf(“Enternumberofr owsandcolumnsofmat r
ixx\
n”)
;
scanf( “%d%d” ,
&m, &n);
printf(“Enternumberofr owsandcolumnsofmat r
ixy\
n”)
;
scanf( “%d%d” ,
&p,&q);
i
f( (m !=P)| | (n!
=q))
{
printf(“Mat r
icesnotcompat ibl
eforaddit
ion\
n”)
;
exit(
1) ;
}
printf(“Entertheelement sofx\n”)
;
for(i=0; i
<m; i++)
CSC203
NOTE
4
for(
j=0;j
<n; j
++)
scanf(“
%d” ,&x[i
][
j]
);
pri
ntf(“
Entertheelementsofx\
n”)
;
for(
i=0;i
<p; i
++)
for(
j=0;j
<n; j
++)
scanf(“
%d” ,&y[i
][j
])
;
/*Summat ionbegins*/
for(
i=0;j
<m; i++)
for(
j=0;j
<n; j
++)
z[i
][j
]=x[i
][j
]+y[ i
][j
];
/*summat i
onends* /
pri
ntf(“
Sum mat ri
xz\ n);
for(i
=0;i
<m; i++)
{
for(j
=0;j
<n;j++)
pri
ntf(“
%d”,z[i][
j]
);
pri
ntf(“
\n”
);
}
getch()
;
}
Exampl e3
Wr it
eapr ogram f ormulti
pli
cati
onoft womat r
ices.
#include<st dio.h>
#include<coni o.h>
#include<pr ocess. h>
voidmai n()
{
i
ntx[ 5][5],
y[ 5][5],z[
5][5]
,m, n,p,q,I
,j
,k;
cl
rscr() ;
printf(“Enternumberofr owsandcol umnsofmat r
ixx\n”
);
scanf( “%d%d” ,&m, &n);
printf(“Enternumberofr owsandcol umnsofmat r
ixy\n”
);
scanf( %d%d” ,
&p, &q);
i
f( n!=p)
{
printf(“Mat r
icesnotcompat i
bleformulti
pli
cati
on\ n”
);
exit(1);
}
printf(“Entertheel ementsofx\ n”)
;
CSC203
NOTE
5
for(i
=0; i
<m; i++)
for(j
=0; j
<n;j++)
scanf(“%d” ,
&x[ i][
j])
;
pri
ntf(“Entertheel ement sofy\
n”)
;
for(i
=0; i
<p;i++)
for(j
=0; j
<q;j++)
scanf(“%d” ,
&x[ i][
j])
;
pri
ntf(“Entertheel ement sofy\
n”)
;
for(i
=0; i
<p;i++)
for(j
=0; j
<q;j++)
scanf(“%d” ,
&y[ i][
j])
;
/*Mul t
ipli
cationofmat r
icesofx7yends*
/
for(i
=0; i
<m; i++)
for(j
=0; j
<q;j++)
{z[ i
][j
]=0;
for(k=0;k<n; k++)
z[i][
j]+=x[ i][k]*y[ k][
j]
;
}
/*Mul t
ipli
cationofmat r
icesofx¥ds*
/
pri
ntf(“ProductMat r
ixz\ n”)
;
for(i
=0; i
<m; i++)
{
for(j
=0; j
<q;j++)
pri
ntf(“%d”,z[i][
j])
;
pri
ntf(“\n”)
;
}
getch();
}
for( i
=0; i<3; i
++)
{
for( j
=0; j<3; j
++)
{
b[i][j]=a[ j][i
];
printf( “%d” ,b[
i][
j])
;
printf( “\n”);
}
}
get ch() ;
}
Exampl e5
Wr itea‘ C’ program tofindt heav er
agemarksof‘
n’st
udent
sof
fi
vesubj ectsforeachsubj ectusingar
ray
s.
Ans.
#include<st di
o.h>
voidmai n()
{
i
ntSno, S1, S2,
S3;
fl
oatt ot,av g;
charsname[ 10];
printf(“Ent erstudentno; ”)
;
scanf (“%d” ,&Sname) ;
printf(“Ent ersubject-1, sub-2, sub-3marks;
”)
;
scanf (“%d%d%d” ,&s1,&s2,&s3);
tot=S1+S2+S3;
avg=t ot/3;
printf(“total =%f”,tot)
;
printf(“Av erage=%f ”
,av g);
}
CSC203
NOTE
7
Exampl e6
Wr iteaCpr ogram t ocheckthegivenwordis‘Pal
i
ndr
ome’
ornot
.
Ans.
#incl ude<st di
o. h>
#incl ude<coni o.h>
voidmai n()
{
charst r[
80] ,r
ev [80];
i
ntk, i,j
, f
lag=0;
clrscr() ;
printf( “
Ent eranyst r
ing(max.80chars):\n”
);
get s( str)
;
for( i=0;st r
[i
]!
=‘ \0’;i
++);
for( j=i-
1; k=0;j>=0; j
—,k++)
rev[k]=st r[
j]
;
rev[k]=‘ \0’;
for( i=0;st r
[i
]!
=‘ \0’;i
++)
{
i
f( str [
i]
!=rev[i
])
{
fl
ag=1;
break;
}
}
i
f( flag==1) ;
printf( “
Gi venst ringisnotpal
indr
ome.\ n”
);
else
printf( “
Gi venst ringispal
indr
ome.\ n”
);
get ch() ;
}
Stri
ngHandlingFunctionsin‘C’
Toper for
m mani pul
ationsonstri
ngdata,ther
ear ebuil
t-
in-
funct
ion(l
i
brar
y
functi
on)Supportedby‘ c’
compil
er.Thestr
ingfunct
ionsare.
1.STRLEN( S1)
2.STRCMP( S1,S2)
3.STRCPY( S1,S2)
4.STRCAT( S1,S2)
1.STRLEN( S1):Thisfuncti
onisusedtoret
urnthelengthofthestri
ngname
S1,
Ex:S1=‘ MOID’
CSC203
NOTE
8
STRLEN( S1)=4
2.STRCMP( S1,S2):Thisisal i
brar
yfunctionusedtoperfor
m compar i
son
betweent wost ri
ngs.Thisf uncti
onreturnsav al
ue<zer
owhenst r
ingS1i s
l
esst hanS2.Thef uncti
onr et
urnav al
ue0whenS1=S2.Fi nal
lyt
hef uncti
on
ret
urnav alue>0whenS1>S2.
3.STRCPY( S1,S2):Thisisal ibr
aryfuncti
onusedt ocopythestr
ingS2t o
S1.
4.STRCAT( S1,S2) :Thisisal i
brar
yf unct
ionusedt oj
ointwostri
ngsone
aft
ertheot her.Thi
sf uncti
onconcatenatesstr
ingS2attheendofstri
ngS1.
Uni
t2:Structur
esin‘C’
St
ruct
ure
2.
0Int
roduct i
on
2.
1Def i
nit
ionofStruct
ure
2.
2StructureDecl
arati
on
2.
3StructuresandArrays
CSC203
NOTE
9
2.
4St
ructurecont
ainsPoi
nters
2.
5Uni
ons
2.
6Defi
nit
ionofUnion
2.
7Di
ffer
encesbetweenStruct
ureandUni
on
Lear
ni ngObj ecti
ves
•Impor tanceofst ruct
ures
•Definiti
onofst ructur
e
•Implement ationofar r
aysinstr
uctur
es
•Definiti
onofUni on
•Uniondecl arati
on
•Dif
fer encesbetweenst ruct
uresandUnion
2.0Introduct ion
Arraysar eusef ult or efersepar atev ar i
abl eswhi char et hesamet y pe.i .e.
Homogeneousr efer r
edbyasi nglename.But ,wemayhav esi tuations
wher et herei s a need f or us t or efer to di ff
erent t ypes of dat a
(Heterogeneous)i nor dert oder i
v emeani ngfulinformat i
on.
Letusconsi dert hedet ailsofanempl oy eeofanor ganization.Hi sdet ails
i
ncludeempl oyer’snumber( Integert ype) ,empl oyee’sname( Char actert y pe)
,basi cpay(I ntegert y pe)andt otalsal ary(Fl oatdat at ype).Al lt hese
detail
sseem t obeofdi fferentdat at y pesandi fwegr oupt hem t oget her ,
they wi llr esulti n gi v i
ng usef uli nf or mation aboutempl oyee oft he
organizat i
on.
Inabov esai dsi t
uat ions,Cpr ov idesaspeci aldat at y
pescal ledSt r uctur e,
whichi shi ghlyhel pfultoor gani zedi fferentt ypesofv ari
abl esunderasi ngl e
name.
2.1Def initi
onofSt ructure
Agr oupofoneormor ev ariablesofdi ff erentdat at y
pesor ganizedt oget her
underasi nglenamei scal ledSt ructure.
Or
Acol lectionofhet erogeneous( dissimi lar)typesofdat agr oupedt oget her
underasi nglenamei scal ledaSt ructure.
Ast ructur ecanbedef i
nedt obeagr oupofl ogicall
yr elateddat ai tems,
whichmaybeofdi fferentt ypes,st or edi ncont iguousmemor yl ocat ions,
sharingacommonname, butdi stinguishedbyi tsmember s.
Henceast ructurecanbev iewedasahet erogeneoususer -defineddat at y pe.
Itcanbeusedt ocr eatev ar i
abl es,whi chcanbemani pulatedi nt hesame
wayasv ariablesofbui lt-
indat at ypes.I thel psbet teror gani zationand
managementofdat ainapr ogr am.
CSC203
NOTE
10
When a st r
uctureisdef i
nest he enti
re group’sref
erenced through the
str
uct urename.Thei ndivi
dualcomponent spr esentint hestructur
ear e
call
ed st ructure member s and those can be accessed and pr ocessed
separat ely.
2.2Str uctur eDeclarati
on
Thedecl ar ati
onofast ructur
especi f
iesthegroupingofv ari
ousdat ait
ems
i
ntoasi ngl eunitwithoutassigninganyr esourcestothem.Thesy ntaxfor
declaringast r
uctur
ei nCi sasfoll
ows:
str
uctSt ructure-Name
{
Dat aTy pemember -1;
Dat aTy pemember -2;
….….
Dat aTy pemember -n;
};
Forexample,st
udent
.dob.dayr
efer
stot
heel
ementdayoft
hei
nner
str
uct
uredob.
Unit3: Pointerin‘
C’:VariableDefinit
ionsandIniti
alizati
on
Pointersar ev ari
ableswhosev aluesar ememor yaddr esses.Nor mally,a
vari
abledi rectlycontainsaspeci ficv al
ue.A poi nter,ontheot herhand,
containsanaddr essofav ar
iablet hatcontainsaspeci f
icv alue.Inthis
sense,av ariabl
enamedi r
ectl
yr eferencesav alue,andapoi nterindi
rectl
y
ref
erencesav al
ue( Fi
g.3.1).Referencingav al
uet hr oughapoi nteriscal
led
i
ndirection.
CSC203
NOTE
14
Fi
g.3.
1. Di
rect
lyandi
ndi
rect
lyr
efer
enci
ngav
ari
abl
e
Poi nt
ers,likeal lvariables,mustbedef inedbeforet heycanbeused.The
def i
niti
on
i
nt* countPtr,count;
specif i
esthatv ari
ablecount Ptrisoft ypei nt*(i
.e.,apointertoaninteger)
andi sr ead,“ countPtrisapoi ntertoint ”or“countPtrpointstoanobjectof
typei nt.
”Al so,thev ari
abl ecountisdef inedt obeani nt,notapoint
ert oan
i
nt .The*onl yappl i
est ocount Ptrint hedef i
nit
ion.When*i susedint his
manneri nadef i
nit
ion, i
tindi
catest hatthev ari
ablebeingdefinedi
sapoi nter
.
Poi nt
erscanbedef inedt opointtoobj ectsofanyt ype.
Pointers shoul d be i ni
tialized eit
her when t hey’
re def ined or i n an
assignmentst atement .Apoi ntermaybei ni
tiali
zedt oNULL, 0oranaddr ess.
A poi nterwi tht he v al
ue NULL poi ntsto not hing.NULL i sa sy mbolic
constantdef inedi nt he<st ddef .
h>header( andsev er
alot herheader s,such
as<st dio.
h>).I nit
iali
zingapoi nterto0i sequi valenttoi ni
tiali
zingapoi nter
toNULL,butNULLi sprefer red.When0i sassigned,i t
’sf i
rstconv er
tedt oa
pointeroftheappr opr i
atety pe.Thev alue0ist heonl yintegerv aluethatcan
beassi gneddi rectlytoapoi ntervari
able.
PointerOper ators
The&,oraddr essoper ator,isaunar yoper atort hatreturnst headdr essof
i
tsoper and.Forexampl e,assumi ngthedefinit
ions
inty=5;
int* yPtr;
thest
atement
yPtr=&y ;
assi
gnstheaddr essoft hevari
ableyt
opoint
ervari
abl
eyPtr
.Vari
abl
eyPtri
s
thensaidto“ pointto”y .Fi
gure3.2showsaschemat i
crepr
esent
ati
onof
memor yaf
terthepr ecedingassi
gnmenti
sexecut
ed.
CSC203
NOTE
15
Figur
e 3.
2.Graphi
calr
epr
esent
ati
on ofa poi
nterpoi
nti
ng t
o an i
nteger
vari
ablei
nmemory.
Theunar y*operator,commonlyrefer
redtoastheindi
rect
ionoper
atoror
deref
erenci
ngoperator,ret
urnst
hev al
ueoftheobj
ecttowhichi
tsoperand
(i
.e.
,apoint
er)poi
nts.Forexampl
e,thestat
ement
pri
ntf
("%d"
,*yPt
r);
pri
ntsthev al
ueofv ari
abl
ey ,namel
y5.Usi
ng*i
nthi
smanneri
scal
l
ed
deref
erenci
ngapointer
.
PointerExpr essionsandPoi nt
erAr i
thmet ic
Pointers ar e v ali
d oper ands i n ar i
thmet i
c expr essions, assi gnment
expressi onsandcompar i
sonexpr essi ons.Howev er,notal lt heoper ators
normal l
yusedi nt heseexpr essionsar ev ali
di nconj unctionwi t
hpoi nter
vari
ables.Thi ssect i
ondescr ibest heoper at
or sthatcanhav epoi ntersas
operands, andhowt heseoper atorsar eused.
Al imitedsetofar i
thmet icoper ationsmaybeper f
ormedonpoi nter s.A
pointermay
bei ncrement ed( ++)ordecr ement ed( --
),ani ntegermaybeaddedt oa
pointer( +or+=) ,ani ntegermaybesubt ractedf r
om apoi nter(-or- =)and
onepoi nt ermaybesubt ractedfrom anot her.
Assumet hatarr
ayi ntv [
5]hasbeendef inedandi tsf ir
stelementi satlocat ion
3000
i
nmemor y.Assumepoi ntervPtrhasbeeni ni
tial
izedt opoi ntt ov[0]—i.
e. ,the
val
ueofv Ptri
s3000.Fi gur e3.3il
lustratesthissituat i
onf oramachi newi th4-
byteinteger s.Var i
ablev Ptrcanbei niti
ali
zedt opoi nttoar rayvwi t
hei therof
thestat ement s
v
Ptr=v;
v
Ptr=&v[0]
;
CSC203
NOTE
16
Fi
gur
e3.
3.Ar
rayvandapoi
nterv
ari
abl
evPt
rthatpoi
ntst
ov.
Inconvent i
onalari
thmet i
c,3000+2y i
eldstheval
ue3002.Thi sisnormally
notthe
casewi thpoint
erarithmetic.Whenanintegeri
saddedt oorsubtr
actedfrom
apoi nt
er ,thepointerisnoti ncrementedordecrementedsi mplybyt hat
i
nteger,butbyt hatintegertimesthesizeoftheobjecttowhichthepointer
ref
ers.Thenumberofby tesdependsont heobj
ect
’sdatatype.Forexample,
thestatement
vPt r+=2;
wouldpr oduce3008( 3000+2*4) ,assumingani ntegeri sstor
edi n4by t
es
ofmemor y.Int hear r
ayv ,vPtrwouldnowpoi ntt ov [2]( Fig.3.4)
.Ifanint
eger
i
sst oredin2by tesofmemor y,t
hent heprecedi ngcal culationwouldresul
tin
memor ylocation3004( 3000+2*2) .Ifthearraywer eofadi f
fer
entdatatype,
theprecedi ngst atementwoul dincrementt hepoi nt erbyt wicethenumberof
bytesthatittakest ost oreanobjectoft hatdatat ype.
Whenper formi ngpoi nterar i
thmeticonachar acterar r
ay ,theresult
swillbe
consistentwithr egul
arar it
hmet i
c,becauseeachchar act eris1bytelong
Fi
gur
e3.
4.Thepoi
nterv
Ptraf
terpoi
nterar
it
hmet
ic.
CSC203
NOTE
17
IfvPt rhadbeeni ncrement edt o3016, whi chpoi ntst ov[
4],t
hest atement
vPt r-=4;
woul dsetv Ptrbackt o3000—t hebegi nningoft hear r
ay.I
fapoi nterisbeing
i
ncr ement edordecr ement edbyone,t hei ncrement( ++)anddecr ement( -
-)
oper atorscanbeused.Ei theroft hestat ement s
++v Ptr;
vPt r++;
i
ncr ement st hepoi ntertopoi nttot henextl ocationinthearray.Ei therofthe
statement s
-
-v Ptr;
vPt r-
-;
decr ement st hepoi nt ert
opoi nttot hepr ev i
ousel ementofthear ray .
Point erv ar i
ablesmaybesubt r
act edf rom oneanot her.Forexampl e,if
vPtrcont ainst hel ocat i
on3000,andv 2Ptrcont ainstheaddr ess3008,t he
statement
x=v 2Pt r-v Ptr;
woul dassi gnt oxt henumberofar rayel ement sfrom vPtrtov 2Ptr,i
nt hi
s
case2( not8) .Poi nterar i
thmet i
ci smeani ngl
essunl essper formedonan
array .Wecannotassumet hatt wov ar i
ablesoft hesamet ypear estored
cont i
guousl yi nmemor yunlesst hey’r
eadj acentel ementsofanar ray.
b.Thefuncti
onsfcl
ose(
)
Thefi
lesthatar
eopenedshoul
dbecl
osedaf
teral
lthedesi
redoper
ati
onsar
e
CSC203
NOTE
20
performedoni t. Thi
scanbeachi ev
edt hroughthisfunct
ion.
Theusageof
thi
sf uncti
onis:
fcl
ose(fi
lepointer);
Wher ef i
l
epointerisreturnedval
ueoft hefopen()functi
on.
Exampl es:
1.fclose(inputfi
le);
2.f close(
outputfi
le)
;
c.Thef uncti
onsget c()&f scanf(
)
1.getc()f unctions:thi
sf uncti
onisusedasi nglechar
act
erfr
om agivenfi
le
,whenev eraf i
leisrefer
encedbyaf i
lepointer
.Theusageofthisf
uncti
onis
get c(f
ilepointer)
;
2.fscanf() functi
on:Thi sf uncti
onisusedt or eadaformat
teddatafrom a
specif
iedf i
l
e.Thegener alusageofthisfuncti
oni s
fscanf( fptr,
“Cont r
ol St
ri
ng”,&li
st);where
f
ptr af
il
epoi
ntert
orecei
vef
ormat
teddat
a
Cont
rol
str
ing dat
aspeci
fi
cat
ionsl
i
st
List t
heli
stofv
ari
ablest
ober ead
fscaf(
inf
il
e,“%d%d,”&no,&marks)
;
Exerci
ses
01.Defi
neanAr ray.Explainone- dimensionalar
ray
02.Explai
nabouttwo-di mensional ar
ray?
03.Explai
nhowt odeclar e,i
niti
alizearrayofchartype.
04.Writ
eaCpr ogram tosortal istofnumber s.
05.Writ
eaCpr ogram foradditionoft womat ri
ces.
06.Writ
eapr ogram formul t
ipli
cat ionoftwomat ri
ces.
07.Writ
eapr ogram topr i
nttransposeofamat rix.
08.Explai
nStri
nghandl ingfunct i
onsi nC.
09.Wr i
teaCpr ogram t oconcat enat
et hegiventwost r
ingsandpr intnew
str
ing.
10.Explai
naboutFi l
eoper at
ionsl i
kefopen(),f
close()
,fpr
int()
,fscan().
CSC203
NOTE
22