BSC 1st Sem C Notes
BSC 1st Sem C Notes
2021
Sub:
Progr
ammi
ngi
nC
B.
sc(
MPCS/
MECS/
MCCS/
MSTCS/
MSTD
S)
DEPT.OFCOMPUTERSCI
ENCE
2020-
2021
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence2
1.whatiscomputer?Explai
nchar acteri
sti
csofcomput er.
***
(Or)
whatiscomput er
?Explaincapabilit
iesandli
mitationsofcomputer
?
Comput er
:Acomput eri
sanel ectr
onicdevi
cet hatt
akesthedata,
processitandgi
ves
theinformati
ontotheusers.Iti
sadev i
ceusedf orcoll
ecti
ng,st
ori
ng,andprocessi
ngt
he
userinformati
onwitht
hehi gherspeedandaccur acy.
Char
act
eri
sti
csofComput
er(
OR)Capabi
l
iti
esofcomput
er:
2.Whatar
etheAppl
i
cat
ionsofcomput
er?
***
i
)Educati
onalInst
ituti
ons:
-Computer
sar eusedinschool
andcoll
egesforeasyl
earni
ng.The
computerbasedlearni
ngmakest hestudentst
ogainknowledgeaboutaspeci
fi
ctopi
c.Web
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence3
basedl earni ngf aci li
tiesinfor mat i
onaboutv ar i
oust opics, f
il
li
ngappl icat i
onf orms, wr i
ti
ng
onlineexamset c.
i
i)Sci ence: comput ersar eusedbysci entistsi nfieldsofr esear chanddev elopment .Itis
al
sousedf oranal y zi
ngnewt heor i
es,pr edictingnat uralcalami tiesli
ket sunami and
earthquake.
i
ii
)Communi cat ion: -
comput er shelpt heuser st ot ransferdat af rom onesy stem toanot her
system.I nter netpr ov idesi nteract i
onamongv ari
oususer s.
i
v)Busi ness: -Comput ersar eusedi nbusi nesst omai ntainrecor dsoft heiraccount s, about
profitandl oss.Comput ersal sousedf orconduct ingmeet ingv iawebconf erencing.
Comput erandi nt ernetal sohel psincar r
yingoutonl inebusi ness.
v)Banki ng:-Comput ersusedi nbanksf oronl inebanki ng.Ithel psi neasyt ransferofmoney
fr
om oneaccountt oanot heraccount .Itisal sousedf ormai nt ainingther ecordsoff i
nanci
al
tr
ansact ions.
vi
)Ent ertainment :
-comput er sar eusedf orcr eatingi nteractivegr aphicsandani mations.
Alsousedf orwat chingmov i
es, toplaygames, t
ol istent othemusi cet c.
vi
i)Gov ernment :
-comput ersar eusedi nv ariousgov t.
depar tment sli
ker ev enue, defense,
i
ndust ry,pol i
ceet c.f orbet termentofpeopl e.
vi
ii)Hospi t
al s:-Comput ersar eusedi nhospi talstokeept rackofpat ientsr ecor dsand
gener atingbi l
ls,tomoni tort hepat ientcondi tionandt oexami net hei nternal partsoft he
body .
i
x)Mi li
tar y:
-Comput ersar eusedi ndesi gningweapons, cont r
ollingaccesst oat omicbomb
etc.
x)Weat herf or ecast :-
Comput ersusedt oanal yzeandf orecastt heweat her .
3.whatar
etheGener
ati
onsofcomput
er?
**
Therearef i
vegener ati
onsofcomput erdependingont hetypeofprocessorsinstal
led
i
namachi ne.
Fi
rstGener ation(1940- 1956)
Thesecomput er
susev acuum Tubet echnologyforcir
cuit
ryandmagnet icdrumsf or
Memor ystorage.
Thi
smachi newasl argeri nsizeandoccupi esentir
eroom.
Theygener ateal otofheatast housandsofv acuum tubeswer eused.Becauseof
this,ai
rconditi
oni ngwasessent i
alforthesemachi nes.
Thecomput ationalspeedwasf asti.
e.,i
nmi ll
i
seconds.
Thesemachi neswer ev eryexpensiveandconsumedl argeamountofel ectr
icit
y.
Theywer emachi ne-languagedependentandhencei tisverydif
fi
cultt
opr ogram and
uset hem.
I
nputsarePunchedcar ds, papertapesandOut putsarePr i
ntouts
E.g.:ENIAC–El ectronicNumer i
cal I
ntegrat
orandCal cul
ator.
UNI VAC–Uni versal Automat icComput er.
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence4
SecondGener ati
on( 1956- 1963)
Thesecomput erswer ebasedont ransistorst echnol ogyandmagnet icdi sksareused
i
nmemor yst orage.
Thesewer esmal leri nsi ze, fast erandmor eener gyef ficientcompar edt othefi
rst
generat i
oncomput er s.
Theygener atel essamountofheat ,butst i
llA. C.wasr equired.
Thecomput at i
onal speedwasv er yhigh.(mi cr oseconds)
Theywer eassembl y-languagedependent .
I
nput sarePunchedcar ds, papert apesandOut put sar ePr intouts
E.g.:
IBM 1620–Sci entificAppl icat i
on
IBM 1401–Busi nessAppl ications
I
BM1794–Usef orbot h
Thir
dGener ation( 1964- Ear ly1970’ s(1971) )
Thesecomput erswer ebasedonI ntegratedCi r
cui ts(IC)t echnol ogy.
Thecomput at i
onal speedwasv er yhigh.(nanoseconds)
Thesewer esmal leri nsi zecompar edt oot hercomput ers.
Theygener atel essamountofheat .A.Cwasnotmandat orybutr equiredi nsome
cases.
Theywer ehi ghl ev el l
anguage( likeFORTRAN, COBAL)dependent .
Thesear el essexpensi ve.
I
nput sareKey boar dsandOut put sar eMoni tor swhi char einterfacedwi than
Operat i
ngsy stem
FourthGener at i
on( Ear l
y1970’ s(1971)t oTi l
l date)
Thesecomput erswer ebasedonmi croprocessor st echnol ogy.
Thesecomput ersusedVer yLar geScal eI ntegr ated( VLSI )Ci r
cuits.
Thesewer esmal leri nsi zecompar edt oot hercomput ers.
Thesemachi neswer epor t
abl easwel lasr eliable.
Thesemachi neswer ev erymuchcheaper .
Theydi dnotgener atemuchheat , thereforeA. C.wasnotr equired.
Thepr oduct ioncosti sv er ylow.
Thesemachi neswer eeasi ert ousebecauseofGUIandpoi nti
ngdev ice.
I
nterconnect i
onamongdi ffer entcomput esr esul tedi nbet tercommuni cationand
resourceshar i
ng.
Fi
fthGener ation( Presentt obey ond)
Thesecomput ersusedSuperLar geScal eIntegr at ed( SLSI )Chips.
Thesecomput ershav elar gecapaci t
yt ost orei nfor mat ionandi nstr
uct ions.
Parall
elpr ocessi ngwasdonet oexecut esev er alinst ruct i
onssi mul t
aneousl yi
na
singl
eoper ati
on.
Art
ifi
cialIntelligencet hatgener allysi mul ateandr epr oducehumanbehav i
orwhich
i
ncludet hinking, speaki ng, andr easoni ng.
Thedi f
ferentt echnol ogiespr esenti nartifi
cial intelligencear eNat ur
al language
processing, Speechandv oicer ecogni tion, andRobot ics.
4.Explaintypesofcomput ersorCl assi f icationofcomput er s?* **
Basedonthesize:
thereare4types
a)Supercomputer
sb)Mai nf
ramecomput er
s c)Microcomputersd)Mi
nicomputer
s
a)Supercomputer
s:thesecomputershav
ehighspeedprocessi
ngandhugest
orage
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence5
capaciti
es.Theyar ecapabl eofper formingsev eralbill
i
onsofcal cul
ationspersecond.
Thesecomput ersar eusedi nweat herfor ecasting, designingofmachi nes,weapons,
aircr
aft
set c.
b)Mai nframecomput ers:t
hesecomput er saredesi gnedt owor kwithl ar
gescal eneedof
businessor gani zat i
on.Thesecomput ersar ecapabl eofst ori
ngandpr ocessinghuge
amountofdat a.Thesecomput erscont ains
Highspeedcomput erpr ocessor
Per i
pher al dev i
cest osuppor tmassi vevol umeofdat apr ocessing
Highper for manceonl inet r
ansact i
onpr ocessi ngsy st
ems.
c)Mi cr
ocomput ers:theyar esmal lerinsi ze.Thesecomput er
sconsi stofmi cropr ocessors,
storageunit,inputuni t,outputuni t.Thesecomput erscanbeusedbyi ndi
vidualuser sin
homes, educat ional i
nstituti
onset c.
Exampl e:Deskt op, l
aptops, handhel dcomput er setc.
d)Mi nicomput er s:thesecomput er scanst oret hedat amor et hanmi crocomput ers.These
aremai nlydesi gnedwi thdual processor .Themai npur poseoft hesecomput ersist ocarry
outoper ati
onsbyconnect i
ngt omai nfr
ames.Thesear econsi deredasnet wor kser ver.Ex.
Industr
ies,educat i
onal i
nstituti
ons, resear chor ganizationsetc.
5.Expl
ainov
erv
iewofCPU.
Comput er: Acomput eri sanel ectroni cdev icet hattakest hedat a,
processitandgi ves
theinfor mationt otheuser s.Itisadev iceusedf orcol lecti
ng, stor
ing,andprocessingthe
userinf ormat i
onwi tht hehi gherspeedandaccur acy .
Component sofcomput erhar dwar e:Thev ariouscomponent sofcomput erhardwar eareas
fol
lows:
1)Inputuni t
2)Cent ralprocessi nguni t
3)Out putuni t
I
nputuni t:
Thisist hepr ocessofent eringdat aandi nst ructions
i
ntot hecomput ersy st
em.
weneedi nputuni tt oputt hedat aandi nstr uctionsintot hecomput er.
Theinputuni tconsi stsofoneormor einputdev ices.
Ex:key board, mouse, scanneret c.
Central Processi ngUni t:CPUi sconsi der edast hebr ainofcomput ersystem.
I
tper formsdat apr ocessingi nbi nar yf ormati .e.int hef orm of1or0.
Component sofCPU:
Ar it
hmet icandLogi cUni t (ALU)
Cont rol Unit
Memor yUni t
Ar it
hmet i
candLogi cal Unit:ALUi sr esponsi blef orperformingalltheari
thmet i
cand
l
ogical operat i
ons.ALUget sthei nputf rom t hememor yunit,processitandsends
backt her esulttot hei nternal stor age.Af terr eceivi
ngt heresult,
inter
nalstorage
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence6
sendsthedatatot heout putdev ices.ALUperformsal lthemat hemat icaloperati
ons
l
ikeadditi
on,subtr
act ion,mul t
ipl
icati
onanddiv i
sionandal soper for
msl ogi
cal
operati
onsli
kelesst han, greaterthanetc.
Cont rolUni
t:I
tcont rolsallt
heuni t
sinthecomput er.itcontr
olst heflowofdat aand
i
nstructi
onsfrom t
hest orageuni ttoA.L.
U.
Memor yUnit:I
tisusedt ost or
el ar
geamountofdat aandi nstructi
ons.
OutputUnit:Thisuni
tcont ainsvariousout putdevi
ces.Out putdevicesar ethoseusi ngwhich
acomput ercanshowt heout puttot heuser.Thev ar
iousout putdevicesar e:monitor,pri
nter
,
speakersetc.
RoleofI/Odevicesinacomputersyst
em:
Aninput/
outputdevi
ceisanyhardwareusedbyahumanoper at
ororothersyst
emsto
communi cat
ewi thacomputer
.Asthenamesuggest s,i
nput
/out
putdevi
cesarecapabl
eof
sendingdata(output
)toacomputerandrecei
vingdatafr
om acomputer(
input)
.
6.Whati
sanal
gor
it
hm?Whatar
ethechar
act
eri
sti
csofal
gor
it
hm?
Al
gori
thm i
sastep-by-
steppr
ocedur
e,whichdef
inesasetofi
nst
ruct
ionstobeexecutedi
n
acer
tainor
dertogetthedesi
redout
put.
analgor
ithm canbei
mpl
ement edi
nmoret hanone
pr
ogramminglanguage.
Charact
eri
sti
csofanAlgori
thm
Fini
teness−Al
gorit
hmsmustt
ermi
nat
eaf
teraf
ini
tenumberofst
eps.
Unambi
guous−Al
gor
it
hm shoul
dbecl
earandunambi
guous.
I
nput−Anal
gor
it
hm shoul
dhav
e0ormor
einput
s.
Out
put−Anal
gor
it
hm shoul
dhav
e1ormor
eout
put
s
Exampl
eProblem −Desi gnanalgor
it
hm t
oaddt
wonumber
sanddi
spl
ayt
her
esul
t.
St
ep1−START
St
ep2−declaret hreei
nteger
sa,b&c
St
ep3−def i
nev aluesofa&b
St
ep4−addv aluesofa&b
St
ep5−storeout putofstep4toc
St
ep6−printc
St
ep7−STOP
2.Whati
sFlowchar
t?
Fl
owchar
tisadiagr
ammat i
crepresent
ati
onofapr
ogr
am.
Fl
owchar
tsusesimplegeometr
icshapes
Symbol
s
Sy
mbol Symbol Pur
pose
Name
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence7
Usedatthebeginni
ngandendoft
heal
gor
it
hm t
o
St
art
/St
op
showstartandendofthepr
ogr
am.
I
ndi
cat
espr
ocessesl
i
kemat
hemat
ical
oper
ati
ons.
Pr
ocess
Input/ Usedf
ordenot
ingpr
ogr
am i
nput
sandout
put
s.
Output
Standsf
ordeci
si
onstat
ementsi
napr
ogr
am,
wher
e
Deci
sion answeri
susual
lyYesorNo.
Showsr
elat
ionshi
psbet
weendi
ff
erentshapes.
Ar
row
On-
page Connect
stwoormorepar
tsofaf
lowchar
t,whi
char
e
Connect
or onthesamepage.
Exampl
e:Dr
awaf
lowchar
ttoi
nputt
wonumber
sfr
om useranddi
spl
ayt
hel
argestoft
wo
number
s
7.Whati
spr
ogr
ammi
ngl
anguage?Expl
aint
ypesofl
anguages?
progr
ammi ngl
anguagei sthemedium ofcommuni cat
ionbetweenyou(aperson)anda
computersyst
em.Itisthesetofsomei nst
ructi
onstoperf
orm ourtask.
TypesOfLanguages:
Typesofcomputerprogramminglanguages
Therearebasi
cal
lythreety
pesofcomput erprogramminglanguages,t
heyar
e
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence8
1.Lowl ev el pr ogr ammi ngl anguages
2.Hi ghl ev el progr ammi nglanguages
3.Mi ddlel ev el pr ogrammi nglanguages
1)Lowl ev elpr ogr ammi ngl anguages
Machi nel anguageandAssembl ylanguagesar ethel owl ev el progr ammi ng
languages.
Thesear emachi nedependentpr ogrammi nglanguagessuchasBi nary(Machi ne
code)andAssembl ylanguage.
Si ncecomput eronl yunder standt heBinarylanguaget hatmeansi nstructi
onsi nthe
for m of0’ sand1’ s.Machi neCode( BinaryLanguage)doesnotneedanyi nterpret
eror
compi lert oconv ertlanguagei nanyf orm becausecomput erunder standsthese
signal sdi r ectly .
2)Highlev el pr ogr ammi nglanguages
Thesear et hemachi neindependentpr ogrammi nglanguages, whi char eeasyt owrite,
read, edi tandunder stand.
Comput erdoesnotunder standpr ogram writt
eninhi ghlev ellanguagesdi rectly.
Pr ogr ammi ngt r
anslatorsar erequi r
edt oconvertahi ghlev elpr ogr am toits
equi valentMachi necode.
Pr ogr ammi ngt r
anslatorssuchasCompi l
ersandI nterpretersar ethesy stem
sof t
war e’swhi chconv ert
sapr ogram wr i
tt
eninpar t
icularpr ogr ammi nglanguagest o
itsequi v alentMachi necode.
3)MiddleLev el pr ogr ammi ngl anguage
Thepr ogr ammi nglanguageswhi chhav efeaturesofLowLev el aswel lasHi ghLev el
pr ogr ammi ngl anguagesknownas" MiddleLevel"programmi ngl anguage.
Cpr ogrammi ngl anguagesi sthebestexampl eofLowLev el Pr ogrammi ng
languagesasi thasf eaturesofl owl evelandhighlev elprogr ammi nglanguagesbot h.
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence9
Subpr
ogram Secti
on
user-
def
inedfunct
ions
Funct
ion1
.
.
Funct
ionn
1)Document ati
onSect i
on
Thi si susedt owr i
tecomment swhi char eusedt oexpl ainaboutst atement s(progr
am)
andaut horname.
Document ati
onsect ioni snon- execut ablesect ion.
2)Pr epr ocessorDi recti
v esSect i
on
LinkSect ion
Thel inksect ionconsi stsoft heheaderf i
l
esoft hefunct ionst hatar eusedi ntheprogr
am.
Itpr ov idesi nstruct i
onst othecompi l
ertol i
nkf unctionsf rom t hesy stem li
brary
Toincl udeheaderf iles
#incl ude<st dio.h>
#i ncl ude<coni o.h>
3)Gl obal Decl arati
onSect i
on
Gl obal var i
ablesar et hosev ari
abl eswhosev aluecanbeaccessedt hroughoutthe
compl et eprogr am ori nal lfunct ions.
Gener al l
y ,global var i
ablesar edecl aredbef orethemai nf unction.
4)mai n()f unct i
on
EveryPr ogr am musthav eonemai n( )funct i
on.Ther eisonl yonemai nfunctioninthe
compl etepr ogram.Pr ogr am execut ionst artsfrom t hemai nfunct ionandal soendsatt he
mainf unct ion.
5)Subpr ogr am sect i
on
User -Def inedFunct ions: Thesear et hesubpr ogram.Thesear edef inedbyt heUser ,
accor dingt ot heirneeds.
9.Whatar eKey wor dsin‘ C’?
Keywor dsar ether eserv edwor dsint heCCompl iers,wecannotchanget hemeani ngsof
them, thesear et hewor dswhi chhav epr edef i
nedmeani ngint hecompi l
ers.
CLanguagehas32key wor ds,whi char e:
auto ext er n si zeof br eak st atic case f
or st ruct
goto swi tch const i f t ypedef cont i
nue i nt char
fl
oatuni on def aul t l ong unsi gned do voi
d r egister
doubl er etur n v ol ati
le el se shor t whi l
e enum si gned
10.WhatareI
dent
if
ier
sin‘
C’?
Anidenti
fi
eri
sthenameofvari
abl
e,const
ant
,ar
ray
,st
ruct
ure,
funct
ionset
c.Thesear
ethe
userdef
inednames
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence10
Her
ear esomeoft herulestodefi
neani dent if
ier
:
AnI dentif
iermuststartwit
hachar acterorunderscore.
On l
y32char act
ersareall
owedasani denti
fi
ername.
Sp acesar enotal l
owedinthei dentif
iername.
Ak ey wordcannotbeuseast heident i
fi
ername.
Ch ar acter
s,digi
ts,under
scoresar eallowedinidentif
iername.
Constant
Aconstantisav alueorv ar
iabl
ethatcan'tbechangedi nt heprogram.
Const
ant Exampl
e
I
ntegerConst
ant 10,
20,
450et
c.
Real
orFl
oat
ing-
poi
ntConst
ant 10.
3,20.
2,450.
6et
c.
Char
act
erConst
ant '
a'
,'
b'
,'
x'et
c.
St
ri
ngConst
ant "
c",
"cpr
ogr
am"
,"ci
njav
atpoi
nt"et
c.
11.
whatisavari
abl
e?Expl
ainscopeofav ar
iabl
e.
Ascopeinanyprogrammingisar egi
onoftheprogram whereadef
inedv
ari
abl
ecanhav
e
i
tsexi
stenceandbey
ondthatvari
ablei
tcannotbeaccessed.
nsi
deaf
unct
ionorabl
ockwhi
chi
scal
l
edl
ocal
var
iabl
es.
Out
sideofal
lfunct
ionswhi
chi
scal
l
edgl
obal
var
iabl
es.
Local
Var
iabl
es
Var
iabl
est
hatar
edecl
aredi
nsi
deaf
unct
ionorbl
ockar
ecal
l
edl
ocal
var
iabl
es.
Theycanbeusedonl
ybyst
atement
sthatar
einsi
det
hatf
unct
ionorbl
ockofcode.
Local
var
iabl
esar
enotknownt
ofunct
ionsout
sidet
hei
rown.
Thef
oll
owi
ngexampl
eshowshowl
ocal
var
iabl
esar
eused.
Her
eal
lthev
ari
abl
esa,
b,andcar
elocal
tomai
n()f
unct
ion.
#i
ncl
ude<st
dio.
h>
i
ntmai
n(){
/
*localvar
iabl
edecl
arat
ion*
/
i
nta,b;
i
ntc;
/*act
ual
ini
ti
ali
zat
ion*
/
a=10;
b=20;
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence11
c=a+b;
pr
int
f("
val
ueofa=%d,
b=%dandc=%d\
n",
a,b,
c);
r
etur
n0;
}
Gl
obal
Var
iabl
es
Gl
obal
var
iabl
esar
edef
inedout
sideaf
unct
ion,
usual
l
yont
opoft
hepr
ogr
am.
Globalv
ari
ablesholdthei
rval
uest
hroughoutt
heli
feti
meofy ourpr
ogr
am andt
hey
canbeaccessedinsi
deanyofthef
uncti
onsdefi
nedforthepr
ogram.
A gl
obalvar
iabl
ecanbeaccessedbyanyfunct
ion.Thati
s,agl obalv
ari
abl
eis
av
ail
ablef
orusethr
oughouty
ourent
ir
epr
ogr
am af
terit
sdecl
arat
ion.
Thef
oll
owi
ngpr
ogr
am showhowgl
obal
var
iabl
esar
eusedi
napr
ogr
am.
#incl
ude<st
dio.
h>
/*global
var
iabl
edecl
arat
ion*
/
i
ntg;
i
ntmai
n(){
/
*localvar
iabl
edecl
arat
ion*
/
i
nta,b;
/*act
ual
ini
ti
ali
zat
ion*
/
a=10;
b=20;
g=a+b;
pr
int
f("
val
ueofa=%d,
b=%dandg=%d\
n",
a,b,
g);
r
etur
n0;
}
12.
whatar
ethest
oragecl
asses?
Astoragecl
assdefi
nesthescope(v
isibi
l
ity
)andli
fe-
ti
meofv ar
iabl
esand/orfunct
ions
wi
thinaCProgr
am.Theyprecedet
hetypethatt
heymodif
y.Wehavefourdi
ff
erentst
orage
cl
assesinaCprogr
am −
aut
o
r
egi
ster
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence12
st
ati
c
ext
ern
Theaut
oSt
orageCl
ass
Theaut
ost
oragecl
assi
sthedef
aul
tst
oragecl
assf
oral
ll
ocal
var
iabl
es.
{
i
ntmount;
aut
ointmont
h;
}
Theexampleabov edef
inestwovar
iableswi
thi
nthesamest
oragecl
ass.'
aut
o'canonl
ybe
usedwit
hinfunct
ions,i
.e.
,l
ocalv
ari
ables.
Ther
egi
sterSt
orageCl
ass
Theregisterstor
agecl assisusedt odef i
nelocalvari
abl
esthatshouldbestoredina
regi
sterinsteadofRAM.Thi smeanst hatthevari
abl
ehasamaxi mum si
zeequaltothe
regi
stersize(usuall
yonewor d)andcan'
thavetheunary'
&'oper
atorappl
i
edtoit(
asitdoes
nothaveamemor ylocat
ion)
.
{
regi
steri
ntmi
l
es;
}
Theregi
stershoul
donlybeusedf orvar
iabl
esthatr
equir
equickaccesssuchascounters.
I
tshouldalsobenotedthatdef
ini
ng'r
egi
ster'
doesnotmeant hatt
hevari
abl
ewil
lbestored
i
nar egist
er.ItmeansthatitMIGHTbest oredinaregi
sterdependi
ngonhardwareand
i
mplementationr
estr
ict
ions.
Thest
ati
cSt
orageCl
ass
Thestat
icst
orageclassinst
ruct
sthecompil
ertokeepalocalv
ari
ablei
nexi
stencedur
ing
thel
if
e-t
imeoft heprogr
am inst
eadofcreat
inganddest
royi
ngiteachti
meitcomesinto
andgoesoutofscope..
Thestat
icmodi
fiermayal
sobeappli
edtoglobalv
ari
abl
es.Whenthisi
sdone,i
tcauses
thatv
ari
abl
e'
sscopetober
est
ri
ctedt
othefi
l
ei nwhi
chiti
sdecl
ared.
I
nCprogr
amming,whenst
ati
cisusedonaglobalv
ari
abl
e,i
tcausesonl
yonecopyoft
hat
membert
obeshar
edbyallt
heobject
sofi
tscl
ass.
Li
veDemo
#i
ncl
ude<st
dio.
h>
/
*functi
ondeclar
ati
on*
/
v
oidfunc(v
oid)
;
st
ati
cintcount=5;
/*gl
obal
var
iabl
e*/
mai
n(){
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence13
whil
e(count
--
){
func()
;
}
ret
urn0;
}
/
*functi
ondefi
nit
ion*
/
v
oidfunc(v
oid){
st
ati
cinti
=5;
/*l
ocal
stat
icv
ari
abl
e*/
i
++;
pr
int
f("
iis%dandcounti
s%d\
n",
i,count
);
}
Theext
ernSt
orageCl
ass
Theext
ernstorageclassisusedtogi
v ear eferenceofaglobalv ar
iabl
et hati
svi
sibl
eto
ALLtheprogram fi
les.Whenyouuse'ext
ern',thev ar
iabl
ecannotbei ni
ti
ali
zedhowever
,it
poi
ntst
hev ar
iablenameatast or
agel
ocati
ont hathasbeenpr ev
iousl
ydef i
ned.
Wheny ouhav emulti
plefi
lesandyoudefi
neaglobalvari
ableorfunct
ion,whi
chwillal
sobe
usedinot herfil
es,thenexter
nwillbeusedinanot herf i
l
etopr ovidetheref
erenceof
defi
nedv ari
ableorf unct
ion.Justforunder
standi
ng,externi
susedt odecl
areagl obal
vari
abl
eorf unct
ioninanotherfi
l
e.
Theext
ernmodi
fi
erismostcommonlyusedwhent her
ear
etwoormor
efi
l
esshar
ingt
he
samegl
obalv
ari
abl
esorfunct
ionsasexpl
ainedbel
ow.
Fi
rstFi
l
e:mai
n.c
#i
ncl
ude<st
dio.
h>
i
ntcount;
ext
ernvoi
dwr
it
e_ext
ern(
);
main(
){
count=5;
writ
e_ext
ern(
);
13.Explainaboutoperatorsi
n‘C’
?
Anoper atorisasy mbolthatt
ell
sthecompil
ertoperf
orm acert
ainmat hematicalorl
ogi
cal
manipulation.
Forexampl e:
c=a+b;
Here,‘+’i
st heoper orknownasaddi
at ti
onoperat
orand‘a’
and‘b’areoperands.The
addit
ionoper atort
ell
sthecompil
ertoaddbothoftheoper
ands‘a’and‘b’.
Coper
ator
scanbecl
assi
fi
edi
ntof
oll
owi
ngt
ypes:
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence14
Ar
ithmet i
coperator s
Re l
at ionaloperat
or s
Logi cal operat
ors
Bitwi seoper at
ors
As signmentoper at ors
Co ndi ti
onaloperat ors
Sp eci aloperat
ors
Incrementordecr ementoperat
ors
Ar
it
hmeticoper at
ors
Th esear et heoper ator
susedtoper
for
m ar
it
hmet
ic/
mat
hemat
icaloper
ati
onson
oper ands.
Oper
ator Descr
ipt
ion
+ Addi
ti
on
- Subt
ract
ion
* Mul
ti
pli
cat
ion
/ Di
vi
si
on
% modul
us
Rel
ati
onal
oper
ator
s
Rel
ati
onal
oper
ator
sar
eusedf
orcompar
isonoft
hev
aluesoft
wooper
ands.
Oper
ator Descr
ipt
ion
== Equal
to
!
= Notequal
to
> Gr
eat
ert
han
< Lesst
han
>= Gr
eat
ert
hanorequal
to
<= Lesst
hanorequal
to
Logicaloper
ators
Logi
cal Operat
orsareusedtocombinetwoormor econdi
ti
ons/
Expr
essions.
Ther esul
toftheoperat
ionofalogi
caloper
atori
sabooleanval
ueei
thertrueorf
alse(
1or
0).
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence15
Oper
ator Descr
ipt
ion
&& Logi
cal
AND
|
| Logi
cal
OR
! Logi
cal
NOT
Bit
wiseoperator
s
TheBitwiseoperat
orsi
susedt
oper
for
m bi
t-
lev
eloper
ati
onsont
heoper
andst
hati
s
perf
orm onbitsofaval
ue.
Oper
ator Descr
ipt
ion
& Bi
twi
seAND
| Bi
twi
seOR
^ Bi
twi
seexcl
usi
veOR
<< l
eftshi
ft
>> r
ightshi
ft
AssignmentOper ators
Assignmentoper at
orsareusedt oassignv al
uetoav ari
abl
e.Thel ef
tsi deoperandofthe
assignmentoper at
orisavariableandr i
ghtsideoper
andoft heassignmentoper atori
sa
value.
Forexampl e:
a=10;
b=20;
ch=' y'
;
Condi t
ional oper
ator
Thecondi t
ionaloperat
orsinCl anguageisalsoknownasTer nar
yoper ator.
Syntax:
expr ession_1?expr essi
on_2: expressi
on_3;
Ifexpression_ 1i
strueexpression_2getsexecuted,i
ffal
sethenexpr ession_3.
Exampl e:
i
nta=4, b=7, c;
c=(a<7?a:
b);
pr
int
f("
%d\
n",
c); /
/out
put
:4
I
ncr
ementandDecr
ementoper
ator
s:
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence16
I
ncr ement
I
tisusedt oincr ementt hevalueoft hev ari
abl eby1.Thei ncrementcanbedoneintwoway
s:
pref i
xi ncr ement
i
ntb=++a;
post fi
xi ncr ement
i
ntb=a++;
Decr ement
I
tisusedt odecr ementt hevalueoft hev ar
iableby1.Thei ncrementcanbedonei
ntwo
way s:
pr efixdecr ement
intb=- -a;/ /b=0
posf ixdecr ement
i
ntb=a- -;
9.Whati sv ariabl e?
Av ar i
abl eisanami ngl ocati
ont hatcanbest oret heval
ue.
Rulesf orv ariabl ename
1.I tdoesnothav easpacebet weenchar act ers.
2.Col lectionofal phabets, digit
s, andunder score(_
).
3.Thef i
rstchar actershoul dbeei t
heralphabetorunder score(_)
.
4.Noot herspeci al symbol exceptunder scor e(_
).
5.Key wor dscannotbeusedasv ari
abl
ename.
Decl arat ionofv ariable
Synt ax:
Dat atypev ar i
abl e_ name;
Exampl e:
i
nta;
I
tt ell
st heuserwhatt ypeofv aluesi tcanhol d.
I
nitializat ionofav ariable
Thepr ocessofassi gninganyv aluet oav ari
abl e.
Exampl e:
i
nta=5;
14.WhatisDatatype?Explaindatatypesin‘
C’
Datatypesspeci
fyhowweent erdataint
oourprogramsandwhatt
ypeofdat
aweent
er.
Clanguagesupports3diff
erenttypeofdatatypes:
Pri
marydatatypes/basi
c/fundamental
Theseareusedtost or
esinglevalueatatime.
I
ntegert
ype
Ty
pe Si
ze(
byt
es)
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence17
i
ntorsi
gnedi
nt 2
unsi
gnedi
nt 2
shor
tintorsi
gnedshor
tint 1
Fl
oati
ngpoi
nt
Thesear
eusedt
ost
oredeci
mal
poi
ntv
alues.
Ty
pe Si
ze(
byt
es)
Fl
oat 4
doubl
e 8
Char
act
ert
ype
Char
act
ert
ypesar
eusedt
ost
orechar
act
ersv
alue.
Ty
pe Si
ze(
byt
es)
charorsi
gnedchar 1
voi
dt ype
voi
dt ypemeansnov al
ue.Thisisusuall
yusedt ospecif
yt hetypeoffunct i
onswhi chret
urns
nothing.
Deriveddat at y pes:
Deriveddat at y pesar eusedt ostoremulti
pleval
uesatat imebutt hosev aluesaresi mil
ar
datat ypev aluesonl y.
Der iveddat at ypesare:
Ar ray s
Poi nter
St ring
Userdef i
neddat atype:
Userdef ineddat atypesar eusedtostoremulti
plevalueswi t
hdifferentdat atypes.
Userdef ineddat atypesare:
St r uct
ure
Uni on
Enumer ati
on
15.Whati sTy peconv ersionorTypecasting?
Thet ypeconv er sionisapr ocessconvertav al
ueint
oonedat atypetoanot herdatatype.
1)Impl icitTy peConv er
sion
Conv ertsonet ypeofdat atypetoothertypeofdatatypeimplicit
ly.Thati sconv er
tsmall
dat at ypev aluei nt
obi gdatatypewhichisdoneaut omat i
call
ybycompi lerwithoutuser
interact ion.
Exampl e:inta=5;
floatb=a;
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence18
Rangeoff loatis4,
rangeofinti
s2by t
es
Expl
ici
tTy peConv er
sion
Convertsonetypeofdat aty
petoothertypeofdat
atypeExpli
cit
ly.Thist
ypeofconv
ersi
oni
s
usuall
yper f
ormedbyt heusermanual l
y.Thati
sconvertabigdatat y
pevaluei
ntosmall
dat
a
ty
pev alue.
Exampl e:floata=2.5;
i
ntb=(int)a;
UNI
T–I
I
1.Explainaboutf or
mat t
edI nputandOut putoperat
ions?
1)Format t
edI nputandOut putOper ati
ons:Theseoperati
ons/
funct
ionsar
eusedforr
eading
andwr iti
ngv aluesfrom keyboar danddi spl
ay sonmoniter.
1)scanf ()
Sy ntax:
scanf (“f
ormatspecifiers” ,&vari
ablesli
st);
wher eformatspecifi
er: Itisawayt otellt
hecompi l
erwhatty
peofdataisi
navari
able
and&i stheaddressoper atorinC.
1)i nta;
scanf (“
%d”,&a);
2)pr intf()
Thepr intf
()method,pr intsthev al
uepassedast heparametert
oit
.
Syntax:
pri
ntf(
“formatspeci fier
s”,variablesl i
st)
;
for
mat speci fi
er:I
tisawayt ot ellthecompi l
erwhattypeofdataisinavar
iabl
e.
pri
ntf(
“%d” ,a);
For
matSpeci
fi
er Descr
ipt
ion
%d I
ntegerFor
matSpeci
fi
er
%f Fl
oatFor
matSpeci
fi
er
%c Char
act
erFor
matSpeci
fi
er
%s St
ri
ngFor
matSpeci
fi
er
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence19
%u Unsi
gnedI
ntegerFor
matSpeci
fi
er
2.Whati
sandEscapesequence?
Whenacharact
eri
sprecededbyabacksl
ash(
\),
iti
scal
l
edanescapesequenceandi
thas
aspeci
almeani
ngtothecompiler
.
Sr
.No EscapeSequence&Descr
ipt
ion
\
t I
nser
tsat
abi
nthet
extatt
hispoi
nt.
\
b I
nser
tsabackspacei
nthet
extatt
hispoi
nt.
\
n I
nser
tsanewl
i
nei
nthet
extatt
hispoi
nt.
\
r I
nser
tsacar
ri
ager
etur
nint
het
extatt
hispoi
nt.
\
f I
nser
tsaf
ormf
eedi
nthet
extatt
hispoi
nt.
\
’ I
nser
tsasi
ngl
equot
echar
act
eri
nthet
extatt
hispoi
nt.
\
” I
nser
tsadoubl
equot
echar
act
eri
nthet
extatt
hispoi
nt.
\
\ I
nser
tsabacksl
ashchar
act
eri
nthet
extatt
hispoi
nt.
3.Whatar ethecont r
olfl
owst atement s?Expl ain?
Controlflowst at ements:Thest atementswhi chspecifyt
heorderofexecut
ionof
stat
ement sarecal ledcontr
olflowst at
ement s.
Therearet hreet ypesofcont r
ol fl
owstatement s.Theyar
e:
1.Conditional st atements
2.Loopingst at ement s
3.Jumpi ngst at ement s
1.Conditionalst atements:thepr ogram needst obeexecuteddependi
nguponapart
icul
ar
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence20
conditi
on.
(i
)‘i
f’statement
(ii
)‘i
felse’st
atement
(ii
i
)‘nestedifelse’
stat
ement
(i
v)‘swit
ch’stat
ement
(i
)‘i
f’st
atement:ifst
atementi
sthemostsimpledeci
sionmaki
ngstatement.I
tisusedt
o
deci
dewhet heracert
ainst
atementorbl
ockofstat
ementswil
lbeexecutedornot.
Syntax f
lowchart
i
f(condi
ti
on)
st
atement
(s)
;
(i
i)‘
ifel
se’stat
ement
i
facondi t
ionistr
uei
twil
l ei
execut fbl
ockofst
atement
sandi
fthecondi
ti
oni
sfal
sei
twi
l
l
executeel
seblockstat
ement.
Syntax f
lowchar
t
sy
ntaxoft
hei
f-el
sest
atement
i
f(condi
ti
on)
st
atement
1;
el
se
st
atement
2;
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence21
(i
ii
)NestedIf….el
sest atement :
I
fconditi
onisinel separ toftheanotherifconditi
oniscal
l
ednestedif
.
Aifstr
uctur
ecanhav eonemor eifst
ructureasapartofstat
ementsandev
enanel
se
partofanif…elsestructureiscal l
ednestedif.
.elsest
ructur
e.
Synt
ax:
if(
conditi
on)
{
Statement s;
--
---
--
}
else
{
i
f( condition)
{
Statementt obedone;
}
else
{
i
f(conditi
on)
{
Statementtobedone;
}
el
se
{
Stat
ement
stobedone;
}
……………….
………………
el
se
{
Stat
ement
stobedone;
}
}
}
(i
v)Theswi t
chSt at
ement:Theswi t
chstatementt est
sthev alueofanexpressi
onina
sequenceandcompar esi
twiththeli
stofi
ntegersorcharacterconstant
s.Whenamatchi
s
found,al
lthestat
ementsassoci
atedwit
hthatconstantareexecuted.
Sy
ntax f
lowchar
t
switch(vari
abl
eorexpr
essi
on)
{
casev al
ue1:
statement
(s)
;
break;
casev al
ue2:
statement
(s)
;
break;
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence22
..
...
...
.
..
...
...
.
casev alueN:
statement(
s);
break;
default:
statement(
s);
}
C++pr ogr am t odet ermineifaletteri
sv owelorconsonant
#incl ude<st dio.h>
#incl ude<coni o. h>
intmai n()
{
charc;
print f("
Ent eraal phabet :"
);
scanf (“d” ,
&c) ;
swi tch( c)
{
case' a':
pri
nt f("
Youent ereda, i
tsav owel")
;
break;
case' e':
pri
nt f("
Youent erede, i
tsav owel"
);
break;
case' i'
:
pri
nt f("
Youent eredi,it
sav owel");
break;
case' o':
pri
nt f("
Youent eredo, i
tsav owel")
;
break;
case' u':
pri
nt f("
Youent eredu, i
tsav owel")
;
break;
def aul t
:
pri
nt f("
Youent eredconsonant "
);
}
get ch();
return0;
}
3.Loopi ngst atement s:Aloopstatemental l
owsust oexecuteastat
ementorgroupof
stat ement smul ti
pletimes
C++pr ogrammi nglanguagepr ovi
dest hef ol
lowi
ngt ypeofloops
1) wh ileloop
2) d owhi le
3) f orl oop
1)whi l
eloop : whil
el oophasonecont rolcondit
ion,andexecutesaslongthecondi
ti
oni
s
true.Thecondi tionoft heloopistestedbef orethebodyoft heloopi
sexecuted;
hencei
tis
cal edanent
l r
y-controlledloop.
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence23
Sy
ntax f
lowchar
t
Whi
le(
condi
ti
on)
st
atement
(s)
;
I
ncr
ement
ati
on;
Ex:
i
nti=1;
whil
e(i<5)
S
{yntax f
lowchar
t
Pri
ntf(“
%d”,i
);
d
i
+o{
+;
}statement(s);
i
ncrement at
ion;
}
whi
le(condi
ti
on)
;
ex:
i
nti=1;
do{
pri
ntf
(“%d”
,i
);
i
++;
}
whil
e(i
<=5);
2)dowhil
e:theloopst
atement
swi
llbeexecut
euntil
thegi
vencondi
ti
onbecomesfal
se.
Ado...
whi
leloopissi
mil
artoawhi
l
el oop,
exceptt
hatado.
..
whil
eloopisguar
ant
eedto
execut
eatleastonet
ime.
3)forloop:
Aforloopisarepet
it
ioncont
rol
str
uct
urewhi
chal
lowsustowr
it
eal
oopt
hati
sexecut
eda
specif
icnumberofti
mes.
Syntax Fl
owchart
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence24
for(i
nit
ial
izat
ionexpr;
testexpr
;updat
e
expr)
{
/
/bodyoft heloop
/
/statements
}
Initi
ali
zationExpr ession:Inthisexpressionwehav etoiniti
ali
zetheloopcount erto
somev alue.forexampl e:
inti=1;
Te stExpressi on:I
nt hisexpressionwehav etot estthecondi ti
on.Ift
hecondi ti
on
ev al
uatest otruethenwewi l
lexecutet hebodyofl oopandgot oupdateexpr essi
on
otherwisewewi l
lexitfrom theforloop.Forexampl e:i<=10;
Up dateExpr ession:Af t
erexecut i
ngl oopbodyt hisexpr essionincr
ement s/decrements
theloopv ar
iablebysomev alue.forexample:i++;
3)Jumpi ngst atement :
Thej ump( break,continue,goto)statementsuncondi t
ionallytr
ansferprogram control
wi t
hinaf unct i
on.Ther eare3t ypesofj umpingst atement s.
goto
break
continue
goto:Thegot ost atementcanbeusedt oj umpfrom onepl acet oanotherplacewi t
hina
function.
Syntax
gotolabel
;
.
......
.
.
......
.
.
......
.
l
abel :
statement
;
.
......
.
br
eak:Thebreakst
atementenabl
esaprogram t
oskipoverpar
toft
hecode.Whenabr eak
st
atementi
sencounter
edinanyloop,
contr
olistr
ansfer
redtot
henextst
atementaf
terthe
l
oop.
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence25
conti
nue:Theconti
nuestatementi
susedi
nsidel
oops.Whenacontinuestat
ementi s
encounter
edinsi
dealoop,contr
olj
umpstothebegi
nningoft
heloopfornextit
erati
on,
ski
ppingtheexecut
ionofstat
ementsi
nsi
dethebodyofloopfort
hecurrenti
ter
ation.
4.Di
ff
erencebet
weenwhi
leanddo…whi
le
Whil
eloop Do.
.whi
l
eloop
1 I
nwhil
eloopcondi
ti
oni
swr
it
tenatt
he I
ndo.
.whi
leloopcondi
ti
oni
swr
it
tenat
t
opoftheloop. t
heendofloop.
2 Inwhil
eloopcondi
ti
onischeckedf
ir
st Indo..
whil
estat
ementi
nthel
oop
andthenstat
ementsint
heloop executesf
ir
standt
hencondi
ti
oni
s
execut
es. checked.
3 Stat
ementint
hewhilel
oopexecut
es Stat
ementi
nthedo.
.whi
l
eexecut
esev
en
basedonthecondi
ti
oneval
uat
ed. foronet
ime.
4 Aft
erthecondi
ti
onorendoft
hel
oop Aft
erthecondit
ionindo.
.whi
l
e
semicol
onisnotrequi
red semicol
onisrequied.
5.Whati
sanar r
ay?Explaintypesofarr
ayswi
thanexample.
Anar
rayisacollectionofdat
aitemsandal
lofthem bel
ongtothesamedat
atype,
havet
hesamest or
agecl assandcanbeaccessedbyacommonname.
Or
Anarrayisacoll
ect i
onofdatait
emswitht
hesamedat atypei
scall
edanArr
ay.
Ar
ray
sar edevi
dedi ntotwotypes
1.Singl
edimensional arr
ay
2.Doubledimensional arr
ay
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence26
Si
ngl
edimensionalar
ray:-
Sy
ntax:
Typear
ray_name[n]
;
Wheretypei
sthedat
atypeofvar
iabl
eformi
ngt
hear
rayandni
sanumberwhi
chspeci
fi
es
thenumberofel
ementst
hatst
oretoget
her.
Ex: i ntn[
5];
Thi
sisanexampl
eofanarrayof5integer
s.Thenameoft
hear
rayi
snandi
tssi
zei
s
10by
teswhichcanbecal
cul
atedbythefol
lowingequat
ion.
Memor
yall
ocat
ioni
s
101 102 103 104 105 106 107 108
109 110
0 1 2 3 4
Int heabov ememor y101t o110ar et hecelladdressesand0, 1,
2,3,4arethesubscr i
pt
number s.
Theel ement soft hear r
aycanber efer r
edusingt hear r
aynameal ongwi ththesubscript
number .Thesubscr i
ptnumbershoul dbespeci f
iedwithinsquar ebrackets.
Arrayi nitial
izati
on:
All el
ement si nanar rayv ari
ablecannotbei nit
iali
zedaut omat i
cwheni ti
sdeclared.Each
elementofanar rayhast obei ni
tializedsepar atelyinthedecl arationstatementofthearray
.
Sy ntax:
Dat at ypear ray_ name={v alue1,value2, ….,
valuen} ;
Exampl e: inta[ 5]={
10,20, 30,40,
50};
Doubl edimensi onal ar r
ay:-
wecanal sodecl arear r
aysasdoubl edimensi onal ar
rays.Eachel ementhav etwo
subscr i
ptnumber s.i.er owandcol umn.Doubl edi mensi onal arr
aysar eusedtosol ve
probl emsofmat rices.
Decl erat i
onofdoubl edi mensional arrays:
Theyar edecl aredsameassi ngledimensi onalar raysbutwi t
htwoi ndi
ces.
Syntax :
Dat atypear r
ayname[ n] [
m] ;
Wher enspeci fiesno. ofrowsandm speci fiesno. ofcolumns.
Ex:
I
nta[ 2][3]
A[
0][
0] A[
0][
1] A[
0][
2]
A[
1][
0] A[
1][
1] A[
1][
2]
I
niti
ali
zati
onoftwodi mensi
onalarr
ays;
-
Twodimensionalar
rayscanbeinit
iali
zedatt
hepointofi
tsdecl
arat
ioni
nthe
fol
lowingmethod.
Syntax:
Datat
ypear
rayname[n]
[m]={
{val
ue1,
v al
ue2,
….,
val
uen},
{val
ue1,
v al
ue2,
….,
val
uen},
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence27
- - -
- - -
}
;
Ex:i
ntA[
2][
3]={
{10,
20,
30}
,{
40,
50,
60}
};
6.Whati sStri
ngandwr it
ethedeclar
ationanditer
ati
onofast ri
ng?
Str
ingsar edefi
nedasanar rayofcharact
ers.Thedif
ferencebetweenachar
act
erar
rayand
astringisthestri
ngist ermi
natedwithaspecialcharacter‘
\0’
.
Declarati
onofstring:
Syntax:charst
r_name[ size]
;
I
ntheabov
esyntaxst
r_nameisanynamegiventothestr
ingv ar
iabl
eandsi zei
susedt
o
def
inet
hel
engt
hofthestri
ng,
i.
ethenumberofchar
act
ersstr
ingswi l
lst
ore.
chargr
eeti
ng[
6]={'
H','
e'
,'
l'
,'
l'
,'
o'
,'
\0'
};
1.char
str
[]="
Hell
o";
2.char
str
[10]="
Hel
l
o";
3.charst
r[
]={
'H'
,
'e'
,
'l
'
,'
l'
,
'o'
,
'\
0'}
;
4.charst
r[
10]={
'H'
,
'e'
,
'l
'
,'
l'
,
'o'
,
'\
0'}
;
Fol
l
owi
ngi
sthememor
ypr
esent
ati
onoft
heabov
edef
inedst
ri
ngi
nC
7.Expl
ainSt
ri
nghandl
ingf
unct
ions?
Str
ing.
hheaderf
il
esuppor
tsal
lthest
ri
ngf
unct
ionsi
nCl
anguage.
St
ri
ng
f
unct
ions Descr
ipt
ion
st
rcat() Concat
enat
esst
r2att
heendofst
r1
st
rncat Appendsapor
ti
onofst
ri
ngt
o
() anot
her
st
rcpy() Copi
esst
r2i
ntost
r1
st
rncpy Copiesgi
vennumberofchar
act
ers
() ofonestr
ingt
oanother
st
rl
en() Gi
vest
hel
engt
hofst
r1
Returns0i
fst
r1issameas
st
rcmp st
r2.Retur
ns<0ifst
rl
<st
r2.Ret
urns
() >0i fst
r1>st
r2
st
rl
wr() Conv
ert
sst
ri
ngt
olower
case
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence28
st
rupr() Conv
ert
sst
ri
ngt
oupper
case
st
rrev() Rev
ersest
hegi
venst
ri
ng
UNI
T-I
II
1.Whati sf unct i
on?Whatar etheadv antagesoff unct ion?Gi veanexampl e?
Funct i
oni sal ogicall
ygr oupedsetofst atementst hatper form aspecifi
ct ask.
EveryCpr ogram hasatl eastonef unctioni .
e.mai n()wher et heexecuti
onoft heprogram
starts.
Theadv ant agesofusi ngf uncti
onsar e:
Av oidr epetiti
onofcodes.
I ncreasespr ogram r eadabili
ty .
Di v i
deacompl expr oblem int osimpl erones.
Reduceschancesofer ror.
Modi f
y i
ngapr ogram becomeseasi erbyusi ngf unction.
2.Wr itet hedi ff
erencebet weencal l byv al
ueandcal lbyr eference?
Cal l
byv alue
Whenaf unct ioniscal l
edbyv alue,acopyofact ual argumenti spassedt othecall
ed
funct ion.Thecopi edar gument soccupysepar atememor ylocationthantheactualargument.
Ifanychangesdonet ot hosev aluesi nsidet hef
unct i
on,itisonlyvisi
bleinsidet
hef unct
ion.
Theirv aluesr emai nunchangedout sideit.
#incl ude<st dio.h>
#incl ude<coni o.h>
voidswap( inta, intb)
{
i
ntt emp;
temp=a;
a=b;
b=t emp;
}
voidmai n()
{
i
nta=100, b=200;
clr
scr ();
swap( a, b);/ /passingv aluet ofunct ion
print f
("\nVal ueofa: %d",a);
print f
("\nVal ueofb: %d",b);
get ch( );
}
Out put
Val ueofa: 200
Val ueofb: 100
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence29
Cal lbyr eference
Inthi smet hodofpassi ngpar ameter
,theaddressofargumentiscopi
edi nsteadofvalue.
Insidet hef unction,theaddr essofargumentisusedt oaccesstheactualargument.Ifany
changesi sdonet othosev aluesinsi
dethefuncti
on,i
tisvisi
blebot
hinsideandout si
det he
funct ion.
#incl ude<st dio.h>
#incl ude<coni o. h>
voidswap( i
nt* a,i
nt*b)
{
i
ntt emp;
temp=* a;
* a=* b;
* b=t emp;
}
voidmai n()
{
i
nta=100, b=200;
clrscr ();
swap( &a, &b);/ /passi
ngv aluetof
uncti
on
pr i
nt f
( "\
nVal ueofa: %d",
a) ;
pr i
nt f
( "\
nVal ueofb: %d",b);
get ch( );
}
Out put
Val ueofa: 200
Val ueofb: 100
4.Whatisi
nli
nefuncti
on?
.
Inli
neFuncti
onarethosefunct
ionwhosedef i
nit
ionsar
esmal landbesubst
it
utedatthe
pl
acewhereitsf
unctioncal
lishappened.Funct
ionsubsti
tut
ionistot
all
ycompil
erchoice.
Let’
stakebel
owexampl e:
#i
ncl
ude<st
dio.
h>
/
/Inli
nef unct
ioni
nC
i
nli
neintf
oo()
{
r
eturn2;
}
/
/Driv
ercode
i
ntmai
n()
{
i
ntr
et;
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence30
/
/inl
i
nefunct
ioncal
l
r
et=foo(
);
pri
ntf(
"Out
puti
s:%d\
n",
ret
);
ret
urn0;
}
5.WhatisRecur
sion?Wri
teaprogr
am tofindfactori
alofagivennumberusingrecur
sion?
Theprocessi
nwhi chaf
unct
ioncal
lsi
tselfdir
ectlyorindi
rect
lyi
scal
ledrecursi
onandt he
corr
espondi
ngfuncti
oni
scall
edasrecursivefuncti
on.
Example:
Recursivefunctionagai
nt wotypes.
a.Li nearrecursi
on:
-ifafuncti
oniscal
l
edi
tsel
fonl
yoncet
hansuchf
unct
ionsar
esai
d
tobel i
near.
Ex:
-
Voidmai n()
{
A();
}
VoidA( )
{
A();
}
b.Non-l
inearrecur
sion:
- ifafunct
ioni
scal
l
edi
tsel
fmor
ethanonet
imesuch
funct
ionsaresaidtobenon-l
i
near.
Ex;
-
Voidmain()
{
A()
;
}
VoidA()
{
A()
;
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence31
A(
);
}
pr
ogr
am t
ofi
ndf
act
ori
alofagi
vennumberusi
ngr
ecur
sion
#i
ncl
ude<st
dio.
h>
i
ntf
act
ori
al(
int
);
i
ntmain()
{
i
ntnum;
i
ntresul
t;
printf(
"Enteranumbert ofi
ndit'
sFactori
al:"
);
scanf (
"%d" ,
&num) ;
i
f(num<0)
{
printf(
"Factori
alofnegat i
venumbernotpossi bl
e\n"
);
}
else
{
result=factori
al(num);
printf(
"TheFact ori
alof%di s%d.\n"
,num,result
);
}
return0;
}
i
ntf actori
al(i
ntnum)
{
i
f(num==0| |
num==1)
{
return1;
}
else
{
return(num*f actori
al(
num- 1)
);
}
}
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence32
q=50;
pt
r=&q;
UNIT-
IV
STRUCTURES
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence33
r
etur
n0;
r
etur
n0;
}
}
OUTPUT
OUTPUT
Thesi
zeofPer
sonUni
on=50
Thesi
zeofEmpl
oyeeSt
ruct
ure=80
3.Whati
sEnumer
ati
oni
nc?
Expl
ain.
Enumerat
ionisauserdefineddatatypei
nCl anguage.I
tisusedt oassi
gnnamest ot
he
i
ntegr
alconst
antswhichmakeapr ogr
am easyt
or eadandmaint
ain.Thekeywor
d“enum”i
s
usedtodecl
areanenumeration.
Her
eist
hesy
ntaxofenum i
nCl
anguage,
Sy
ntax:
enumenum_
name{
const
1,const
2,.
..
..
..}
;
Theenum keywordi
salsousedtodefi
nethevar
iabl
esofenum t
ype.Ther
ear
etwoway
sto
def
inethevar
iabl
esofenum t
ypeasfol
lows.
enum week{
sunday
,monday
,tuesday
,wednesday
,thur
sday
,fr
iday
,sat
urday
};
enum weekday;
Her
eisanexampl
eofenum i
nCl
anguage,
Exampl
e
#i
ncl
ude<st
dio.
h>
enum week{
Mon=10,
Tue,
Wed,
Thur
,Fr
i=10,
Sat
=16,
Sun}
;
enum day
{Mond,
Tues,
Wedn,
Thur
s,Fr
id=18,
Sat
u=11,
Sund}
;
i
ntmai
n()
{
pr
intf
("Theval
ueofenum week:
%d\t%d\t%d\
t%d\t
%d\t%d\
t%d\n\n"
,Mon,
Tue,
Wed,
Thur
,Fr
i,
Sat
,Sun)
;
pr
intf
("Thedefaul
tval
ueofenum day
:
%d\t%d\t%d\t
%d\ t
%d\t
%d\t
%d",Mond,
Tues,
Wedn,
Thur
s,Fr
id,
Sat
u,Sund)
;
r
etur
n0;
Out
put
Theval
ueofenum week:10111213101617
Thedef
aul
tvalueofenum day:0123181112
4.
Whati
sfi
lehandl
ing?
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence34
Fi
lehandl
ingi
nCenablesustocreat
e,updat
e,read,
anddeletet
hefi
lesstor
edont
helocal
fi
l
esystem t
hroughourCpr
ogram.Thefoll
owingoperat
ionscanbeperf
ormedonafi
l
e.
o Cr
eat
ionoft
henewf
il
e
o Openi
nganexi
sti
ngf
il
e
o Readi
ngf
rom t
hef
il
e
o Wr
it
ingt
othef
il
e
o Deleti
ngthef i
l
e
5.
Whatar etheFunctionsforfi
lehandli
ng?*
**
Therearemanyf uncti
onsintheClibr
arytoopen,
read,
wri
te,
sear
chandcl
oset
hef
il
e.Al
i
st
offi
l
ef unct
ionsaregivenbelow:
No. Funct
ion Descr
ipt
ion
1 f
open(
) opensneworexi
sti
ngf
il
e
2 f
pri
ntf
() wr
it
edat
aint
othef
il
e
3 f
scanf
() r
eadsdat
afr
om t
hef
il
e
4 f
put
c() wr
it
esachar
act
eri
ntot
hef
il
e
5 f
get
c() r
eadsachar
act
erf
rom f
il
e
6 f
close(
) cl
osest
hef
il
e
7 f
seek(
) set
sthef
il
epoi
ntert
ogi
ven
posi
ti
on
8 f
put
w() wr
it
esani
ntegert
ofi
l
e
9 f
get
w() r
eadsani
ntegerf
rom f
il
e
10 f
tel
l
() r
etur
nscur
rentposi
ti
on
11 r
ewi
nd(
) set
sthef
il
epoi
ntert
othe
begi
nni
ngoft
hef
il
e
Openi
ngFil
e:f
open()
Wemustopenaf i
lebefor
eitcanberead,wr
it
e,orupdat
e.Thef
open(
)funct
ioni
susedt
o
openafi
l
e.Thesyntaxofthefopen(
)isgi
venbel
ow.
1.FI
LE*fopen(constchar*fi
l
ename,
constchar*mode)
;
Thef
open()funct
ionaccept
stwoparamet
ers:
o Thef
il
ename(
str
ing)
.Ift
hef
il
eisst
oredatsomespeci
fi
clocat
ion,
thenwemust
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence35
ment
iont
hepat
hatwhi
cht
hef
il
eisst
ored.Forexampl
e,af
il
enamecanbe
l
i
ke"
c:/
/some_
fol
der
/some_
fil
e.ext
".
o Th emodei nwhi chthefi
leistobeopened.Iti
sast r
ing.
Wecanuseoneoft hefoll
owingmodesi nthefopen(
)functi
on.
Closi
ngFile:f
close()
Thef cl
ose()f
unctionisusedtocloseafil
e.Thef i
l
emustbecl osedaf
terper
for
mingal
lthe
operati
onsoni t
.Thesy ntaxoffcl
ose()f
uncti
onisgivenbelow:
Openi
ngFi
l
e:f
open(
)
Wemustopenafi
lebefor
eitcanberead,wr
it
e,orupdat
e.Thef
open(
)funct
ioni
susedt
o
openaf
il
e.Thesy
ntaxofthefopen(
)isgi
venbel
ow.
1.FI
LE*
fopen(constchar*f
il
ename,
constchar*mode)
;
Thef
open(
)funct
ionaccept
stwopar
amet
ers:
o Thef
il
ename(
str
ing)
.Ift
hef
il
eisst
oredatsomespeci
fi
clocat
ion,
thenwemust
ment
iont
hepat
hatwhi
cht
hef
il
eisst
ored.Forexampl
e,af
il
enamecanbe
l
i
ke"
c:/
/some_
fol
der
/some_
fil
e.ext
".
o Themodei
nwhi
cht
hef
il
eist
obeopened.I
tisast
ri
ng.
Wecanuseoneoft
hef
oll
owi
ngmodesi
nthef
open(
)funct
ion.
Mode Descr
ipt
ion
r opensat
extf
il
einr
eadmode
w opensat
extf
il
einwr
it
emode
a opensat
extf
il
einappendmode
r
+ opensat
extf
il
einr
eadandwr
it
emode
w+ opensat
extf
il
einr
eadandwr
it
emode
Cl
osi
ngFi
l
e:f
close(
)
Thefcl
ose(
)functi
onisusedt
ocloseafil
e.Thef
il
emustbecl
osedaf
terper
for
mingal
lthe
oper
ati
onsonit.Thesynt
axoffcl
ose(
)functi
oni
sgiv
enbel
ow:
1.i
ntf
close(FI
LE*
fp)
;
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence36
Wr
it
ingFi
l
e:f
pri
ntf
()f
unct
ion
Thefpr
int
f()f
unct
ioni
susedt
owr
it
esetofchar
act
ersi
ntof
il
e.I
tsendsf
ormat
tedout
putt
o
astr
eam.
Sy
ntax:
1.i
ntf
pri
ntf
(FI
LE*
str
eam,
constchar*
for
mat[
,ar
gument
,..
.]
)
Readi
ngFi
l
e:f
scanf
()f
unct
ion
Thef
scanf(
)funct
ionisusedt
or eadsetofchar
act
ersf
rom f
il
e.I
treadsawor
dfr
om t
hef
il
e
andr
etur
nsEOFatt heendoffi
le.
Sy
ntax:
1.i
ntf
scanf
(FI
LE*
str
eam,
constchar*
for
mat[
,ar
gument
,..
.]
)
NEW SCI
ENCEDEGREECOLLEGE Dept
.OfComput
erSci
ence37