0 ratings 0% found this document useful (0 votes) 23 views 49 pages Programming in C
The document discusses the concept of functions in programming, including their declaration, parameters, and usage. It explains how functions improve code reliability, facilitate debugging, and allow for code reuse. Additionally, it covers various types of functions, including mathematical and string functions, and the advantages of using recursion in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Carousel Previous Carousel Next
Save Programming in C For Later Twreopuction Jo Fonerions -_
Bastaking up a page ‘unt degmatls, Oren
(renonka known ab spondumit » eath, fuenchuenie can be sysullin
More ox Jus indupendant 5 each oft.
ae yandie dn Whe pager: is Aupposed. to
“pedgem Gul dapined task.
Need |usoge of Gundioie inc
) To Ampoiove dhe renclabiliiy eee
») \mporoves Bu ruanrab iy pe code , Aome 4undien can
led i akan tod
be aud an any progtam thstiad oy senrabing the
again and again . | _
5 Debugging is cou Be a ee
A) Reduces the Atze the wd, ar cuiphicle
aeks ee ruplatedl Py aaa
2) Fundions makes coy snbousing
i
/— lop
Eaton Potlype Declantion
-A Funélin cicanatins Jat the comple about &
pendin Name and nue ee ob poxamétin thak the
Pndion exped’ ta seeese and the dota type of, the. value.
Yak ib will sedtinn te Hee cally mn
ailing dandien
> Funcktsi Declenatio’n has Wee follauing penis
‘alan pe es nona pment)
7 eg: ink erin (iab-a, int Ws de a Valid fin cleclonation
Of, mrko fenton auth 2 poramidtues 4 ink datalype.s
his dn uilb ative va - Inbege, value Ob Herubl
$ geen Fecal
> Since poxomilue Nami ase nok srlpotak?
> The obove example Can also be ayrutlin, Ob
int min Cinks ink) 5
ushich is alto @ valid fori call.
> Poxomatvy art ophonal , dune mex contain No
, Ponamdtr.“Thue Format 9} Funds Def rition to cfs
i noni Radia tnate Cate)
\ Bolg oy the dundion
3
= "Ra Type The ho is the dalalype oy ine vale
sulioned by the fandicn
“2, the duntn pygms ie dined, peace
uusdhouk yutieuing avalue-
= Then the section type ts void
| Fandin Name: Is Hie Name of the Junction sused. fo call
the dunctioh in he pregtion:
| > Poamelins 2 When a. fis called , you. pass value fe’
the poramelur
= Pasian ist sales fo tape ef data, Ordest
and no % onguments
— Poramelisrs are ophénal .
7 Fur Body. = Contains colledticn of staiments that dekine
LL hat the fr doesTopic A _Fancuin Catt
> To wea fantom , ase raw, te cat the function bo
Pog he dg ae
> When a progam cals &. undo’ 4 the poner conbul Is
Fransfooud > tre called qundisn
=> Ona the exeutor Of ae feuncin Le completes the
endian rulivcns the Peter toriiol and tha 2asalk ef
Kho ps cad.
7 To call the syndion i aas ign the seagpiveeal poramantere
ur 23,
- yesulk = aunts
ahk man (unk numt, tak num 2)
pusulk = wM25
|
| Max value iS :Q00Tories: Bont.
An Functions
\Noesx OF Function .
> WS = Comptia He toni of Ie angeonart
7 ep = Compal he e versed be qe pow
> Jo9, z Computes nabinial, Angasdtinm
> log fn = Computis Jegessithn bf ave ong to
> pow - Compu Ye ramber mal ON
> Sin 5 Computes Aerio oy the anguimant
> oor 2 Computes Squcre Soot a the ongiamarh
= tone ~ Compas tangent aa
a dante 7 femme ape Feat
a the oe
> cbt - Cormpubes ube Toot of the
a
and So On.eler wt Any
_STRing Fone 9.
> ShreakO
> SkrncakO
? Sshepy Oo
> strln O
> Shremp oO
Sy Skrobru
> skrluy 6 0)
> se pr 6
> Bly 0)
7 Blrdup C>
and So on
Strin _ Fun cmon
_ Coneatunatas Shr2 oF Whe end op shel
Pppendt oo porten a4 ang bo anolhuc
= Copies qn number opschiamal
of one anal
- que the. Lunath eae
~ Ratusins 0 “Shr is Aare af sha.
Rekwurs 40, 4, ght Sho
= Rekwuns pointer to joisk occurance bs
Chan an St!
: Conveds eve douseceare
- Cornea! viuegle pra
E Duplicates the sure.
a
G
7Ca LevLATOR Usirer ao
IN _Foeton's_
indudt <$kdio hy
AE undue Lemus hy
AR and Amoth-h >
Void mainy
7
Fook 9, 0,4) b,¢,+, mule, Aumzo, gik, sub, div, h,
‘Ant
5 SUA, num 5
Vid,e, bei, Z mums, x
= 1 NLP
Chor Ks
tong int grat, Ziat3
double. result ;
Fi dn.
Choc 0) 5
: “prtatd ti iy Reape ony ena. fe do” operidhers \q
Vyade \n 2ysub \n-8)mul \n 4)
PEC\n enbor operation no \n")s -
Acany (* vd" 2 a’) ;
Swikh(d)t
Cope):
PA Century Ine nos you swank bo add \n");
atts yl", Ded;
PE Cents the non";
de Cicosine sit)
4
Any $" 24) 5
Aum = Aum +f 5
Print] (* The tum 1s 7£\n", Aum;
bowak s
Cone 2:
Pf CSentin two nos you want fo Sub \0"95
MON 1 ey 24. 2h)
Sub = ach;
PEC taf = xg \o's gh, Subd;
brook 5 ;
Ort 3 2 Pe-Cn Oe ne nes you wank bo vmaditply\ nt) s~ ee
sh (8 yd" 9e)5
PE(* enlen the No\n” ys
for (isl;ixces jot)
4 seanp C87.” , 24)
4 aa. mul+t 5
TePEUY tee muadple ia 76 10", meal ci
bneade 5
Cone A:
PEC’ enturttos ne apt taank fe divide. \n") 5
PLCs RAM,
2q.2h);
div = g/hs
PICS Rey p = 7£ \n"5 g,h,dio 3
bran 5,
Caye 5:
PEC" enkr the value
ALCOES aehs
v= (314/190) #05
P= Sin (ws
b= wsCy>5
C= fants); -
P+ C "the. Value a Sin (rf): %£ \n" 3% P)5
PEC the Nobu of cos CU-#)# Zf \n5, xb) 5
Pt CO" The vahue + tan Cy. fy. 1H\A" as Js
CEES Be U8 Eatin Hae no
Sky", af),
TOs = Sort (8) 5 Ts 7
Pet £* $2 aot ef ne Is ZA\O") nes);
brecte ,
eb ae Lue
aoe swank by find % wotjn”);eo
Cored:
Cane 4 +
Cane Ht
PEC enkor Ine Volue\n">s 13
“bc “yf . Zhu);
yosulk = acos (rum);
PEC" tn wadlan dnvouse of Cosel 70.26) = o2txt\o’y num,
Sesule)>
Terabe = Cush’ 1 eo) (3-14 5
PEC In he Inverse aeosl 7.0.2f)20-af Jot naz, rwoull)s
breaks
PEC’ enter Hhe value \n");
“A ( 24", Drums;
Mwaulk = asin (num; ;
PE (™ Racin Inveux ay sin (wont) =% o.2f.\ntyfuum ,reaute);
srosulk = (seesutk 180) /3-14 5
PE - Degnee [Voy of stn Coa) = Zo-ait \n’, run,
Seeauthd;
bxwak ;
3
Prints Credle the volun \n")3
ACHE, Drum
susuk 2a lan (rem),
PEO Radian aniowe ©] tan(i 0-24) [0.21f\n", rum, desis
sepulk=(vesulk #1eo) /314. 5
pt" Degree tinvoue Fan C7.0.0f) Enttn Ihe nas sou wwant to i
3 a “rt
Ent Ine no
4S
3
4
The muphi ple 1s 540.000000
AL sysa swank be do mow cpa ypetal
a
~~ Eaton Operalten ne
Enier the value
1
Ractan Inve & tos (1-00) 2 0.210. 00000 0
Degree Invere “4 Cog Cl-08) = Makar arene eat
a6
| /Topics. Paeomever fhssimen
7s"
= When the exeuition Coibut Js Framed yom (aling
“potion Je called durelisn at Pied coe oY
mmc Wot valuer - These deta Values ve called
poramatist
) Adust _ 2.
Actuot’ Pararastow + ;
Actuol fer cou. Die poromitos that | one
Afeayil in calling pinion: ja inside ™
ie main ¢>
“qhe orral poramuctun au the panamabixathat
ont datloud ok tre Called undhish -TJas_Nestods_to Fant porornetre
> Then cou Suse ralhod te pass ponamelcrs wer
Calan yndtisn to cated yn
1) Call by Vole ov Paws by Vole
& callby Reypunce °F Poss by Paource .
Cath by. Volut £
> In car by Volud pancsnetn powsng.. mained » the copy
4, adtiol. panarneten. Vabius Oe top to formal
ponarnalinh ond there formal, poneunehvs ‘aru. wxcol
wn clad fen |
= The Changs made tn vhe ferma panamelisu: ees
nok apygek the ae of adtnol ponometin ”— in, Ain ue extuticn Conlsol tomes back bo the
36
calling funitsn the ariel posamelr Value ramains
Aarmk -
Heandide < o}dio-h7
fF indudadumto-h7
Voicl main 0)
4 =
ia Cum aun 7 Aveaaspaorel
—> Void Awop Cnt in V3 Sy daclanation
chiserta; —
Num | =195 |
Num2 = 155
purl Yn Bolero
Jyusap (run, eum 295 I fir cabling ”
pune yn Ayla, Awap ¢ nwt exd\n nun2=%d 5am),
nana 2)'5
2
num <7. ANo , hum2=7 dl’
* pum, oum>)5
O> |
void swap [1h a pink) / caltacl En
ah kemp 5 {
<4; | 28 ‘
debs i Bype Pade num l= 10s
4 pe benps | fum2 =15
Mba dmuapping num > 10 5 |
“num2 =t5 5Call Rerehin Addous +
= DH Lajouner] for [
= \n call ba zane > Adiual topy fe memory ‘ocalion
is passed to the called fynctuin
> Ths, Sagenel ponamation gets apgeecl Ap Vodaate of Ihe
Poramitus 0 calud a cs Changec|
& me Sup turn nus
te andd bdan ho $
s : =o, Au 2
aE unclucke Zuo: hy Aiton Swap: num! i
Voicl main (>
Noid panop (ante, tnt J Pn duclonation
|
Ink num Meu 2 5 . |
|
|
|
|
Obes rd 5
num’ = 05
Mn 2 = =205
prank, (*\n Byer swap mn num 2 =e 5 nem 1, numa)
: AWOp (Era, Drums J catlurg fn
Prot (thn Agta Awarp: rami red jrum 2 ol" cums, name)
4 rs
soi Aap Cink 4a, rir xb) “H coded fn
° i)
Ot 2002
oOEE ESS 17
Rewwei CAWON =
A “fonction that calls bse i Known a6 &
Tew usion fnctien . The fichiigue Sun Knourn swutsion «
does Rewvu. tor Work |
2 The neuen conkinuiat antl ome tmditicn . is mot
| 7 pi L | oe lone
> Bp pve angi 72 SJadusien . Condilisn al Abitimants
Nee ipcdsc ov Amilo appreach Can he. suyeck
ushew one \yranch mallad Ihe eunrsuic call
and olnen doesn't.nl a 1¥2%SxH ED
=F indude Skdio- hy
: a Bx2X1
ne tod: Uink os a ae ‘
Ynt main
i
ink 3
prim” Enlor o positive number "05 = 5
ACONLC™ yd", BN) 5 apes
Put (* Fadosual op rd= Ld’, wv, Lack lo); = fats)
eae ee
4 3 fr call
ink tack Cink nd => fou(s) naw a
ap tn 7 =D > 4 (s7=0 [
. lun nw gock (n- 5 yok 5% face CHD
: eae. : hue
j sulin 15 coll
. oo | 4 hysl-T
r a —— yuk & 4 ve gare (2)
jp QureT, . ay Bra T
| Enix a positiine Aumbe: 5 : mb 3% fore)
_ . : ai azar. T
Fa chow at Bf S=120 eee Cyacked
jo = Rewuion Reduces coda
7 Con Aolve prablims _ eons voy wohile ks
akoiatine Avtdion Je Voy Big ond tomple
~> \pcearsa the seadabili hee
2 Helps an tode reuaarbilily
—Disodvaninget
1 > Rewwwien uses move Mamerg:
> In suuisein 3 stalumnent: o Amare inal Alaliment
jb must to ovoid. Re
|, Rein ys more puso # fine
Ramer Aes in amis aan
cya 0 aundows tand and bendSiwe Series:
Sto OD = 9-7" / 3) + 2° oa
mes a as
7
> > Au Ye Shabiometa Jn clo pant sitll exeaidt etleast
onde
> The Stalimants ip olopank aud exauile for the And kore
Ushen the tonditien in The while | sep Wy Tue.
and umbinws unfull the ’ Condittan failsAF indludec stcio he
indlucle conto: hy
+E induce 4 malkh >
AF apne PL 3142.
INE arn C)
4
ink is degree 5
ploak x, Aum=o, hewn , nume denos
chiser 05 os :
prt “Enter the Vola of clagreet »%
Acar (r7-d", 2 degres ds
4
ao
x = degree # CPi/\go) 3x To Lonvoct dagaat to Raduans
Tume = % 5
Gores ton He
deno = '5 1)
Teas
do
ent
foun = nuns 05
nuume = = pure F9E% % §
dno = deno #) * C495
et
pum = Sum + foun; NY ;
+148 ' guch 69;
J ushile (Jabs Clown’) 7= 0: oose!); | 4
J]
Pung (“the sue yy “dis Bed
Prunts (8 the sude tuncin m2 A.1S Latin", dnaners Str dls
—Entin the Value
a
The Sue & Be is
30
0-500
The Aue fundzan 8 30 ona. Jibrreny 15 Q.5002 ponreRs: ( Barebone of ©~Prigramon'y )
— pointer
ancther Vvartable +
— Since pointer Uo alse a lend of Vari
ftsel will
a a
be Stored at dagperent emery OTS
Bons
Ca Variable which stores the address of
able, thus peinber
location:
- Ts Variables:
ypes of ;
4 ’ '
> = le Variable that stores a Valea such as 10 ery
\ on rs
pleats character *
f
address © simple
ui) Complexe Variable’ that stores
,
Variable Gj} pointer Vartables
— —
Exompk “
rk maint)
{ ink a=3; y Sople Variable - oa
int «ply; // pointer Variable oe os
cpbre BAP i es \yo*
ne coe Variable b’
by
@ Name of Veria ble a P
L helds . integer elresef sndegor
+ Type of yolde thal
Value stored
3
Hed (Assen
Variable oy
0 Address of
fed Cees
pep Asses
ValeBxcmple >:
jnt matnt)
ft
ink a=3;
ink xplr, xxppyr;
prueba)
pps = Apter;
rehon 0;
+
Reference Uagram for the above program:
renee Atagram for fhe abe py
Variable Sa!
us” pla
yoo KA
PRE
pt re
Variable ‘pty’
Bob
o Name of Variable a ply
e Type of Value U- holds Integer Address of. | Ald ress of ‘ply
0 | Valu: stored 3 packp sadf
| 4 | Address of Variable | oaclt- sed nd3.9%
e Bewerirs ( MERITS) OF POINTERS INC?
Cg Sg
. \ a
— Pointer provide \liveck access bo memor
- Se
Pelnters provide a way bo return more than Orc Value
bo the functions -
i a ‘
~ Reduces the storage space anol Complenity of the
Praram .
\ ’
Reduces the enecebren hima of the program.
ic a
acess arre elem enty
Provieles an allirnabe wag bo”
— peinkers can be used be pass Informabion back and
: pone lee
forth between the calling fun ebron and ‘called function *
\
. poraters allows us be perform elynamse memo yy
:
dllocablon and deallocabien’,
- pointers helps us te build tomplse date strcbres
tee Unwed Lak , Stace, Queutt; trees, graphs ae
— Pointers allow us te resize the dynamically
allocated. memory block :
—_ 7
\ -
Reld ressos of oblecks can be extrnceted using pointers
DPEYERITS OF POINTERS 2
Uniniblabzed pointers might cause Segmentation foudk
Dynamically pre ea is be pred _cnp Weibly,
Olkerwise Ub Woulel lead te memory leat :
Pointers ave Slower Han ‘normal Vartables”pee
Lp. poinkers are updabecl with Intcorrect Values,
iplion +
might lead fn memory SOUP EN
gram
pprenlt f° debug + Pls Peg
Pointer bugs are
7
1
Ely »
bars efifectively’and. correce] *
nas ponsi bility fo use pointers ‘effectively ly
——
° PoINTER OPERATOR IN CP
Operator Operator Name | Parpose
¢
x Value at Operator / Gyive Walee bbored.
Incdérectron Op, ab particular acdre i
Adldress Operator Give adelress of
Variable.
— fn order & create pointer loa Variable. we use”
Operator anel be prircl the acld ress of Vari hfe
ee
operator
&
be neces ee)
Example: iat poe
meine) wt n;
sh
f . u
Printé( Acldrese of nb ZX , an);
print fl" Value off & pA" nd;
prit £0” Value of n & yal * UE);
f int nese,
Peldrees of nts PP tiday
Value of A 20
Vode of-n a$29
How C49) 4 Same ax prinking the Value
apn?
In [Gives address of the memory location whose
wD
name uF ns
Means Value ot Oe gives value ab
address spe cipied by Spr?
mefn Aclel ress of nis gtored tam, ‘but remem ber that
m unot ordinarg Variable Leke ‘nt
Step by Sep calculation bo compute the Value
n
me xl Fn) [ec]
ew ( Addr: of Variable ‘n’ ) Hp 7b ay
2% C fpetlat= Vea Ieee ct
[mere idves penis
DECLARING POINTER VARriABlee?
ee
ede Datatype * Variablecname
Ce) ee
iy) Chay eh] . '
Vi) fleak *F) :3.30
i) ‘phics declared as that per’ ewill be used. only
fer s boring the aclelress of the intege y Valued. Vartables .
WS we can also say that plr’ points bo integer.
Wr) Value at the aeldrers contacnecl tn ‘ply’ a Inbejer .
' ptr
ia 8930 44 5 arbege
b55bahec bssbaqee. Value &.
After ascigning the address off Vartable t potnker
' br :
=> = bssbayccd Ald ress ©
ae Variable i’
essbayece bssbayce a
@ POINTER INITIALIZATION:
ee €
Syntax tn
pointer Variable = 2
“4; | ink az lo;
Ink xptr;
bye Rar | // potter Inctializabion
7 P'afel
MENT ORY REQUIRED To (TORE POINTER VARIABLE!
\
jy) Variable may be Vabeger/ character » Pent” but the
address ef the Vartable & afways fabeger £0 potater
ee a sity beger
requires 2 by bes of memory In TE lompiler
WW) Lf yet dun the fame preg
then the putpuk May ole fper a}
' ai pfere complet)
I y other DoF
ram in any
C requirement a
olepperert fer
Void mein O
:
int ipl;
char xeper;
sfleak app hy
rinkf (" Gixeoft Fak porary * fd bytes’) Hip)
prink fC" Size of char poinker tof. bates", ire! pedi
printf (" Sree of fleak jd by bes 4% cfer”,
poinker.:
Ber lend o/e++
Sircofp Inter abytes
brvcef pel tye
qurboe {ert
eee
pdhy te
Siac of Eateger!
Brreof pointer: Phy te
Visual Ce
dial
Sreop Taba? thytes
Sircert pointer: by bes332
; e DEREFERENCING Pointrice + A
4 ee Cys Pera erénciing fperater)
= Oe referencing Operations performed tb aterss or
Soames
manipulate lata tontained. in memory location pointed é
by a pointer.
ee Oa see reperented frint
dleveck ecks bhe Veluwe” of Vera ble. Ub points te
Example
mata ¢) OO
mide Value at C ptr) |
= Valuer ak Cie
Int nzco, «Pp bros
Plre Pa3 * pty) = 50
X= aplry;
n
50
Hea
B POINTER ARITHMETIC 3—
— You can Perform arithmeb'e operations once porntey
just as you Can ona numerte Value .
— There are fear cotthmeb'e Operators that can be
ee ree eee
used on poinkers Dott aay Ft and —) Incrementing
because we
the contents of
Lacremee
of the
Tnerementing pointer
have tonbiguons
Pointer:
“ ° . i. ?
a“ generally used fa array
memory in array and we lenew
location -
Var'able depends open datnly?e,
nrexeb memory
blag pointer
pointer Variable -
°
Rules used te facre
meak pein ker
Aedldlress ¢4 = Address
Arddvess pp = Prddress
pi fddvess 2 Addvess
0 Pickoxial representation:
a
ws
tooo
0:
per
ete i ]
Lnerernea bing loon
LOS$-
Data type old Address choredl in poloter Next acolrecs £ tored
p : ELS In
Pir) | Pointer after incrementing
int toco eft
float tooo pee
thar. tooo poate
Joo |
}
aayExample: 33g
Voie macn 5
Int vartges ft 0, too, 200};
ink *, xp;
plrs Var; L base cderess of ver (vartoy) & weg
ferlico pi<3y T+)
t printh¢ " Address of Val] d Te 7. x "' per); id
Prroe P CO" Vatue of VerEAdy = 7d" iy xpbr) 5
pertt; W per= ptrtt (move to the next
3 lecatron )
Ovrpur i
Atel ress of Varlol = 4haataga
Value of Varo] =
Adewecs of Var Days 4baasse
Vale of Vara] = loo
Address of var[a]= pbansgs
Value of Yarpsy < 200
00
cae vost J -L we
L thbe
wh peu
por-A var,
F pov =
[96 > Vase;
folio; 1 <2 44
Oa SD
© preg (Adder 7x", per ))
priv BL 3 tp
peony. eNTIN
wi) pecremen ING
The 5
pointe? t
of rts
Euomph!
vo
A PoInTeR?
dataty Pe
tel maint)
Ce ee
jot $, *phT5
pire Rvar [29 j
, teen!
for ( Ee
print fC " dd ves:
printf
pir-7
C Value
oie fe Help revi lo
Bes ede
ame consiclerabions apply
hick decreases its value My te nee BS
ce) £0 od
too, 20°F 7
--)
pop Vanesa dee” idchl
of perl deen
cat 100}
D
Oy
bd;Reference Ding para
i per 7
El After Ee
(eco joa |
loco LOSE Foeremeabing [ete
Datatype Ole Acldrecs stored Net Address tterel In
in pointer (ptr) pointer afer dacremesting
7 Cptr--)
Int tooo 099g
float leoo oath €
Char tooo 0994
pip Adding labeger vale with porn bar? —
: ee
_te pointer Variable
we tan add rabeger nuraber
ned plepectly legal “ha © programming -
Formule to taleulate he eolclress :
fnafioaladeeets. 5 C present address) #0
Size 0
In beger Veileo *
f clatatype of the
pointer’)sor
Bram ple t)
tnt aplrs Clok x) loco 5
pre plr43
ce
plr= ply + 3 #C Sizeof (int?)
looo + 3% (2)
= looo +b
Per = Took ~prent oddone
Ga e e
soda)
Example. (¥) i
ord moun?
char xpBr= Lehar at) 100° 5 Eee pee Lik “ire
phr= pert ent
poh
P
prs piess aC aoupeaeny) 3
s ivvo +2, * O) :
= ooo #2
lar | ik ma © syed
ae ° ;
Example tid ae :
TP pileot apere Cloak +) 1000 5 . +e “e
pere pir t! " =
=f pty
0
pert (siseapl Peat)
= tooo +! * (4)3-39
WN) Sublrcieting the tokeger yalue wi'th pein
ST ee ee
[ plr = initieladdress —n 4 Ctieeof (datatype) | :
Void: macn () é
fot xptr= Cint *) \oo0 ;
plr= ptr~ 3;
prinkPC " New Velour of pPlricfu u I phe) ,
j é
Output : Pir= 1000-3 Ser
New Value of ply: 99y = looo — 3 (a1).
2 looo— &
= 44
Pointer — Poinker = Loteger
(pe Dobeger = Poiaker
;
DIFFERENCE BETWEEN Two POINTER Vegi qgces:
) Diff erencing means Suh broc ting heo pointe re
n) Sublracting gives the bola) ne vof. Objects behueen them «
TW) fublraction Indicates ‘How apart the hoo polnbers
Qe are * 2
potty Q _
oF ho
Seewe TRUELY
= ie XN? 3.39 4 par PHD
Program: PO ey eee 1PMIET a
ae Pansy UF pa
T vold mating ant
q evrper
~* nt num, xpert, wpbray a
peri = tnum;
pers peri +2 7 Pee
5 ip jm, OP
print ft C hd 7 phra~pbri dy : a ans
3 “pt _— al :
Suppese the Address of Varta ble, nurr =/p00 ~
i en a
Ska bement Value off pert Value of per>
cae num, epbry eplr a] Garbage Garba ge
pert sdnum j fee Garbage
Prac pir +37 looo foo4.
ptrs-ptr! 5 tooo loos.
. Cnt vols) 5
e Compu babion of (ptra- ptr 4): ie phe, ¥ pou;
mee (pty ery
Perraule: . | pod 2 KOH,
fioal. Values. Cperacptr)). | sizeof Colabestry ped ib peu <= pois]
. x
ae
3) phenaphry = Value of pir> —
= l00 4% — loo
Value of perl
5) Computing Pesta) CAetoal) DIFF
Final Value = Cpbr2-pe1) J Sr of (Fa)
= 4/2
eh340
Sp tow pointers are following Mamerica) ie 7
Datu Type ; Diiggersnce tf
Lnkeger a J
Pleat 4 !
tharecher 1 t
@ Arrays anc Pointers:
’
~ Arrays are closely related te pointers in & programming
but the important diffperence belween them és ‘that; a pointe.”
1
Varrable Lakes different addresses’ a8 Yalus Whereas -in ea
of arrey te & freed.
char charArrl4J j
jak}
fer iz0; ey sittd
1 ;
printel” Address of char AreC/d] = oxy jy RCharbrrt
3
3
oer Address of charAn lol = 289A 44
Address of char C19 = ep EES
Address of thar AreL2jy = eff t6
Address of CharArr C33 = 2ett YFcae
Pointer Arithmetic e o7
If you want to have complete knowledge of pointers, pointer arithmetic is very important
Hoe ya tdl in this topic we will study how the memory addresses ‘change when you!
increment a pointer.
16 bit Machine
Ina 16 bit machine, size of all types of pointer, be it
always 2 bytes. But when we perform any arithmetic function like increment on a *
pointer, changes occur as per the size oftheir primitive data type
| Float’, char® oF double* Is
Size of datatypes on 16-bit Machine:
Type Size (in bytes) cod
nay KT a
int dint 2 Byer One
intor si :
ee iw A) an eed
char 1 re cee 7
long 4 iS
float a a
double 8
long double 10 :
-Examples for Pointer Arithmetic
Now lets take a few examples and understand this more clearly:
BE PS reseseinnsa ih
In the above case, pointer will be of 2 bytes. An
by 2 bytes because “is also of 2 bytes.
In this case, size ot poimer is still 2 bytes ini
increment by 4 bytes because datatype is of 4 bytes.32 bit Machine
The concept of poiriter arithmetic remains exact same, but the size of pointer and
various datatypes is different in a 32 bit machine. Pointer in 32 bit machine is of 4 bytes.
And, following is a table for Size of datatypes on 32-bit Machine :
Type Size (in bytes)
int or signed int 4
char 2
long . . 8
float 8
double 16
Note: We cannot add two pointers. This is because pointers contain addresses, adding
two addresses makes no sense, because you have no idea what it would point to,
But we can subtract two pointers. This is because difference between two pointers gives
the number of elema. « of its «ala type that can be stored holween the two pointers.
Program for pointer arithmetic(32-bit machine)
Beene ys aR REir
4. Either use argument with functions, Because argument passed to the functions
are declared inside the calling function, hence they will live outside the function as
well
local variables insidé the function and return them. As static
2. Or, use s
1a¢) function exits, therefore they will be
variables have a lifetime until the
available througout the program.
Pointer to functions
It is possible to declare a pointer pointing to a function which can then be used as an
argument in another function. A pointer to a function is declared as follows,
fy 4
iS a pointer to afunction ..Now. canbe called using function pointer = along
with providing the required argument values.
2%Note:
— Notice, that there te an equal “cliff rence ¢ oltfperence of
ft bye) bebween any hreo conccenbive +element- of array
thay Arr
~ But pointer gust point at the location. of- another Variable,
UL can sme ang add ress
RetaTion BETWEEN ARRAYS AND POINTERS! A crown anno
.
@
Consider an Arra
fy
* arr
Int arrE¥) 5 => avyCoJ avr) avrts) arr£37
~ = Te programming ngme of the Srref alongs points te
address of the Pivse element of an array.
ESBS oie a il ese
; nee ,
@ — It the aheve example Sov and ‘arvCol “points bo the
add wees op the first element Tn 20 ary anol arrLod£e] are
- Tdenticet
a; FarrLo] w equivalent be arr
Ly
Since, the acldrecses of both are _the Sarre the -Veclaer
\ + \ .
arvranc ParrL0J ‘aye also the seme -
arrLo] G equivalent te xarr (Value of
an address of He Pointer’)
=" xfile * (ai) 2D:
= (iex)
= iExX]
KCB I= &Cxcay)
2y (x Cx 45)ms,
fLorrCay & equivalent te Carers) Ano, arrlaj ts equivalent
- to ACarrt+2)
dovrLra & egtdvaleat te Carr¢2) AND, arrpey ce eguivelent
bo x Carrt?)
pans} & equivalent to Carr¢3) Any, arr Lay te egutvaler
to * Carrt+3)
yarfiy i equivalent to Carrzi) AND, arrliy 4 eg uivalen
to * Carrti)
&
- you Can oleclare an. array and can use pointer to
aller the cata of an arrag.
Exampte
Vord maint)
4 ine i, avrces, Sum =o;
print £O" Enter baumbers™>
for( teoj;ieu; i++) é
i UY (avr ey) equivalent to Rarrtly
Seanfl Sd y Carre) DF
UA (arrth).4egeevelent bo arth.
Sum += * Carr di )}
5
Priokf ( "Sum = Joel 4, sum) 5
purpuT = Enter baumbers
hey 53
Sum = 2)grue (9)
2
Jat matrix [3303];
for the above arety,
the base address of ap Anny.
mabrix > points te
a (matrix) 2 points be firck row of 29 Arey . [marictod ]
x lmat inte) 2 Fy
a (matrix t 4) 2 points te seeonel row of 2p Arrag. _
wen mat rine 9 points #2 mat ix CojLo] C:
aCe C mate +0) 9 pownts te matrnLos le] op ot &*
Oo te
ae at ge
a Ce Cmabrixpo)to) 2 ’
CH mate 44) 2 Polok te matex Lot
Points t6 mebrixe £oJ oy
points to matrix 023 oy
\
elm (matin tot) 2D
aoe Cmatrire ae)t2) 2D 3643
Pointer 72 ARRAY:
Wwe tan use o pointer to point fo an array, ancl then we tan
ute that pointer to access the array elements
inter ees Se
peer
Void meine)
1 ink is
lak apste f tprrde 4S} 5
ink &p za; HI Same as
for(iso;tes pitt)
F pninkee CM dl" P27
Pitt?
colt) prink all the ve Ines
Stored in the array one by one
OurpuT >
= Replacing the print Nid) P27 gg babement oft above example,
the resulk.
lou Stabernenks. Lets See wha ee
£ will be
with bel is
prink eC Wynd", atin); prints the array, by tnevementing tnd
vin :
printf ("pod FEAT);
sepsis peter Mopcel ly Ah) f. Thee will print address of al) the
patel dec Th Ot ee amen
wink dt (lfc C24) 7 9 will print Valus of array element
p 1 y
price C's Yea); —9 will prink Value ef aLod only ,
Att; & > Compile tine error, we Cannot
change th. base address of He array
Nee: lati) G Same as alil
—_— ea
> thes wl) also prink alementsopancs |De® O coun quaunen ny wouuyen 77
cd
p os i
o ARRAY oF diorens 1 clata typ. 6% ea —nameZ LSi20 of Aregds
— We can haw array oft pointers « pointers are Very help fel
Jeagth..
in handling character array ewoith rows of varyin
ozieaang wus of Vryid a —
char wnamelay = f " zain",
0
" zai 4 using pointer
array"
hee
Zara" J3 —+
char namel3ytaea =f "Zain", array without
“zaip') an pointer &
"pare" 5; ag pen
without pointer
Using Pointer
@ | 4st —>Qain S
1 [ond |» @aig !
2» | Frd [> @are Dh
“Char name C3) Lee] &
Only 3 locations fer pointers, Extends Gill. zo memory
‘ —_—_——_——
wohechwilh..paink.£. the first. locations.
tharacter’ oft thetr respective
Strings.
1
> without using Pointer memery wastage & more, hence tks
prefered te use pointer in Such Cases.Example Program Sorting off names:
Hinclucle
Hinclucle < String A>
teiaclade < Conto-h>
Vor maine)
{
Chay aftop List, ELISI;
tnE tj ny
prinkp-(" Enter the novo names");
b seanp Cp #0);
fort iso; teen
{ geese acta);
J
fer ( Peo, enens itt)
phar)
{
forljattl if
eansjtt)
ip C stromp CaliIeaLjI)>0)
Sbrepy C by ali I) 5
cbrepy Caciz, acjI);
| Serepy C alfa, E);
4
puideop-€ 1. After. fox d2n9 la "9; .
Cieoprenn; ttt)
4 puts Caci3);
3
Nore:— Te declare string using acl
replace the Ste
‘thar a Lie] ”
ss
ourpur?
Enter the ne-of nam
6
daha
aashim
Zara
Zacnr
vyeem
ghaj
After Sorting .
aashim
lake
yeem
Shaj
Zoi
Zara
‘char aLie] icy beSY
Finclude
H#included toniohs
Vo fel swap (rnéx, inkx )
Vord main cy
{.
Ink a,b;
print£( "Enter two numbers");
feank "7d fd", Fa, PL
prep" In Before Swapping thn Qe betd ", ab);
Swapl Pa, Phd; ;
print£ "In After swapping i In @=fd b= ya a, 4);
GOO
3
Void Swap (ink #x, ink #y )
fo dnt be AX 5
aX = HY |
aygek;
fm,
5
OuTper
Bena Baapp tig wea one . :
Ac/2 bah.
After Swapping : r
acy baleTo change the Value of Variable using pass by
erence .
[ thincluce ¢ stelioh>
include
Voiel maine)
Mk aslo
® hat xptr;
Chrscre;
priate "In Vales off a Cwhen azie) i da
prety
j axptr = !2 5
at “hn Value of al when xperale) + Ad) a);
A=IkS
priate
@
getchor;
j |
"\y Value of aphr (when a=/$) + yd’, wpe) 5
fwhen alo) + Jo
of 4
Vet lee of 4 C when ¥pereiz) sn
oft #pty (When a=ly)! Ip