You are on page 1of 114

WHAT IS C? C is a programming language developed at AT & T's Bell Labs of USA in 1972 !

t "as designed and "ritten b# $ennis %it&'ie !t "as in t'e late seventies & began to repla&e t'e more familiar languages of t'at time li(e AL)*L++,L-! et& +C seems to be so popular be&ause it is reliable +simple and eas# to use *ut of t'e do.en languages t'e pri.es of purit# go to ,ASCAL+ C's prett# sister C "asn/t meant to "in pri.es+ it "as meant to be friendl#+ &apable and reliable T'erefore+ 0uite a fe" programmers "'o begin b# falling in love "it' ,as&al end up 'appil# married to & HISTORICAL DEVELOPMENT OF C: B# 1912's a 'oard of &omputer languages 'ad &ome into e3isten&e+ almost ea&' for a spe&ifi& purpose 4or e3ample C*B*L "as being used for Commer&ial Appli&ations+ 4*%T%A5 for 6ngineering and s&ientifi& Appli&ations and so on At t'is stage people started t'in(ing t'at instead of learning and using so man# languages+ ea&' for a spe&ifi& purpose T'erefore an international &ommittee &ame out "it' a language &alled AL)*L712 8o"ever AL)*L 712 never reall# be&ause popular T'en t'e# &ame up "it' C,L9Combined ,rogramming Language:developed b# Cambridge Universit# 8o"ever C,L turned out to be so big 'aving so man# features t'at it "as 'ard to learn and diffi&ult to implement Basi& Combined programming Language 9B,CL: developed b# ;artin %i&'ards aimed to solve t'is problem but turned out to be too less po"erful and too spe&ifi& Around same time <en T'omson at AT & T's Bell labs developed a language &alled B language but "as also ver# spe&ifi& %it&'ie in'erited t'e features of B and BC,L added some of 'is o"n feature and developed C language Year Language
1960 1963 196& 19&0 19&. ALGOL CPL 'CPL ' C

Developed by
International Committee Cambridge Universit (artin )ic*ards at Cambridge Universit ,en T*om%son at AT - T 'ell Labs "ennis )itc*ie at AT - T 'ell Labs

Remarks
Too general, too abstract !ard to learn, "i##ic$lt to im%lement Too s%eci#ic, deals +it* onl s%eci#ic %roblem Too s%eci#ic, deals +it* onl s%eci#ic %roblem lost generalit o# 'CPL and ' restored

C7,rogramming Stru&ture=
A C7program ma# 'ave one or more se&tions as s'o"n belo"

$o&ument se&tion

Link Section Definition Section


main9: 4un&tion se&tion
/ Declaration part Executable part 0

Subprogram se&tion
4un&tion 1
1$nction . 1$nction 3 2 2 1$nction n

$o&ument se&tion=
T'is se&tion &onsists of a set of &omment lines "'i&' gives t'e name of program+ t'e aut'or name+ date of &reation and ot'er details of t'e programmer

Lin( Se&tion=
T'is se&tion provide instru&tion to t'e &ompiler to lin( fun&tions from t'e s#stem librar# on using a dire&tive #include

$efinition Se&tion=
T'is se&tion defines all s#mboli& &onstants on using a dire&tive #define
Main ( Func!i"n #ec!i"n:

6ver# C program must 'ave one main 9: fun&tion se&tion to tell t'e &ompiler "'ere t'e e3e&ution of t'e program s'ould begins !f "e use more t'an one main fun&tion t'e &ompiler &annot tell "'i&' one mar(s t'e beginning of t'e program T'is se&tion &onsists of t"o parts+ "'i&' appears bet"een t'e opening and &losing bra&es

A: $e&laration part=
!n t'is part t'e de&laration of variables t'at ma# be useful in t'e e3e&utable part are de&lared

B: 63e&utable part=
T'ere is atleast one output statement in t'e e3e&utable part >e use variables t'at are de&lared in t'e de&laration part to a&'ieve a spe&ified tas(

T'e program e3e&ution begins at t'e opening bra&e and &loses at &losing bra&e T'e &losing bra&e is t'e logi&al end of t'e program All statements in t'e de&laration and e3e&utable part must end "it' semi&olon

Subprogram se&tion=
!t &ontains all t'e user7defined fun&tions t'at are &alled in main fun&tion T'is se&tion is generall# pla&ed immediatel# after main 9: alt'oug' t'e# ma# appear in an# order

,rogramming st#le=
C program statements are "ritten in lo"er &ase letters Upper &ase letters are used onl# for s#mboli& &onstants Bra&es group program statements toget'er and mar( beginning and end of t'e program Care must be ta(en to indentation of bra&es and statements properl# ma(e a program to read & understand easil# !t is a good pra&ti&e to "rite ea&' statement on a separate line even >e &an group statements toget'er in one line !nserted &omment not onl# in&reases t'e readabilit# but also 'elp to understand t'e logi&

63e&uting a C7program=
63e&uting a program "ritten in C involves a series of steps 1 Creating t'e program 2 Compiling t'e program ? Lin(ing t'e program "it' fun&tions of C7librar# @ 63e&uting t'e program

333333333333333

)6TT!5) STA%T6$ >!T8 C LA5)UA)6= Communi&ating "it' a &omputer involves spea(ing t'e language t'e &omputer understands+ "'i&' immediatel# rules out 6nglis' as t'e language of &ommuni&ation But t'e &lassi&al met'od of learning 6nglis' is to learn alp'abets or &'ara&ters used in t'e language to form "ords and &ombining to form senten&es and paragrap's Learning C is mu&' more easier in "'i&' "e must first (no" "'at alp'abets numbers and spe&ial s#mbols are used in & t'en 'o" using &onstants+ variables and (e#"ords are &onstru&ted and finall# 'o" are t'ese &ombined to form an instru&tion A group of t'ese instru&tions &ombined to form a program T'is is illustrated in t'e figure belo"

S!e$# in lea%nin& En&li#' lan&ua&e and #!e$# in lea%nin& C lan&ua&e:

Li(e ot'er languages C also 'as its o"n vo&abular# and grammar To learn an# language &ompletel# "e must start to learn from alp'abets T'is part in C is &alled as &'ara&ter set

Character set:
C 'as a subset of &'ara&ters t'at &an be used on most personal+ mi&ro+ mini+ and mainframe &omputers T'is subset &onsists of t'e follo"ing &ategories 1 Letters li(e A()* a(+ 2 $igits or numbers li(e ,(? Spe&ial &'ara&ters li(e A+ 7+ B+ -+ &+ C+ =+ D et& @ >'ite spa&es li(e blan( spa&e 9spa&e bar:+ 'ori.ontal bar+ &arriage return+ ne" line et& T'e &ompiler ignores "'ite spa&es unless t'e# are t'e part of a string

C okens:
!n a passage of te3t individual "ords and pun&tuation mar(s are &alled tokens. C also has such sort of tokens (no"n as C to(ens C 'as 1 t#pes of to(ens+ t'e# are 1 <e#"ords 2 !dentifiers ? Constants @ Strings E Spe&ial s#mbols 1 *perators ./ 0e12"%d#: 6ver# "ord is &lassified as eit'er as a (e# "ord or an !dentifier <e# "ord is a "ord "'i&' 'as a fi3ed meaning "'ere t'e user &annot be able to &'ange t'at meaning T'e (e# "ords+ "'i&' are fre0uentl# used in C Language+ are

Auto brea( &ase &'ar &onst &ontinue default do

double else enum e3tern float for goto if

int long register return s'ort signed si.eof stati&

stru&t s"it&' t#pedef union unsigned void volatile "'ile

5ote= All t'e (e#"ords must be "ritten in lo"er &ase


3/ Iden!ifie%#: !dentifiers refer to t'e names of variables+ fun&tions and arra#s T'ese are user7 defined names A user 'as an a&&ess to modif# t'em as per 'is re0uirement C7 permits to de&lare variables of lengt' ?1 &'ara&ters but onl# first eig't &'ara&ters are signifi&ant b# man# &ompilers 8ere after !dentifiers for data names are treated as Fariables A variable is a data name used to store a data value A variable ma# ta(e different values at different times during e3e&ution T'ere are &ertain rules provided to de&lare an identifier+ t'e# are= 1 !dentifier or variable &onsists of a se0uen&e of letters and digits "it' a letter as first &'ara&ter 4ollo"ed b# letter t'ere ma# be digits 2 Bot' upper&ase and lo"er&ase letters are permitted alt'oug' lo"er&ase letters are &ommonl# used ? T'e unders&ore &'ara&ter and G sign are permitted as identifier and used as a lin( bet"een t"o "ords in long identifiers Some s#stems also permits unders&ore as t'e first &'ara&ter @ 63&ept t'e above spe&ial &'ara&ters no ot'er &'ara&ters are permitted during de&laration E T'e variable name must not be a (e#"ord 1 >'ite spa&e is not allo"ed 63amples of variables are

Fariable name
4irstHvariable C'ar %oll no 12student intHt#pe valid not valid not valid not valid Falid

FalidD

%emar(

&'ar is a (e#"ord Blan( spa&e not permitted starting &'ara&ter must be a letter (e#"ord ma# be part of name

454

4/ C"n#!an!#:

C o n s ta n t s 5 u m e r i& !n t e g e r $ e & im a l * & ta l 8 e 3 d e & im a l 4 lo a t % eal $ o u b le C ' ra & te r S in g le C ' a r a & t e r S tr in g

Constant refers to fi3ed values t'at do not &'ange during t'e e3e&ution of program C &onstants are &lassified as follo"s=

!nteger Constants=
An integer &onstant refers to a se0uen&e of digits

$e&imal integer &onstants=


$e&imal integer &onstant refers to a se0uen&e of digits t'roug' 2 to 9 pre&eded b# an optional I or A sign 63amples= 77J1+ 1@?+2+ AE@? et&

*&tal integer &onstants=


*&tal integer &onstant refers to a se0uen&e of digits t'roug' 2 to 7 leading 2 63amples= 2?@E+ 2+ 2E17+ 21E et&

8e3ade&imal integer &onstants=


8e3ade&imal integer &onstant refers to a se0uen&e of digits t'roug' 2 to 9 and A t'roug' 4 pre&eded b# 23 or 2K T'e letters A t'roug' 4 represent numbers from 12 t'roug' 1E 63amples= 232+ 23?@E+ 2Kffab et&

%eal Constants=
T'e 0uantities t'at are represented b# numbers &ontaining fra&tional part are &alled as real &onstants or floating7point &onstants 63amples= 2 22J1+ 72 7E+ A27E 2+ 21E + 9E 9t'is notation is &alled as de&imal notation: A real number ma# also be e3pressed in e3ponential or s&ientifi& notation 63amples= 2 1Ee@+ 12e72+ ? 1J6?+

Single C'ara&ter &onstants=


A single &'ara&ter &onstant &ontains a single &'ara&ter en&losed "it'in single 0uote mar(s 63ample= La/+ L%/+ /M/+ L7/+/ L et& T'e &'ara&ter L7/ is not as t'at of number 7
464

A single &'ara&ter &onstant 'as integer values (no"n as ASC!! values T'e# store t'ese ASC!! values in t'e memor# allotted to t'em 8en&e single &'ara&ter &onstants are also used to perform arit'meti& operations on &'ara&ter &onstants

String &onstants=
A string &onstant is a se0uen&e of &'ara&ters en&losed in double 0uotes T'e &'ara&ters ma# be letters+ numbers+ spe&ial &'ara&ters and blan( spa&e 63amples= N8ello "orldO+ N1999O+ NK N et& T'e differen&e bet"een a single &'ara&ter &onstant and string &onstant is t'at= Single &'ara&ter &onstant 'as an integer value "'ere as string &onstant does not 'ave an e0uivalent integer value

Ba&( slas' &'ara&ter &onstants=


C also supports some spe&ial ba&(slas' &'ara&ter &onstants t'at are used in output fun&tions T'e# are treated as single &'ara&ter even t'oug' t'e# &onsist of t"o &'ara&ters T'ese &'ara&ter &ombinations are &alled as Escape sequences.

Some of the important backslash character constants are


Constan t LPa/ LPb/ LPf/ LPn/ LPr/ LPt/ LPv/ LP// LPO/ LPD/ LPP/ LP2/ meaning Audible alert Ba&( spa&e 4orm feed 5e" line Carriage return 8ori.ontal tab Ferti&al tab Single 0uote $ouble 0uote Question mar( Ba&( slas' 5ull

4&4

!5ST%UCT!*5S=
T'ere are basi&all# four t#pes of instru&tion 1: T#pe de&laration instru&tion 2: !nput - output !nstru&tion ?: Arit'meti& !nstru&tion @: Control !nstru&tion T#pe $e&laration !nstru&tion= to de&lare t'e t#pe of variables used in a C program !nput - *utput !nstru&tion= To perform t'e fun&tion of suppl#ing input data to a program and obtaining t'e output results from it Arit'meti& !nstru&tion= to perform arit'meti& operations bet"een &onstants and variables Control !nstru&tion= to &ontrol t'e se0uen&e of e3e&ution of various statements in a C program 4!%ST C ,%*)%A;=

63ample for printing of a message=


main9:
/

$%in!f(5 T'i# i# a C $%"&%a67 8


0

printf9: is a fun&tion "'i&' is used to print on t'e s&reen t'e value &ontained in a variable T'e general form of printf9: fun&tion is= printf9NRformat string SO+Rlist of variablesS:M s&anf9: is a fun&tion to input values from t'e (e#board and given to t'e variables T'e general form of s&anf9: fun&tion is s&anf9NRformat stringSO+ Raddress of variablesS:M >e &an get t'e address of an# variable b# using an & 9ampersand: operator before t'e variable name s&anf9: fun&tion ta(es t'e address of t'e variable so t'at t'e value entered t'roug' t'e (e#board &an be stored dire&tl# at t'at address lo&ation

464

C'apter 2
Conditional instru&tion=
!n t'e previous &'apter "e "ent t'roug' some of t'e programs "'i&' are normall# e3e&uted se0uentiall# Some times t'e e3e&ution of &ertain tas(s depends on t'e &onditional &'e&( C language provides su&' de&ision7ma(ing &apabilities and t'e supporting statements are (no"n as &ontrol or de&ision ma(ing T'ese statements are used to &ontrol t'e flo" of e3e&ution of statements ./ if statement 3/ #2i!c' statement ? &onditional operator statement 9/ &"!" statement $e&ision ma(ing "it' if statement= if #!a!e6en!: !t is basi&all# a t"o7"a# de&ision statement and is used in &onTun&tion "it' an e3pression T'e test e3pression is evaluated first and depending upon t'e value eit'er true or false evaluated b# t'e e3pression t'e statements are e3e&uted General syntax for this is if (c"ndi!i"n e:$%e##i"n ; #!a!e6en! <l"c=8 > #!a!e6en! ?8 T'e (e#"ord if tells t'e &ompiler t'at "'at follo"s is a de&ision &ontrol instru&tion T'e &ondition follo"ing t'e (e#"ord if is al"a#s en&losed "it'in a pair of parent'eses !f t'e &ondition "'atever it is true t'en t'e statement is e3e&utedM instead t'e program s(ips past it But 'o" do "e e3press t'e &ondition itself in CD As a general rule "e e3press a &ondition using C/s relational operators and t'e logi&al operators T'e relational operators allo" us to &ompare t"o values to see "'et'er t'e# are to ea&' ot'er+ une0ual or "'et'er one is greater t'an t'e ot'er 8ere/s 'o" t'e# loo( and 'o" t'e# are evaluated in C C supports si3 relational operators in all+ t'e# are Rela!i"nal "$e%a!"%#: *perator R RU ;eaning !s less t'an !s less t'an or e0ual to
494

S SU UU VU L"&ical "$e%a!"%#:

!s greater t'an !s greater t'an or e0ual to !s e0ual to !s not e0ual to

T'ese operators are used to test more t'an one &ondition and ma(e de&isions T'e e3pression+ "'i&' &ombines t"o or more relational e3pressions+ is termed as a logi&al e3pression or a &ompound relational e3pression C 'a# !'e f"ll"2in& !'%ee l"&ical "$e%a!"%# L"&ical "$e%a!"%: *perator && WW V 63ample= 1 main9: X int &'M printf9Yenter #our &'oi&e=Y:M s&anf9YCdY+ &&':M if9&'UU2: X printf9Y8ello "orld VPnY:= Z if 9&'UU1: printf9Ygood b#eVY:M printf9Yt'an( #ouY:M Z *utput= 6nter #our &'oi&e= , 8ello "orld T'an( #ou 6nter #our &'oi&e= .
4 10 4

;eaning And *r 5ot

)ood b#eV T'an( #ou

2 main9: X int a+ b M aU1M bU9M if9aSb: X printf9YA is greaterY:M Z Z *utput= A is greater ? C program to &'e&( "'et'er t'e given no is even or odd main9: X int noM printf9Yenter a number=Y:M s&anf9YCdY+ &no:M if9noC2UU2: printf9Yit is an even numberY:= if9noC2UU1: printf9Yit is an odd numberY:= Z enter a number= @ !t is an even number 6nter a number= !t is an odd number !n t'e above e3amples if t'e test e3pression is true t'e statement beneat' t'e if statement is going to be e3e&uted !f t'ere are multiple instru&tions t'at need to be e3e&uted based on t'e &ondition t'en t'ose instru&tions need to be pla&ed "it'in t'e opening and t'e &losing bra&es But if it is a single instru&tion as in t'e above e3ample+ on&e t'e &ondition is found to be true t'en t'e instru&tion belo" t'e if is done automati&all# 5*T6= if t'ere are more t'an one statement after if statement t'en (eep all t'e statements in a blo&( 9i e + X and Z:
4 11 4

63ample= main9: X int 3U2M if93UU2: X printf9Y ! Y:M printf9Y am Y:M printf9Y learning C language Y:M Z Z ! am learning C language 8ere in t'e above e3ample if : is e0ual to .ero "e are going to e3e&ute a group of statements i e t'ree printf statements 8en&e t'ese t'ree statements are grouped as a blo&( 5*T6= !f t"o simple &onditions are to be Toined toget'er to ma(e a &omple3 &ondition ma(e use of logi&al operator 63ample= main9: X int #earM printf9Yenter a #ear=Y:= s&anf9YCdY+ &#ear:M if9#earC@UU2: printf9Yit is a leap #earY:M Z If(el#e #!a!e6en!: T'i# i# an e:!en#i"n #i6$le if #!a!e6en!/ T'e &ene%al f"%6 i# if (c"ndi!i"n e:$%e##i"n ; T%ue <l"c= #!a!e6en!#8 > el#e ; Fal#e <l"c= #!a!e6en!#8 > #!a!e6en! ?8 !f t'e test e3pression is true+ t'e statements immediatel# after if statement is e3e&uted i e !%ue <l"c= #!a!e6en!# ot'er"ise t'e statements immediatel# after false statement

4 1. 4

is e3e&uted i e fal#e <l"c= #!a!e6en!# not bot'/ !n bot' &ases t'e &ontrol is transferred to t'e statement K 63ample= 1 C7program to &'e&( "'et'er t'e given number is even or odd main9: X int numberM printf9Yenter numberY: s&anf9YCdY+ &number:M if9numberC2 UU 2: printf9Yt'e number entered is evenY:M else printf9Yt'e number entered is oddY:M Z !n t'e above program if #ou enter a value to t'e variable Lnumber/ + if t'e number gives a reminder .ero t'en it gives t'e output as N t'e number entered is evenO And t'e reminder is ot'er t'an .ero i e one t'en t'e output is Nt'e number entered id oddO 3/ C program to &'e&( "'i&' element is greater upon t'e given values main9: X int a+ b M printf9Yenter a and b values=Y:M s&anf9YCdCdY+ &a+ &b:M if9aSb: printf9YA is )reaterY:M else printf9YB is greaterY:M Z T'e el#e if ladde%: !t id perfe&tl# alrig't if "e "rite an entire if A el#e &onstru&t "it'in eit'er t'e bod# of t'e if statement or t'e bod# of an el#e statement T'is is &alled nesting of ifBs t'is is s'o"n in t'e follo"ing program T'e general form is !f9&ondition: Statement1M else if 9&ondition2: statement2M
4 13 4

else if9&ondition?: statement?M 7777777 7777777 7777777 else default statementM statement KM 63ample of nested if7else= main9: X int iM printf9Nenter eit'er 1 or 2O:M s&anf9NCdO +&i:M if9i UU 1: printf9N[ou "ould pass t'e e3amO:M else if9i UU 2: printf9N#ou "ill fail t'e e3amO:M else printf9N#ou "ill s(ip t'e e3amO:M Z 5ote t'at t'e se&ond if Ael#e &onstru&t is nested in t'e first el#e statement !f t'e &ondition in t'e first if statement is false+ t'en t'e &ondition in t'e se&ond if statement is &'e&(ed !f it is false as "ell t'e final el#e statement is e3e&uted T'e &onditions are evaluated from top do"n"ards As soon as a true &ondition is found+ t'e statement asso&iated "it' it is e3e&uted and &ontrol is transferred to t'e statement >'en all t'e n &onditional are false t'en t'e final else statement is e3e&uted T'ere is no limit on 'o" deepl# t'e if and t'e el#e &an be nested 63ample= main9: X &'ar &odeM printf9Yenter a &ode number9r-g-b: UY:M s&anf9YC&Y+ &&ode:M if9&ode UU 'r': printf9Y&olor is redY:M
4 17 4

else if9&ode UU 'g': printf9Y&olor is redY:M else if9&ode UU 'b': printf9Y&olor is redY:M else printf9Y&olor is defaultY:M Z T'e #2i!c' #!a!e6en!: A program &an be designed using more number of if statements+ but t'e &omple3it# of su&' program in&reases "'enever t'e number of alternatives in&reases !t ma# &ause &onfusion if more number of if \else statements are t'ere C 'as a built7in multi"a# de&ision statement (no"n as #2i!c' statement T'e s"it&' statement tests t'e value of a given variable against a list of &ase values and "'en mat&' is found+ a blo&( of statements asso&iated "it' t'at &ase is e3e&uted else t'e default statement blo&( is going to be e3e&uted The general form of switch statement is #2i!c'( in!e&e% e:$%e##i"n X ca#e &onstant1 : do t'isM ca#e &onstant2 : do t'is 8 ca#e &onstant? : do t'is 8 / / / defaul! : do default 8 Z !n t'e s#nta3 given above t'e "ords mentioned in t'e bold letters are (e#"ords 1 T'e e3pression in s"it&' statement is an !nteger or single &'ara&ter &onstant 2 T'e &onstant1 + &onstant2 \ is &onstants and are (no"n as &ase labels ? 6a&' of t'ese values is uni0ue "it'in s"it&' statement @ T'ere is no need to put bra&es around t'ese blo&(s

4 15 4

E T'e brea( statement at t'e end of ea&' blo&( tells t'e &ompiler t'at it is end of ea&' &ase blo&( and e3it from t'e s"it&' statement transferring t'e &ontrol out of s"it&' &ase 1 T'e default is an optional &ase T'e default blo&( is e3e&uted "'enever t'ere is no &ase mat&'ing "it' t'e e3pression !f t'ere is no default in t'e s"it&' statement no a&tion ta(es pla&e if no mat&' found in t'e s"it&' statement So+ "'at 'appens "'en "e run t'e program &ontaining t'e s"it&'D 4irst+ t'e integer e3pression follo"ing t'e (e#"ord s"it&' is evaluated T'e value it gives is t'en mat&'ed one b# one against t'e &onstant values t'at follo" t'e &ase statements >'en a mat&' is found t'e program e3e&utes t'e statements as "ell !f no mat&' is found "it' an# of t'e &ase statements onl# t'e statements follo"ing t'e default are e3e&uted A fe" e3amples "ill s'o" 'o" t'is &ontrol stru&ture "or(s Consider t'e follo"ing program main9: X int i U 2M s"it&'9 i : X &ase 1= printf9N! am in &ase 1O:M &ase 2= printf9N! am in &ase 2O:M &ase ?= printf9N! am in &ase ?O:M default= printf9N! am in defaultO:M Z Z T'e output of t'is program "ould be= ! am in &ase 1 ! am in &ase 2 ! am in &ase ? ! am in default $efinitel# not+"'at "e e3pe&ted >e didn/t e3pe&t t'e se&ond and t'e t'ird line in t'e above output T'e program prints &ase 2 and &ase ? and t'e default &ase >ell + #es "e said t'e #2i!c' e3e&utes t'e &ase "'ere a mat&' is found and all t'e subse0uent ca#e# and t'e defaul! as "ell !f #ou "ant t'at onl# &ase 2 s'ould e3e&ute+ it is upto #ou to get out of t'e &ontrol stru&ture t'en and t'ereb# using a <%ea= statement >'enever a <%ea= statement is e3e&uted t'e &ontrol is broug't out of t'e #2i!c' ca#e T'e follo"ing e3ample s'o"s 'o" t'is is done

4 16 4

main9: X int i U 2M s"it&'9 i : X &ase 1= printf9N! am in &ase 1O:M brea(M &ase 2= printf9N! am in &ase 2O:M brea(M &ase ?= printf9N! am in &ase ?O:M brea(M default= printf9N! am in defaultO:M Z Z T'e output of t'is program "ould be = ! am in &ase 2 5*T6= T'ere is no need for a <%ea= statement after t'e defaul!+ sin&e t'e &ontrol &omes to t'e end an#"a# TIPS FOR CSIND SWITCH/ A fe" useful tips about usage of s"it&' are as follo"s= a: T'e earlier program "'i&' used s"it&' ma# give #ou a "rong impression t'at #ou &an use &ase arranged in as&ending order 1+2+? and default [ou &an in fa&t put t'e &ases in an# order #ou please 6g= main9: X int i U 22M s"it&'9 i : X &ase 121= printf9N ! am in &ase 121O:M brea(M &ase 9= printf9N! am in &ase 9O:M brea(M &ase 22=
4 1& 4

printf9N! am in &ase 22O:M brea(M default= printf9N! am in defaultO:M Z Z T'e output of t'is program "ould be= ! am in &ase 22 b: [ou are also allo"ed to use &'ar values in ca#e and #2i!c' as s'o"n in t'e follo"ing program But "e are n"! all"2ed to 'ave fl"a! &onstant in s"it&' main9: X &'ar & U L3/M s"it&'9 & : X &ase Lv/= printf9N! am in &ase vO:M brea(M &ase La/= printf9N! am in &ase a:M brea(M &ase L3/= printf9N! am in &ase 3O:M brea(M default = printf9N! am in defaultO:M Z Z T'e output of t'e above program "ould be= ! am in &ase 3 &: >e &an mi3 integers and &'ara&ter &onstants in different ca#e# of a #2i!c' main9: X int & U 9M s"it&'9 & : X &ase Lv/= printf9N ! am in &ase vO:M brea(M &ase 9= printf9N ! am in &ase 9O:M
4 16 4

brea(M &ase 27= printf9N ! am in &ase 27O:M brea(M default = printf9N ! am in defaultO:M Z Z T'e output of t'e above program "ould be ! am in &ase 9 T'e advantages of #2i!c' over if are t'at #2i!c' &ase leads to a more stru&tured program and t'e level of indentation is manageable 5ote t'at fl"a! c"n#!an!# a%e n"! all"2ed in #2i!c' SOME MORE E?AMPLES: 63ample 1= C7program to demonstrate s"it&' statement using e3pression as integer &onstant main9: X int &odeM printf9Yenter a &ode number91-2-?: = Y:M s&anf9YCdY+ & &ode:M s"it&'9&ode: X &ase 1= printf9Y[ou entered *neY:M brea( M &ase 2= printf9Y[ou entered T"oY:M brea( M &ase ?= printf9Y[ou entered T'reeY:M brea( M default = printf9Y[ou entered "rong 5umberY:M Z Z T'e output of t'e program "ould be enter a &ode number91-2-?:=2 [ou entered t"o enter a &ode number91-2-?:= @ [ou entered "rong number

4 19 4

63ample 2= C7program to demonstrate s"it&' statement using e3pression as single &'ara&ter &onstant main9: X &'ar &olorM printf9Yenter a &olor9r-g-b: = Y:M s&anf9YC&Y+ & &olor:M s"it&'9&olor: X &ase 'r' = printf9Y[ou opted %ed &olorY:M brea( M &ase 'g' = printf9Y[ou opted )reen &olorY:M brea( M &ase 'b' = printf9Y[ou opted Blue &olorY:M brea( M default = printf9Y[ou opted >rong &olorY:M Z Z T'e output of t'e above program "ould be 6nter a &olor9r-g-b: = b [ou opted Blue &olor 6nter a &olor9r-g-b: = B [ou opted >rong &olor T'e above program "or(s onl# if #ou provide t'e input value as a lo"er &ase letter to a&&ommodate for bot' lo"er and upper &ase letters modif# t'e program as follo"s main9: X &'ar &olorM printf9Yenter a &olor9r-g-b: = Y:M s&anf9YC&Y+ & &olor:M s"it&'9&olor: X &ase '%'= &ase 'r'= printf9Y[ou opted %ed &olorY:M brea( M &ase ')'=
4 .0 4

&ase 'g'= printf9Y[ou opted )reen &olorY:M brea( M &ase 'B'= &ase 'b'= printf9Y[ou opted Blue &olorY:M brea( M default = printf9Y[ou opted >rong &olorY:M Z Z T'e output of t'e above program "ould be 6nter a &olor9r-g-b:= r [ou opted )reen &olor 6nter a &olor9r-g-b:= % [ou opted for )reen &olor 6nter a &olor9r-g-b:= B [ou opted for Blue &olor Sin&e t'ere are no statements and also brea( statement after ca#e ERE: t'e &ompiler b# passes t'e &ontrol to t'e ne3t statement i e ca#e E%E: t'erefore t'e &ontrol &'e&(s "it' bot' t'e &ases 9upper and lo"er: of t'e e3pression C"ndi!i"nal "$e%a!"%: T'is is also an operator useful to ma(e t"o7"a# de&isions T'is operator is a &ombination of ? and : and ta(es t'ree operands T'e general s#nta3 for t'is operator is as follo"s C"ndi!i"nalFe:$%e##i"n ? e:$%e##i"nF. : e:$%e##i"n38 *t'er "a# of loo(ing at it is= C"ndi!i"nFe:$%e##i"n ? !%ue #!a!e6en! : fal#e #!a!e6en!8

4 .1 4

T'e &onditional e3pression is evaluated first !f t'e result is true9non7.ero integer: e3pression1 is evaluated and t'e value is returned to t'e &onditional e3pression ot'er"ise e3pression72 value is returned 63ample= main9: X int a+b+3M printf9Yenter a and b values=Y:M s&anf9YCdCdY+&a+&b:M if9aSb: 3 U aM else 3 U bM printf9YCd is greater Y+3:M Z T'e above program &an also be re"ritten using a &onditional operator as follo"s= main9: X int a+b+3M printf9Yenter a and b values=Y:M s&anf9YCdCdY+&a+&b:M 3U9aSb:Da=bM printf9YCd is greaterY+3:M Z T'e &onditional operator &an also be nested for evaluating more &omple3 assignment de&isions 63ample= A program to print t'e biggest upon t'e given t'ree numbers main9: X int a+b+&+3M
4 .. 4

printf9Yenter a and b values=Y:M s&anf9YCdCdY+&a+&b:M :G(aH< ? (aHc ? a : c : (<Hc ? < : c8 printf9YCd is greater Y+ 3:M Z !n t'e above e3ample t'e &onditional statement a S b is first evaluated !f it is true+ t'en it &'e&(s for aS& and if it also evaluates to be true t'en+ it assigns a to 3 if not & to 3 and if aS b &ondition fails t'en b S & is &'e&(ed+ if found to be true t'en assigns b to 3 and ot'er"ise assigns & to 3 T'e &"!" #!a!e6en!: C supports t'e goto statement to bran&' un&onditionall# from one point to anot'er in t'e program But using t'is statement in 'ig'l# stru&tured language li(e C is not essential T'e goto re0uires a label in order to identif# t'e pla&e "'ere t'e bran&' is to be made A label is an# valid variable names+ and must be follo"ed b# &olon 9=: and is pla&ed immediatel# before t'e statement "'ere t'e &ontrol is to be transferred T'e label &an be an#"'ere in t'e program eit'er before t'e usage of goto statement >'enever &"!" la<el statement en&ounters t'e &ontrol "ill Tump to t'e statement immediatel# follo"ing t'e label !t brea(s t'e se0uential e3e&ution of program !f t'e label is before t'e goto statement a loop "ill be formed and some statements "ill be e3e&uted repeatedl# Su&' a Tump is &alled as <ac=2a%d Iu6$/ !f t'e label is after t'e goto statement some statements "ill be s(ipped "it'out e3e&ution Su&' a Tump is &alled as f"%2a%d Iu6$/ 5*T6= A &onditional statement must be used to terminate t'e loop "'enever t'e ba&("ard Tump is used ot'er"ise it ma# lead to an infinite loop 63ample= 63ample for 4or"ard Tump main9: X int nM printf9Yenter eit'er 2 or 1 to get message=Y:M s&anf9YCdY+ &n:M if9nUU2: goto ab&M else goto 3#.M ab&= printf9Y8ello >orldVY:M 3#.= printf9Y)ood B#eVY:M
4 .3 4

Z T'e output of t'e above program "ould be= enter eit'er 2 or 1 to get message=2 8ello >orldV enter eit'er 2 or 1 to get message=1 )ood B#eV 63ample for Ba&("ard Tump= ,rinting of natural numbers main9: X int iU1M natural= printf9YCdY + i:M iAAM goto naturalM Z T'e output of t'e program 12?@E17J9\\\\\\\\\\\\\\\ t'e above program "ill lead to an infinite loop To avoid t'at uses a &onditional statement along "it' &"!" statement and &an be modified as follo"s main9: X int iU1M natural= printf9YCdY + i:M iAAM if9iR22: goto naturalM Z T'e output of t'is program is 12?@E17J91211121?1@1E11171J19 63er&ise= Questions !f and if7else 1 >rite a program to find t'e greatest among t'ree numbersD 2 >rite a program to find "'et'er a given number is even or oddD ? >rite a program to &al&ulate t'e grade of a student based on 'is average+ "'ere t'e user is allo"ed to enter t'e mar(s for E subTe&ts D @ >rite a program to &'e&( "'et'er a given #ear is leap #ear or notD E >rite a program to &al&ulate ele&tri&it# bill b# t'e follo"ing &riteria
4 .7 4

U5!TS RU122 S122 RU222 S222 S>!TC8 CAS6=

,%!C6 2 E2 2 12 2 7E

1 >rite a program to find "'et'er a &'ara&ter is vo"el or not ]'int = using s"it&'7 &ase^D 2 >rite a program to perform t'e addition+ subtra&tion+ multipli&ation and division of t"o numbers using s"it&' I &ase "'ere enter t'e &'oi&e to be an integer variableD ? %e"rite t'e above program using a &'ara&ter variableD C'a$!e% ? DECISION MA0IND AND LOOPIND T'e versatilit# of &omputer lies in its abilit# to perform a set of instru&tions repeatedl# T'is involves repeating some portion of t'e program eit'er a spe&ified no of times or until a &ondition is being satisfied T'is is being done t'roug' a loop &ontrol stru&ture $epending on t'e position of t'e &ontrol statement in t'e loop+ t'e loop is &lassified as 1: 6ntr# &ontrolled loop= T'e &ondition is &'e&(ed before t'e e3e&ution of t'e bod# of t'e loop 2: 63it &ontrolled loop= T'e &ondition is &'e&(ed after e3e&ution of t'e bod# of t'e loop B# t'ree "a#s+ "e &an ma(e a loop using "'ile using for using do7"'ile The while loop: T'e &ene%al f"%6a! "f 2'ile l""$ i# a# f"ll"2# initiali.e loop &ounterM "'ile9test loop &ounter using a &ondition: X do t'isM and t'isM in&rement - de&rement loop &ounterM Z

4 .5 4

T'is is an entr#7&ontrolled loop be&ause t'e test &ondition is evaluated first and if it is true t'en t'e bod# of t'e loop is e3e&uted After e3e&ution of t'e bod#+ t'e test &ondition is on&e again &'e&(ed and if it is true t'e bod# is e3e&uted T'is pro&ess is &ontinued until t'e &ondition is false and t'en &ontrol goes to t'e statement follo"ing t'e loop bod# 4e" points about "'ile= t'e statements "it'in "'ile loop "ould (eep on getting e3e&uted till t'e &ondition is true >'en t'e &ondition be&omes false+ t'e &ontrol passes to t'e first statement t'at follo"s t'e bod# of t'e "'ile loop t'e &ondition ma# use relational or logi&al operators e3ample= "'ile9iRU12: "'ile9iR12 && TRU1E: "'ile9TS12&&9bR1EWW&R22:: t'e statements "it'in t'e loop ma# be a single line or a blo&( of statements !f a blo&( of statement is t'ere t'en it s'ould be en&losed "it' pair of bra&es+ ot'er"ise &reating a blo&( is optional e3ample= "'ile9iRU12: iUiA1M "'ile9iRU12: X printf9YCdPnY+ i:M iUiA1M Z NOTE: T'e <%ace# a%e needed "nl1 if !'e <"d1 c"n!ain# !2" "% 6"%e #!a!e6en!#/ 63amples= -B printing of natural numbers less t'an 22 Bmain9: X int iU1M -B!5!TAL!_AT!*5 *4 FA%!ABL6 B64*%6 C*;,A%!5)Bprintf9Yt'e natural numbers less t'an 22 are=PnY:M "'ile9iRU22: X printf9YCdPnY+ i:M iUiA1M -B in&rement BZ Z The do while loop: T'e basi& format of do "'ile statement is as follo"s d" ; <"d1 "f !'e l""$8
4 .6 4

> 2'ile( c"ndi!i"n 8 T'is is an e3it7&ontrolled loop be&ause t'e bod# of t'e loop is e3e&uted first for t'e first time and t'en t'e test e3pression is evaluated !f it is true t'en t'e bod# of t'e loop is e3e&uted again T'is pro&ess is &ontinued until t'e &ondition is false and t'en &ontrol passes to t'e first statement t'at follo"s t'e bod# of t'e do "'ile loop 63amples= 1 printing of natural numbers less t'an 22 main9: X int iU1M printf9Yt'e natural numbers less t'an 22 are=PnY:M do X printf9YCdPnY+ i:M iAAM Z "'ile9iRU22: M Z

The for loop: T'is is anot'er entr#7&ontrolled loop t'at provides anot'er a more &on&ise loop &ontrol stru&ture for is t'e ver# popular loop allo"s us to spe&if# t'ree t'ings about a loop in a single line= setting a loop &ounter to an initial value testing t'e loop &ounter in&rement or de&rement of loop &ounter ea&' time t'e loop repeated T'e general s#nta3 is f"%(ini!iali+a!i"n8 c"ndi!i"n 8 inc%e6en!Jdec%e6en! ; <"d1 "f !'e l""$8 > 1 !nitiali.e se&tion= !n t'is se&tion t'e variable are initiali.ed and t'e variables are (no"n as loop7&ontrol variables 2 Test7&ondition se&tion= !n t'is se&tion t'e value of t'e &ontrol variable is tested !f t'e &ondition is true+ t'e bod# of t'e loop is e3e&uted ot'er"ise t'e loop is terminated and statements immediatel# follo"s t'e loop is e3e&uted
4 .& 4

? !n&rement - de&rement se&tion= !n t'is se&tion t'e loop7&ontrol variable is eit'er in&remented or de&remented e3ample= main9: X int p+n+&ountM float r+siM for9&ountU1M&ountRU?M&ountU&ountA1: X printf9Y6nter values of p+n+rY:M s&anf9YCdCdCfY+&p+&n+&r:M siUpBnBr-122M printf9YSimple !nterest U%s CfY+si:M Z Z let us see 'o" for statement e3e&utes= "'en t'e for statement is e3e&uted first time + t'e value of &ount is set to an initial value 1 no" t'e &ondition &ountRU? is tested Sin&e &ondition satisfied+ bod# of t'e loop is e3e&uted for t'e first time on rea&'ing t'e &losing bra&e of for +&ontrol ba&(s to t'e for statement+ "'ere t'e value of &ount gets in&remented b#1 again t'e test is performed to &'e&( t'e &ondition !f t'e &ondition is true+ t'en t'e statements "it'in t'e bra&es of for are e3e&uted again t'e bod# of for loop &ontinues till t'e &ount doesn't e3&eed t'e final value ? >'en &ount rea&'es @ t'e &ontrol e3its from t'e loop and is transferred to t'e statement immediatel# after t'e bod# of for Addi!i"nal fea!u%e# "f f"% l""$: 1 ;ore t'an one variable &an be initiali.ed at a time in for statement and ea&' variable must separate "it' &omma for9iU2+TU12 M iR12 MiAA: 2 ;ore t'an one variable &an be in&remented-de&remented at a time in for statement and ea&' variable must separate "it' &omma for9iU2+TU12 M iR12 MiAA+ TAA: ? T'e test7&ondition ma# 'ave an# &ompound relation 9relational statements "it' logi&al statements: @ *ne or more se&tions &an be omitted if ne&essar# but t'e semi7&olons must be pla&ed as it is T'e important point to note is t'at+ "e &an omit eit'er initiali.ation 9if t'e variable is alread# initiali.ed: or
4 .6 4

in&rement-de&rement of &ontrol variable 9if t'is pro&ess &arries out in t'e bod# of t'e loop: or bot' But if t'e test &ondition is omitted for statement sets up an infinite loop Su&' loops &an be bro(en using brea( or goto statements for9 M iR12 M : -B ,rogram to print 12 natural numbers Bmain9: X int iU1M for9 M iRU12 M iAA: -B initiali.ation is avoided as ! is alread# de&lared Bprintf9YCd Y+ i:M Z ?: ,rogram to find t'e sum of given numbers main9: X int i+n+sumU2 M for9iU2MiR12M : -B in&rementation is avoided as !t is de&lared in t'e bod# of t'e loop BX printf9Yenter a numberY:M s&anf9YCdY+&n:M sumAUnM iAAM -B in&rementation of &ontrol variable9i: BZ printf9Yt'e sum of a given number is U Cd Y+ sum:M Z Ne#!ed l""$#: 63e&ution of a loop "it'in a loop is &alled as nested loops 8ere are fe" e3amples to e3plain about t'is Examples: -B ,rogram to print stars in t'e follo"ing format using nested do\"'ile loop BB BB BBB BBBB BBBBB main9: X int r+&+nM printf9Y 6nter t'e number of ro"s #ou "ant to print=Y:M
4 .9 4

s&anf9YCdY+&n:M rU1M do -B starting of outer loop to in&rement ro"s BX &U1M do -B starting of inner loop to print stars BX printf9YBY:M &AAM Z "'ile9&RUr:M -B end of inner loop Bprintf9YPnY:M rAAM Z"'ile9rRUn:M -B end of outer loop BZ -B end of program BKu6$in& in l""$#: Some times it is needed eit'er to s(ip a part of loop or to e3it from t'e loop basing on a parti&ular &ondition C provides t"o statements ./ c"n!inue to s(ip a part of a loop 3/ <%ea= to Tump out of t'e loop c"n!inue #!a!e6en! : T'is statement &auses a loop to &ontinue "it' t'e ne3t iteration after s(ipping an# statements in bet"een !t tells t'e &ompiler to s(ip t'e follo"ing statements and &ontinue "it' t'e ne3t iteration T'e s#nta3 for t'is statement is c"n!inue8 5*T6= brea( and &ontinue statements are usuall# asso&iated "it' an if statement and it is possible onl# inside a loop 63ample= main9: X int i+TM for9iU1MiRU2MiAA: X for9TU1MTRU2MTAA: X if9iUUT: &ontinueM printf9YPnCdCdPnY+i+T:M Z Z Z T'e output of t'e above program "ould be
4 30 4

12 21 8ere "'en t'e value of i e0uals t'at of T+ t'e &ontinue statement ta(es t'e &ontrol to t'e for loop 9inner: b#passing rest of t'e statements pending e3e&ution in t'e for loop9inner: <%ea= #!a!e6en!: >e often &ome a&ross a situation "'en "e "ant to Tump out of a loop instantl#+ "it'out "aiting to get ba&( to t'e &onditional test T'e (e#"ord brea( allo"s us to do t'is A brea( is usuall# asso&iated "it' an if statement E:a6$le: Q= "rite a program to determine "'et'er a number is prime or not a prime number is one "'i&' is divisible onl# b# 1 or itself main9: X int num+iM printf9Yenter a number =Y:M s&anf9YCdY+ &num:M iU2M "'ile9i RU num71: X if9numCiUU2: X printf9Ynot a prime number Y:M brea(M Z iAAM Z if9iUUnum: printf9YPn Cd is a prime number Y+num:M Z 'ere "'en t'e num "ill be divisible b# i "'i&' "ill be 'aving t'e value of 2 to num71+ t'e if 9numCiUU2: &ondition "ill be&ome true+ t'en t'e loop "ill brea( "it'out testing t'e &ondition T'e e:i!( Func!i"n e:i!( is a standard librar# fun&tion t'at &omes read#7made "it' t'e C &ompiler !ts purpose is to terminate t'e e3e&ution of t'e program <%ea= terminates t'e loop or s"it&' in "'i&' it is "ritten +"'ereas e:i!( terminates t'e e3e&ution of t'e program itself E:e%ci#e: L**,S

4 31 4

1 2 ? @ E

>rite a program to find t'e sum of first Ln/ natural numbersD >rite a program to find "'et'er a given number is prime or notD >rite a program to print t'e number in reverse orderD >rite a program to find t'e fa&torial of a numberD >rite a program to find t'e po"er of 3 raised b# # "'ere 3 and # values are inputsD C'a$!e% @ A%%a1#

!n previous &'apter "e learnt a&&essing of values t'roug' variables+ !t is evident t'at "e &an not store multiple values in onl# one variable name 4or t'at C is providing a derived data t#pe (no"n as arra#s T'is &'apter des&ribes 'o" arra#s of various t#pes &an be &reated and manipulated in C Defini!i"n: An arra# is a group of related data items of same data t#pe t'at s'ares a &ommon name T'e arra# name represents a set of data items A parti&ular value is a&&essed b# its inde3 value or subs&ript value in s0uare bra&(ets i e ] ^ after t'e arra# name T'e individual values are termed as elements. !n C7language "e &an refer arra#s of n7 dimensions 8o"ever t'ere are situation in "'i&' "e "ould be "anting to store more t'an one value at a time in a single variable 4or e3ample suppose "e "is' to arrange t'e per&entage mar(s obtained b# 122 students in as&ending order !n su&' a &ase "e 'ave t"o options to store t'ese mar(s = a: Constru&t 122 variables to store per&entage mar(s obtained b# 122 different students i e ea&' variable &ontaining one student/s mar(s b: Constru&t one variable 9&alled arra#: &apable of storing or 'olding all t'e 'undred values *bviousl# t'e se&ond alternative is better A simple reason is it "ould be mu&' easier to 'andle one variable t'an 'andling 122 different variables One di6en#i"nal a%%a1#: A list of items &an be given one variable name using onl# one subs&ript is &alled as single subs&ript variable or one dimensional arra# T'e subs&ript &an begin "it' number 2 Decla%a!i"n "f a%%a1 La%ia<le:
4 3. 4

da!a!1$e La%ia<leFna6eM a%%a1 #i+e N T'e arra# si.e must be an integer &onstant value and t'e datatype ma# be of an# data t#pe Arra# si.e spe&ifies t'e number of elements in an arra# of an# data t#pe 4or e3ample if a variable "ant to a&&ess E integer values "it' a &ommon name t'en t'e de&laration s'ould be done as follo"s= int number]E^M 5o" t'e variable Lnumber/ &an be able to a&&ess E values of integer t#pe Ini!iali+a!i"n and a##i&nin& Lalue# !" a%%a1 La%ia<le#: T'e initiali.ation and assignment of values to arra# variables &an be done b# t'ree "a#s 1: initiali.ation at t'e time of de&laration 2: assignment after de&laration of variable "it' t'eir inde3 values ?: Assignment of values as per users re0uirement using standard input and output statements Ini!iali+a!i"n a! !'e !i6e "f decla%a!i"n: T'e initiali.ation of arra# elements is t'e same "a# as #ou initiali.e a ordinar# variable but onl# #ou 'ave to ma(e a blo&( of elements pre&eding and su&&eeding "it' bra&es T'e general s#nta3 for t'is is Da!a !1$e a%%a1Fna6eM#i+eN G ; li#! "f Lalue# >8 8ere is an e3ample to demonstrate t'e initiali.ation of arra# variable in! aMON G ;3*O*@*-*.>8 !f #ou "ant to initiali.e t'e elements less t'an t'e de&lared si.e t'en t'at man# elements "ill be initiali.ed !f #ou don't (no" t'e e3a&t number of elements #ou are going to initiali.e t'en omit t'e subs&ript value9si.e: and initiali.e t'e elements T'e &ompiler allo&ates enoug' memor# to a&&ommodate t'e elements i e t'e si.e is t'at value for 'o" man# elements #ou provided to a&&ommodate for 6g= int n]^ U X2+1J+9+? 12 @EZM float a]^ U X12 2+ @E 29+2? 2@+7@? 22ZM 5*T6= !f t'e si.e of t'e arra# is not spe&ified t'en initiali.ation be&omes ne&essar# 63ample= main9: X
4 33 4

int a]E^UX 1+2+?+@+EZ+ iM for9iU2MiREMiAA: printf9Y T'e value stored in a]Cd^ UCd PnY+i+a]i^:M Z *utput= T'e value stored in a ]2^ U 1 T'e value stored in a ]1^ U 2 T'e value stored in a ]2^ U ? T'e value stored in a ]?^ U @ T'e value stored in a ]@^ U E D%a2<ac=# in ini!iali+a!i"n "f a%%a1#: 1: T'ere is no &onvenient "a# to initiali.e onl# sele&ted element 2: T'ere is no s'ort&ut met'od for initiali.ing large amount of data A##i&n6en! af!e% decla%a!i"n "f La%ia<le 2i!' !'ei% inde: Lalue#: Using t'eir inde3 values 9subs&ript value: &an do t'e assignment of arra# elements to t'e arra# variable !n general Variable-name[index no ! "al#e 4or e3ample if #ou "ant to initiali.e a value to an arra# variable do as follo"s number]2^U12 number]1^U11 number]2^U12 number]?^U1? number]@^U1@ A##i&n6en! "f Lalue# a# $e% u#e%# %ePui%e6en!= Using standard input and output statements t'e user &an be able to assign t'e values to t'e arra# variable To assign t'e elements or printing out t'e elements in t'is met'od at least one loop is re0uired main9: X int mar(s]E^ + i M printf9Y 6nter elements into t'e arra#Y:M for9iU2MiREMiAA: -B loop to &'ange t'e subs&ript value Bs&anf9YCd Y+ &mar(s]i^:M for9iU2MiREMiAA: -B loop to print b# &'anging t'e subs&ript value Bprintf9Y T'e value stored in mar(s]Cd^ UCd PnY+i+mar(s]i^:M Z on&e an arra# is de&lared + individual elements in t'e arra# &an be referred "it' subs&ript + t'e number in t'e s0uare bra&(ets follo"ing t'e arra# name T'is number
4 37 4

spe&ifies t'e elements position in t'e arra# All t'e arra# elements of t'e arra# are numbered starting "it' 2 T'us+ mar(s]2^ is not t'e se&ond element but t'e t'ird !n our program "e are using t'e variable i as a subs&ript to refer to various elements of t'e arra# T'is variable &an ta(e different values and 'en&e &an refer to t'e different elements in t'e arra# in turn 5*T6= T'e value of variable Li L is started from 2 sin&e t'e subs&ript value in an arra# starts "it' 2 and ends "it' arra# si.e minus one+ for an arra# of E elements t'e minimum subs&ript value is 2 and ma3imum value is @ B*U5$ C86C<!5)= !n C t'ere is no &'e&( to see if t'e subs&ript used for an arra# e3&eeds t'e si.e of t'e arra# $ata entered "it' a subs&ript e3&eeding t'e arra# si.e "ill simpl# be pla&ed in memor# outside t'e arra# probabl# on top of some data T'is "ill lead to unpredi&table results+ and t'ere "ill be no error messages to "arn #ou t'at #ou are going be#ond t'e arra# si.e T'e follo"ing program ma# turn out to be sui&idal 6g= main9: X int num]12^M int iM for9iU2MiRUE2MiAA: num] i ^UiM Z T'us to see to it t'at "e do not rea&' be#ond t'e arra# si.e is entirel# t'e programmer/s bot'eration and not t'e &ompiler/s E:a6$le# "n #in&le di6en#i"nal a%%a1#: 1: ,rogram to a&&ept values from t'e user and find t'e sum main9: X int a]12^+ n+ i +sumU2M printf9Y6nter t'e si.e of an arra# 9R12:=Y:M s&anf9YCdY+&n:M printf9Y6nter elementsY:M for9iU2MiRnMiAA: X s&anf9YCdY+ &a]i^:M sum AU a]i^M Z printf9Yt'e sum of t'e given numbers is=CdY+ sum:M Z
4 35 4

2: ,rogram to a&&ept mar(s of E different subTe&ts and &al&ulates t'e total and average main9: X int mar(s]E^M int totalM float avgM int iM printf9Nenter t'e mar(sO:M for9iU2MiREMiAA: X s&anf9NCdO+ &mar(s] i ^:M Z totalU2M for9iU2MiREMiAA: X total U total Amar(s] i ^M Z avg U total - EM printf9NCd CdO+ total+avg:M Z T'e important logi& &on&epts to be (no"n in arra#s are sorting and sear&'ing T"o dimensional arra#s= !n t'e above sessions "e 'ad gone t'roug' one7dimensional arra#s !t is also possible for arra# to 'ave t"o or more dimensions T'e t"o dimensional arra# is also &alled a matri3 Decla%a!i"n "f !2"Fdi6en#i"nal La%ia<le: T'e de&laration of a t"o dimensional variable is similar to a one7dimensional variable+ but t'e onl# addition is ant'er dimension 5o" "e &an define a t"o dimensional arra# to be as a &olle&tion of single dimensional arra#s T'e general s#nta3 is Da!aF!1$e a%%a1Fna6eM%"2Q#i+eNMc"lQ#i+eN

Ini!iali+a!i"n and a##i&nin& Lalue# !" !2"Fdi6en#i"nal a%%a1 La%ia<le#: T'e initiali.ation and assignment of values to t'ese arra# variables &an be done b# t'ree "a#s 1: !nitiali.ation at t'e time of de&laration 2: Assignment after de&laration of variable "it' t'eir inde3 values @: Assignment of values as per users re0uirement using standard input and output statements
4 36 4

. Ini!iali+a!i"n a! !'e !i6e "f decla%a!i"n: T'e initiali.ation of arra# elements is t'e same "a# as #ou initiali.e a one dimensional variable but onl# #ou 'ave to ma(e a blo&( of elements pre&eding and su&&eeding "it' bra&es T'e general s#nta3 for t'is is !1$e a%%a1Fna6e M #i+e N M #i+e N G ; li#! "f Lalue#>8 8ere is an e3ample to demonstrate t'e initiali.ation of arra# variable in! aM3NM3N G ;3*O*@*->8 T'e values &an also be initiali.ed as ro" b# ro" 'ere is an e3ample to demonstrate t'e initiali.ation in ro" b# ro" met'od in! aM3NM3N G ; ;3*O>*;@*-> >8 Commas are re0uired after ea&' bra&e t'at &loses off a ro" e3&ept in t'e &ase of last ro" 63ample= main9: X int a]2^]2^UX 1+2+?+@+Z+ i+ T M for9iU2MiR2MiAA: for9TU2MTR2MTAA: printf9Y T'e value stored in a]Cd^]Cd^ UCd PnY+i+ T+ a]i^]T^ :M Z *utput= T'e value stored in a ]2^]2^ U 1 T'e value stored in a ]2^]1^ U 2 T'e value stored in a ]1^]2^ U ? T'e value stored in a ]1^]1^ U @ 3 A##i&n6en! af!e% decla%a!i"n "f La%ia<le 2i!' !'ei% inde: Lalue# Using t'eir inde3 values &an do t'e assignment of arra# elements to t'e arra# variable !n general Va%ia<leFna6eM%"2Qinde:n"NM c"lQinde:n"N G Lalue 4or e3ample if #ou "ant to initiali.e a value to an arra# variable do as follo"s number]2^]2^U12 number]2^]1^U11 number]1^]2^U12
4 3& 4

number]1^]1^U1? 4 A##i&n6en! "f Lalue# a# $e% u#e%# %ePui%e6en!: Using standard input and output statements+ t'e user &an be able to assign t'e values to t'e arra# variable To assign t'e elements or printing out t'e elements in t'is met'od at least t"o loops are re0uired+ one for t'e ro" and ot'er for &olumn main9: X int num]?^]?^ + i +T M printf9Y 6nter elements into t'e arra#Y:M for9iU2MiR?MiAA: for9TU2MTR?MTAA: s&anf9YCd Y+ &num]i^]T^:M for9iU2MiR?MiAA: for9TU2MTR?MTAA: printf9YT'e value stored in num]Cd^]CdZ UCd PnY+ i+ T+num]i^]T^:M Z T'e position of elements in t'e form of inde3es &an be referred as 92+2:+92+1:+92+2:\ and so on >'ere first &o7ordinate refers to ro" number and se&ond &o7ordinate refers &olumn number li(e .erot' ro" .erot' &olumn+ .erot' ro" first &olumn+ .erot' ro" se&ond &olumn+ \ and so on 63amples= ,rog1= to find t'e sum of elements of a matri3 of ? K ? si.e main9: X int a]?^ ]?^+ i +T+ sumU2 M printf9Y 6nter elements into t'e arra#Y:M for9iU2MiR?MiAA: for9TU2MTR?MTAA: X s&anf9YCd Y+ &a]i^]T^:M sumAUa]i^]T^M Z printf9Ysum of t'e elements of a matri3 is U CdY+ sum:M Z prog2= find t'e addition of t"o matri&es and print t'e resultant matri3 in matri3 form

4 36 4

main9: X int a]?^]?^ + b]?^]?^+ &]?^]?^ M int i+TM printf9Y 6nter elements into t'e arra#Y:M for9iU2MiR?MiAA: for9TU2MTR?MTAA: s&anf9YCd Y+ &a]i^]T^:M for9iU2MiR?MiAA: for9TU2MTR?MTAA: s&anf9YCd Y+ &b]i^]T^:M for9iU2MiR?MiAA: for9TU2MTR?MTAA: &]i^]T^Ua]i^]T^:Ab]i^]T^ M printf9Yt'e resultant matri3 is=Y:M for9iU2MiR?MiAA: X for9TU2MTR?MTAA: X printf9Y CdPtY+ &]i^]T^:M Z printf9YPnY:M Z Z 63er&ise= 1: 2: ?: @: E: 1: 7: 12: 1?: 1@: >rite a CIprogram to add t'e elements of an arra# >rite a C7program to insert an element into an arra# >rite a C7program to delete an element from an arra# >rite a C7program to &op# all elements of one arra# into anot'er !n an arra# of elements+ some elements are repeated for more t'an t"i&e >rite a C7program to &op# elements t'at are not dupli&ated into a ne" arra# >rite a C7program to displa# t'e addition of t"o matri&es >rite a C7program to displa# t'e subtra&tion of t"o matri&es >rite a C7program for multipli&ation of matri3 "it' an integer number >rite a C7program for multipli&ation of t"o matri&es >rite a C7program to displa# t'e transpose of a matri3

S!%in&#

4 39 4

!n t'e previous &'apter #ou learnt 'o" to define arra#s of different si.es and dimensions+ 'o" to initiali.e arra#s et& + >it' t'is (no"ledge #ou s'ould be read# to 'andle &'ara&ter arra#s T'e "a# a group of integers &an be stored in an integer arra#+ similarl# a group of &'ara&ters &an be stored in a &'ara&ter arra# C'ara&ter arra#s are often &alled as #!%in&# C'ara&ter arra#s or strings are t'e data t#pes used b# t'e programming languages to manipulate te3t su&' as "ords and senten&es Decla%in& and ini!iali+in& #!%in& La%ia<le#: A string variable is li(e an ordinar# variable and is al"a#s de&lared as an arra# T'e general s#nta3 to de&lare a string variable is c'a% #!%in&Fna6eM#i+eN8 t'e si.e in a &'ara&ter string represents t'e number of &'ara&ters t'at a &'ara&ter string &an 'old 6a&' &'ara&ter of t'e string &an be treated as an element of t'e arra# name and is stored in t'e memor# A string &onstant is a one7dimensional arra# of &'ara&ters terminated b# a null 9LP2/: &'ara&ter 6g= &'ar name]12^ U XL!/+/5/+/$/+/!/+/A/+/5/+/P2/ZM 6a&' &'ara&ter in t'e arra# o&&upies one b#te of memor# and t'e last &'ara&ter in t'e arra# is al"a#s LP2/ T'e null9LP2/: &'ara&ter loo(s li(e t"o &'ara&ter but is a&tuall# one &'ara&ter "it' P indi&ating t'at "'at t'at follo"s is somet'ing spe&ial 5ot t'at t'e elements of t'e &'ara&ter arra# are stored in &ontiguous memor# allo&ation T'e terminating null9LP2/: is important be&ause it is t'e onl# "a# t'e fun&tion t'at "or( "it' a string &an (no" "'ere t'e string ends !n fa&t a string not terminated b# a 9LP2/: is not reall# a string but merel# a &olle&tion of &'ara&ters Ini!iali+in& !'e #!%in& La%ia<le#: C &on&edes t'e fa&t t'at #ou "ould use strings ver# often and 'en&e provides a s'ort&ut for initiali.ing strings 4or e3ample t'e string used above &an be initiali.ed as 6g= &'ar name]12^ U O!5$!A5OM 5ote t'at in t'is de&laration LP2/ is not ne&essar# C inserts t'e null &'ara&ter automati&all# C also permits to initiali.e a &'ara&ter arra# "it'out si.e also+ in su&' &ases t'e lengt' of string "ill be t'e a&tual si.e of t'e arra# 6g= &'ar name]^ U N!5$!A5OM A##i&n6en! "f #!%in& c"n#!an!# !" a #!%in& La%ia<le: T'e assignment of string &onstant to a string &an be done eit'er b# using str&p# 9dest+ sour&e: of #!%in&/' 'eader file or reading-"riting from t'e terminal "it' t'e 'elp of printf9: and s&anf9: fun&tions T'e input fun&tion s&anf9: is used to read t'e data from t'e
4 70 4

&onsole and t'e output fun&tion printf9: to "rite t'e data to t'e &onsole "it' t'e 'elp of t#pe spe&ifier Cs T'e general s#nta3 for using Cs is as follo"s YCsY 8ere are t'e e3amples to e3plain about strings= "'ile reading t'e sting data t'e '&' sign is not re0uired before t'e variable name be&ause t'e name of t'e &'ara&ter string 'olds t'e base address of t'e string 63ample2= main9: X &'ar name]12^M printf9Yenter a name=Y: s&anf9YCsY+name:M printf9Y t'e nameUCsY+name:M Z To s&an a string of multiple "ords + s&anf fun&tion does not "or( >'enever a "'ite spa&e or ne"7line &'ara&ter en&ounters+ s&anf inserts t'e 5ULL &'ara&ter So+ t'e string terminates at t'at point i e end of string T'at is t'e reason+ "e ma(e use of s&anf fun&tion for t'e input of onl# one "ord !f "e "ant to provide a string "it' spa&es t'en ma(e use of t'e follo"ing fun&tions= &e!#( and $u!#( gets9: fun&tion is used to s&an a string of multiple "ords and puts9: fun&tion is used to displa# a string+ T'e general form of gets9: and puts9: as= gets9strname:M puts9string7&onst-strname:M 'ere + no formats are allo"ed+ li(e Cd+ Cs 63ample?= main9: X &'ar str1]12^M puts9Yenter a name "it'out spa&es =Y:M gets9str1:M puts9Y t'e name is=O:M puts9str1:M puts9Yenter a name "it' spa&es =Y:M gets9str1:M puts9Y t'e name in Y:M puts9str1:M Z Acce##in& !'e c'a%ac!e%# "f a #!%in&:
4 71 4

6a&' &'ara&ter of a string &an be a&&essed "it' its inde3 value T'e follo"ing e3ample e3plains about t'is 63ample @= main9: X int iM &'ar name]12^M printf9Yenter a name=Y: s&anf9YCsY+name:M for9iU2Mname]i^VU'P2'MiAA: printf9Y t'e &'ara&ter in name]Cd^ UC&PnY+name]i^:M Z 63ample E= >rite a C7program to find t'e lengt' of a string main9: X &'ar string]12^M int iM printf9Yenter a string=Y:M s&anf9YCsY+ string:M for9iU2Mstring]i^VU'P2'MiAA:M printf9Yt'e lengt' of string is CdY+ i:M Z 63ample 1= >rite a program to &op# a string to anot'er string main9: X &'ar string1]12^+ string2]12^M int iM printf9Yenter a string in lo"er &ase=Y:M gets9string1:M for9iU2Mstring1]i^VUP2MiAA: string2]i^ Ustring1]i^M string2]i^U'P2'M printf9YT'e &opied string is U CsY+string2:M Z 63ample 9= >rite a program to &onvert a lo"er &ase string to upper &ase main9: X
4 7. 4

&'ar name]12^M int iM printf9Yenter a string in lo"er &ase=Y:M gets9name:M for9iU2Mname]i^VUP2MiAA: name]i^7U?2M printf9YCsY+name:M Z 63ample12= >rite a program to &on&at a string to anot'er string main9: X &'ar string1]12^+ string2]12^M int i+TM printf9Yenter a string in lo"er &ase=Y:M gets9string1:M for9iU2Mstring1]i^VUP2MiAA:M string1]i^U' 'M for9TU2Mstring2]T^ VU 'P2'MTAA: string1]iATA1^ Ustring2]T^M string2]iATA1^U'P2'M printf9YT'e &on&atenated string is U CsY+string1:M Z C"6$a%i#"n "f !2" #!%in&#: C does not permit to &ompare t"o strings dire&tl# Statement li(e string1UUstring2 is not valid !f #ou "ant to &ompare t"o strings t'en t'e &omparison is done &'ara&ter b# &'ara&ter T'e &omparison "ill be &arried out in a loop "it' &ondition until t'ere is a mismat&' of &'ara&ter or an# of t'e strings ma# terminate to null &'ara&ter 8ere is an e3ample t'at e3plains about it 63ample 11= main9: X &'ar str1]12^+str2]12^ int iM printf9Yenter first string:M s&anf9YCsY+str1:M printf9Yenter se&ond string:M s&anf9YCsY+str2:M iU2M "'ile99str1]iAA^UUstr2]i^: && str1]i^VU'P2' && str2]i^ VU'P2': iAAM if9str1]i^UU'P2' && str2]i^UU'P2':
4 73 4

printf9YBot' are 60ualY:M else printf9YBot' are not 60ualY:M Z T'ere is fun&tion in string ' 'eader file "'i&' 'elps to &ompares t"o strings i e str&mp9: T'is fun&tion returns an integer value+ "'i&' is t'e differen&e bet"een t'e ASC!! values of differed &'ara&ters of t"o strings !f t'e differen&es bet"een &'ara&ters of first string and se&ond string is t'at of positive+ t'en t'e first string is greater t'an se&ond one !f t'e differen&es bet"een &'ara&ters of first string and se&ond string is t'at of negative+ t'en t'e first string is less t'an se&ond one !f t'e differen&e bet"een &'ara&ters of first string and se&ond string is t'at of .ero+ t'en bot' t'e strings are e0ual T'e general s#nta3 for t'is fun&tion is #!%c6$(#!%in&.*#!%in&3 63ample for str&mp9: main9: X &'ar str1]12^+str2]12^ int iM printf9Yenter first string:M s&anf9YCsY+str1:M printf9Yenter se&ond string:M s&anf9YCsY+str2:M if9str&mp9str1+str2:UU2: printf9YBot' are 60ualY:M else if9str&mp9str1+str2:S2: printf9Ystr1 is greater t'an str2Y:M else printf9Ystr1 is less t'an str2Y:M Z Readin& a line "f !e:!: To read a line of te3t from t'e terminal get&'ar9: fun&tion is used T'is fun&tion reads &'ara&ter b# &'ara&ter from t'e &onsole T'is fun&tion is used repeatedl# to read t'e &'ara&ters from t'e &onsole and pla&e t'em into a &'ara&ter arra# T'e reading is terminated "'enever 'Pn' is en&ountered

63ample= main9: X &'ar line]E2^+&'M int iU2M


4 77 4

printf9Yenter t'e line of te3t and press return at t'e end=Y:M do X &' U get&'ar9:M line]i^U&'M iAAM Z"'ile9&'VU'P2':M i 7 7M line]i^U'P2'M printf9Yt'e entered line is U CsY+ line:M Z

T2"Fdi6en#i"nal #!%in& a%%a1#: A list of names is treated as a table of strings >'enever it is ne&essar# to store multiple names "it' onl# one variable name+ it is ne&essar# to de&lare t'e variable as t"o7 dimensional arra# T'e de&laration is li(e an integer arra# Da!aFT1$e La%ia<leFna6eMinde:.NMinde:3N !n t'e above s#nta3 inde31 indi&ates t'e number of students and inde32 indi&ates t'e lengt' of ea&' string 4or e3ample if t'e variable is de&lared as na6eMONM3,N t'en it indi&ates t'at t'e variable name &an be able to 'old E names "it' a lengt' of 22 &'ara&ters ea&' Ini!iali+a!i"n "f !2"Fdi6en#i"nal #!%in& La%ia<le: T'is &an be done as follo"s= !1$e La%ia<leFna6eM NM NG;R#!%in&F.R*R#!%in&F3R*(* R#!%in&FnR>8 e3ample= &'ar &it#] ^] ^UXY)U5TU%Y+YF!_A)Y+8[$6%ABA$YZM To a&&ess t'e name of &it# at i!' lo&ation a&&ess t'at "it' its inde3 value i e if "ant to a&&ess t'e &it# 8[$6%ABA$ in t'e arra# t'en a&&ess it "it' its inde3 &it# ]2^ *n&e an arra# is de&lared as t"o7dimensional arra#+ it &an be a&&essed li(e a one7dimensional arra# in furt'er manipulations ,rogram for sorting of names main9: X &'ar string]12^]22^+temp]22^M int i + T +nM printf9Yenter number of names #ou "ant to enter9R12:=Y:M s&anf9YCdY+&n:M
4 75 4

printf9Yenter t'e names=Y:M for9iU2MiRnMiAA: s&anf9YCsY+ name]i^:M -B ,ro&ess for sorting of names Bfor9iU2M iRn71M iAA: for9TUiA1M TRnM TAA: if9str&mp9name]i^+name]T^:S2: X str&p#9temp + name]i^:M str&p#9name]i^+name]T^:M str&p#9name]T^+temp:M Z for9iU2MiRnMiAA: printf9YCsY+ name]i^:M Z Librar# 4un&tions for 'andling String= 4un&tion meaning strlen 4inds lengt' of a string strl"r Converts a string to lo"er&ase strupr Converts a string to upper&ase str&at Appends one string at t'e end of anot'er str&p# Copies a string into anot'er str&mp Compares t"o strings strrev %everses t'e string main9: X &'ar str1]22^+str2]12^M printf9Yenter first string less t'an 12 &'ara&ters=Y:M s&anf9YCsY+str1:M printf9Yenter se&ond string less t'an 12 &'ara&ters=Y :M s&anf9YCsY+str2:M str&at9str1+Y Y:M printf9Y T'e string str1 after &on&at "it' a "'ite spa&e U CsBY+ str1:M str&at9str1+str2:M printf9Y T'e string str1 after &on&at "it' str2 U CsY+ str1:M Z
4 76 4

*utput= enter first string less t'an 12 &'ara&ters= `o'n enter se&ond string less t'an 12 &'ara&ters= Travolta T'e string str1 after &on&at "it' a "'ite spa&e U `o'n B T'e string str1 after &on&at "it' str2 U `o'n Travolta E:e%ci#e: A%%A[S= 1: 2: ?: @: E: >rite a C7program to displa# t'e reversed string >rite a C7program to &'e&( t'e given string is a palindrome or notD >rite a C7program to reverse t'e &ase of a string9from lo"er to upper or vi&e versa: >rite a C7program to displa# t'e number of vo"els present in a given string >rite a C7program to displa# t'e number of vo"els+ t'e number of "ords+ number of lines and "'ite spa&es in a given line of te3t 1: >rite a program to enter values in a single dimensional arra# and &ount t'e number of even or odd numbers enteredD 7: >rite a program to find t'e greatest among 12 numbers in an arra#D J: >rite a program to enter t'e values in a single dimensional and sort it in as&ending orderD 9: >rite a program to implement matri3 additionD]'int = use a t"o dimensional arra#^ 12:>rite a program to implement matri3 multipli&ation D]'int = t'e first ro" of t'e first matri3 is multiplied b# t'e first &olumn of t'e se&ond matri3 and use a t"o dimensional arra#^

C'a$!e% O 4un&tions A fun&tion is a self7&ontained blo&( of statements t'at perform a &o'erent tas( of same (ind 6ver# C program &an be t'oug't of as a &olle&tion of t'ese fun&tions Till no" #ou 'ave alread# seen t'e fun&tions li(e printf9:+ s&anf9: !n C if an# "ord is follo"ing "it' a pair of parent'esis +t'en it is a fun&tion C fun&tions are &lassified into t"o &ategories= librar# fun&tions and user defined fun&tions Librar# fun&tions are t'e fun&tions t'at are defined in t'e 'eader files >e "ill see about t'e user7defined fun&tion+ t'en "e "ill go for t'e librar# fun&tions !n order to use an user defined fun&tion+ first of all "e s'ould define t'e fun&tion+ t'en "e 'ave to &all t'e fun&tion in order to e3e&ute it So+ in order to use a fun&tion "e are 'aving t'ree maTor part = fun&tion definition fun&tion &alling fun&tion de&laration "e "ill see t'e fun&tion de&laration later in t'is &'apter first "e "ill see ot'er t"o T'e general form for defining an user defined fun&tion is as= fun&tion7name9arg1+arg2+arg?:
4 7& 4

t#pe arg1+arg2+arg?M X statement1M statement2M statementnM Z 63ample= main9: X add9:M Z add9: X int a+bM printf9YPnenter a and b =Y:M s&anf9YCdCdY+ &a+ &b :M &UaAbM printf9YCdY+&:M Z 8ere in t'is e3ample+ in main9:+ add is a fun&tion and inside main blo&( after t'e pair of parent'esis semi&olon is appearing so +"'en #ou get a semi&olon after t'e pair of parent'esis+ it is t'e fun&tion &all But after t'e main blo&( after add9: a opening bra&e is available +'ere t'e fun&tion definition starts Let us summari.e "'at "e 'ave learnt so far a: C program is a &olle&tion of one or more fun&tions b: A fun&tion gets &alled "'en t'e fun&tion name is follo"ed b# a semi&olon 4or e3ample+ main9: X argentina9:M Z &:A fun&tion is defined "'en fun&tion name is follo"ed b# a pair of bra&es in "'i&' one or more statements ma# be present 4or e3ample= argentina9: X statement1M statement2M statement?M Z d: An# fun&tion &an be &alled from an# ot'er fun&tion 6ven 6ain( &an be &alled from ot'er fun&tions for e3ample main9: X
4 76 4

message9:M Z message9: X printf9YPn &an/t imagine life "it'out uY:M main9:M Z e: A fun&tion &an be &alled an# number of times 4or e3ample main9: X message9:M message9:M Z message9: X printf9YPn`e"el T'ief VY:M Z f: T'e order in "'i&' t'e fun&tions are defined in a program need not be same in "'i&' t'ose are getting &alled for e3ample main9: X message19:M message29:M Z message29: X printf9YPnBut t'e buffer "as bitterY:M Z message19: X printf9YPn;ar# boug't some butterY:M Z g:A fun&tion &an &all itself Su&' a pro&ess is &alled %ecu%#i"n >e "ill dis&uss t'is aspe&t later ':A fun&tion &an be &alled from ot'er fun&tion + but a fun&tion &annot be defined in anot'er fun&tion T'us t'e follo"ing program "ould be "rong main9: X printf9YPn! am in mainY:M argentina9: X printf9YPn ! am in argentinaY:M Z Z

4 79 4

>'# Use 4un&tions= a: !t redu&es t'e &oding in main 9: to avoid too large and &omple3it# b:!t redu&es t'e &omple3it# of debugging + testing and maintaining &:!t improves t'e repeatabilit# of t'e tas( in t'e programs i e a sub7 program &an be used repeatedl# and b# man# ot'er programs d:!t fa&ilitates modular programming ,assing values bet"een fun&tion= T'is is t'e me&'anism to &onve# information to t'e fun&tion T'is performed b# using t'e YargumentY Till no" "e 'ave used t'e fun&tions li(e printf9: and s&anf9: 'ere t'e formatting string and t'e list of variables used inside t'e parent'eses in t'ese fun&tions are arguments T'e arguments are some time also (no"n as parameters 63ample= main9: X int a+ bM printf9Yenter t'e value of a and b =Y:M s&anf9YCdCdY+ &a+ &b :M add9a+b:M Z add93+#: int 3+#M X int .M .U3A#M printf9Y Cd ACd U CdY+3+#+.:M Z 'ere "e re&eive t'e values of a and b in fun&tion 6ain( t'roug' t'e (e#board and "e "ant to &al&ulate t'e sum of a and b in fun&tion add9: "e must pass t'ese values to add9: !t is being done b# &alling t'e add9: fun&tion as add9a+b:M T'en+ as t'is fun&tion is passing t'e variables +it s'ould be 'eld in some variable "'ile defining so+ "'ile defining "e are using as= add93+#: int 3+#M "% add9int 3+int #: 'ere t'e a+b are (no"n as 'a&tual parameter' and 3+# are (no"n as 'formal parameter' An# number of arguments &an be passed to a fun&tion being &alled 8o"ever+ t'e t#pe+ order and number of a&tual and formal parameters must al"a#s be same

4 50 4

!nstead of using different variable name+ "e &an use same variable name but t'e &ompiler treats t'em as different variables sin&e t'e# are in different fun&tions 4un&tion "it' ret#rn= >'en "e "ant to displa# t'e sum of a and b in fun&tion main9:in t'e above program it is not possible A return statement is t'e me&'anism for returning a value from t'e &alled fun&tion to t'e &alling fun&tion 8ere t'e &alling fun&tion is main9: and &alled fun&tion is add9: so "e s'ould return t'e sum of a and b from add9:fun&tion T'at is a&&omplis'ed b# a return9: statement main9: X int a+ b+&M printf9Yenter t'e value of a and b =Y:M s&anf9YCdCdY+ &a+ &b :M &Uadd9a+b:M printf9Y Cd ACd UCdY+a+b+&:M Z add93+#: int 3+#M X int .M .U3A#M return9.:M Z 'ere t'e return statement serves t"o purpose= a: on e3e&uting t'e return statement t'e &ontrol immediatel# transfers to &alling program b: !t returns t'e value present in t'e parent'eses after return to t'e &alling program !n t'e above program+ t'e sum of t"o numbers is being returned 5ote= t'ere is no restri&tion on 'o" man# return statement "ill be t'ere in a fun&tion+ but a return statement &an return onl# one value at a time %eturn values and t'eir t#pes= All fun&tions b# default returns integer !f t'e fun&tion is of integer return t#pe even de&laration is also not needed but for ot'er return t#pes de&laration is a must A fun&tion ma# send or ma# not send ba&( an# value to t'e &alling fun&tion !f it is returning an# value t'en return statement is must T'e return statement is of an# one t#pe ma# be plain return or ma# be return "it' an e3pression

4 51 4

returnM return9variable:M Calling a fun&tion= A fun&tion is &alled b# using a fun&tion name in a statement A fun&tion+ "'i&' returns value+ &an be used as an e3pression li(e a variable !t &an not be used on t'e rig't 'and side of t'e assignment operator >'ile &alling a fun&tion as an individual statement semi&olon is must at t'e end e3 add9:M main9: X add9:M Z T#pes of fun&tions= A&&ording to t'e presen&e of arguments and returning of values fun&tions are of t'ree t#pes T'e# are fun&tions "it' no arguments and no return values arguments and no return values arguments and return values

n" a%&u6en!# and n" %e!u%n Lalue#: >'en a fun&tion 'as no arguments and t'ere is no return statement t'en t'ere is no data transfer i e no value passes from t'e &alling fun&tion and no value returns from t'e &alled fun&tion 63ample1= main9: X printline9:M -B fun&tion &all BZ printline9: -B fun&tion 'eader BX int iM for9iU2M iRJ2M iAA: printf9Y7Y:M Z T'e above program prints a line of '#p'ens 97: 8ere in t'is fun&tion no argument is passing from t'e &alling fun&tion and no value is returned from t'e &alled fun&tion ba&( to t'e &alling fun&tion Arguments but no return values=
4 5. 4

main9: X int a+ b+ add9:M printf9Yenter a and b values=Y:M s&anf9YCdCdY+ &a+ &b :M add9a+b:M Z add9int 3+int #: X int &M &UaAbM printf9YCdY+&:M Z Arguments "it' return values= main9: X int a+ b+&M printf9Yenter t'e value of a and b =Y:M s&anf9YCdCdY+ &a+ &b :M &Uadd9a+b:M printf9Y Cd ACd UCdY+a+b+&:M Z add93+#: int 3+#M X int .M .U3A#M return9.:M Z !n t'e above e3ample t'e a&tual arguments a+ b are passed to t'e &alled fun&tions as formal arguments 3+ # and t'e addition value of 3 and # are returned ba&( to t'e &alling fun&tion !n t'e &alling fun&tion t'e returned value is stored in t'e variable & for furt'er pro&essing T'e value of & is t'en printed in t'e &alling fun&tion >'en returning non7!nteger values= All fun&tions b# default returns integer !f t'e fun&tion returns of integer t#pe+ t'en fun&tion de&laration is not re0uired As "e 'ave seen till no"+ "'en a fun&tion returns a value of ot'er t#pe t'en t'e return t#pe s'ould be spe&ified and a protot#pe de&laration is re0uired
4 53 4

e3ample = main9: X float a+ b+&M float add9int+int:M-Bprotot#pe de&larationBprintf9Yenter t'e value of a and b =Y:M s&anf9YCfCfY+ &a+ &b :M &Uadd9a+b:M printf9Y Cf ACf UCfY+a+b+&:M Z float add9float 3+float #: -B return t#pe is floatBX float .M .U3A#M return9.:M Z 8ere "e 'ave seen t'e fun&tion de&laration after t'e variable de&laration+ it is also (no"n as protot#pe de&laration T'e protot#pe of t'e fun&tion sa#s t'e &ompiler t'e details of t'e fun&tion li(e t'e return t#pe of t'e fun&tion "'i&' &ome before t'e fun&tion name and t'e arguments t#pes+ "'i&' is spe&ified inside t'e pair of parent'eses !n t'e above e3ample float before add9: at t'e time of fun&tion definition and de&laration represents t'e return t#pe and t'e t#pes inside t'e fun&tion represents t'e t#pes of formal arguments %e&ursive fun&tions= >'en a fun&tion &alls itself t'en t'e fun&tions are &alled as re&ursive fun&tions >'en a fun&tion is &alled li(e t'is t'en t'e e3e&ution "ill &ontinue indefinitel# To terminate t'is indefinite loop a &ondition is re0uired 63ample= main9: X int n+fa&tM int fa&torial9int:M printf9Yenter a number to find fa&torial=Y:M s&anf9YCdY+ &n:M fa&t U fa&torial9n:M printf9YPn4a&torial of Cd is CdY+n+fa&t:M Z int fa&torial9int n: X
4 57 4

int fa&tM if9nUU1: return 91:M else fa&t U n B fa&torial9n71:M return 9fa&t:M Z T'e & fun&tions &an be &lassified into t"o t#pes = &all b# value &all b# referen&e Till no" "'ile &alling a fun&tion+ "e "ere passing t'e values of t'e variables as t'e arguments So+ all t'e above programs in "'i&' "e are &alling a fun&tion b# passing t'e variables are not'ing but e3amples of &all b# value >'en "e "ill be in need of returning t"o or more values it is not possible in t'e &all b# value met'od !f "e "ill a&&ess a variable "it' its address and "e are &'anging t'e value of it t'roug' t'e address+ t'en "e "ill be able to a&&omplis' t'e previous tas( for t'is "e need to pass t'e address "'ile &alling t'e fun&tion and t'is te&'ni0ue is (no"n as &all b# referen&e 63ample= -Bs"apping t'e values of t"o variablesBmain9: X int a+b+&M printf9YPn 6nter a & b=Y:M s&anf9YCdCd'+&a+&b:M s"ap9a+b:M -BCALL B[ FALU6Bprintf9Y PnaUCd bUCdY+a+b:M Z s"ap9int a+int b: X int &M &UaM aUbM bU&M Z 'ere even t'oug' "e are &'anging t'e values of t'e variables in fun&tion s"ap9: +it "ill not affe&t t'e values of a and b in main9: >e &an do t'is as= >8AT !S A ,*!5T6%= As #ou (no" t'e memor# of t'e &omputer is divided into bit and b#tes 6a&' b#te is numbered beginning "it' b#te 2 T'e number of ea&' b#te is &alled t'e address and t'e address is said to point to a parti&ular b#te A pointer t'en is simpl# t'e address of a b#te in t'e &omputer/s memor#
4 55 4

T'e C programming language allo"s #ou define variables &apable of storing pointers T'e language also provides operators t'at &an be used to a&&ess and manipulate pointers THE S AND T OPERATOR: Consider t'e de&laration int i U 9M T'is de&laration tells t'e C &ompiler to = i: %eserve spa&e in memor# to 'old t'e integer value ii: Asso&iates t'e name L i L "it' t'is memor# lo&ation iii: Store t'e value 9 at t'is lo&ation >e ma# represent iB# lo&ation in t'e memor# b# t'e follo"ing memor# map

>e see t'at t'e &omputer 'as sele&ted memor# lo&ation 1@92 as t'e pla&e to store t'e value 9 T'e lo&ation number 1@92 is not a number to be relied upon some ot'er time t'e &omputer ma# &'oose a different lo&ation for a storing t'e value 9 T'e important point is iB# address in memor# is a number and ever# time a variable is de&lared of an# t#pe an appropriate amount of memor# is given to ea&' and ever# and a uni0ue address >e &an printf t'is address number t'roug' t'e follo"ing program main9: X int i U 9M printf9NAddress of i U CdPnO+&i:M printf9Nvalue of i U CdPnO+ i:M Z T'e output of t'e above program "ould be Address of i U 1@92 Falue of i U 9M Loo( at t'e first printf9: statement &arefull# L&/ is used in t'is statement is C/s address operator T'e e3pression &i returns t'e address of t'e variable i+ "'i&' in t'is &ase 'appens to be 1@92 >e 'ave been using t'e & operator in t'e s&anf9: statement

4 56 4

T'e ot'er pointer operator present in C language is LB/ &alled t'e value at address operator !t gives t'e value stored at a parti&ular address T'e value at address operator is also &alled t'e indire&tion operator *bserve &arefull# t'e output of t'e follo"ing program main9: X int i U 9M printf9NAddress of i U CdPnN+&i:M printf9NFalue of i U CdPnN+i:M printf9NFalue of i U CdPnN+ B9&i::M Z T'e output of t'e above program "ould be= Address of i U 1@92 Falue of i U 9 Falue of i U 9 5ote t'at printing t'e value of B9&i: is same as printing t'e value of i -B s"apping t'e values of t"o variables Bmain9: X int a+b+&M printf9YPn 6nter a & b=Y:M s&anf9YCdCd'+&a+&b:M s"ap9&a+&b:M -BCALL B[ %646%65C6Bprintf9Y PnaUCd bUCdY+a+b:M Z s"ap9int Ba+int Bb: X int &M & U BaM Ba U BbM Bb U &M Z 8ere "e are passing t'e addresses of variables a and b+ "'ile &alling t'e fun&tion s"ap9: in main9: !n s"ap9: "e are a&&essing t'e variables t'roug' t'e pointers+ so t'e value at t'e address "ill be s"apped T'is above te&'ni0ue is (no"n as &all b# referen&e 63er&ise= 4U5CT!*5S= 1 >rite a program to add t"o numbers using a fun&tionD
4 5& 4

2 >rite a fun&tion to &'e&( "'et'er a given number is even or oddD ? >rite a program to a&&ept 3+# and &ompute 3 raised to # using a fun&tion po"er "'i&' returns t'e resultD @ >rite a fun&tion "'i&' a&&epts a number and find "'et'er t'e number is prime or notD E >rite a fun&tion to find t'e fa&torial of a numberD] 'int = EV U EB@B?B2B1 U122^

C'apter 1 Da!a T1$e# and C P%e$%"ce##"% Da!a T1$e#: T'e data t#pes "e 'ave seen till no" are primar# t#pes= &'ar+ int and float T'ese are again divided into several t#pes= T#pe Si.e 4ormat %ange signed &'ar 1 C& 712J to A127 unsigned &'ar 1 C& 2 to 2EE signed int 2 Cd 7?271J to A?2717 unsigned int 2 Cu 2 to 1EE?E signed long int @ Cld 721@7@J?1@J to A21@7@J?1@J unsigned long int @ Clu 2 to @29@91729E float @ Cf 7? @e?J to A? @e?J double J Clf 71 7e?2J to A1 7e?2J long double 12 CLf 71 7e@9?2 to A1 7e@9?2 T'ese datat#pes &an be used as previous one's 4or e3ample +"'en #ou "ant not to store an# negative values in an integer variable t'en "e s'ould de&lare t'at variable as unsigned int similarl# +t'e ot'er datat#pes &an be used S!"%a&e Cla##e# in c: Storage &lasses tells us = a: >'ere t'e variable "ould be storedD b: >'at about t'e initial value of t'e variable+ if t'e initial value is not spe&ifiedD &: >'at is t'e s&ope of t'e variableD d: >'at is t'e life of t'e variableD T'ere are four storage &lasses in &= a: automati& storage &lass
4 56 4

b: register storage &lass &: stati& storage &lass d: e3ternal storage &lass Automati& Storage Class Storage $efault initial value S&ope Life 63ample 7memor# 7An unpredi&table value 9garbage value: 7Lo&al to t'e blo&( in "'i&' defined 7Till &ontrol remains "it'in t'e blo&( in "'i&' it is defined

main9: X auto int i+ TM printf9YPn Cd Cd Y+ i+T:M Z 'ere output "ill be some garbage value %egister Storage Class Storage $efault initial value S&ope Life 63ample main9: X register int iM for9i U 2M iR 12 M i U i A 1: printf9YPn Cd Y+ i:M Z 6ven t'oug' "e 'ave de&lared t'e storage &lass of 'i' as register+ "e &an't sa# for sure t'at t'e value of 'i' "ill be stored in a C,U register Be&ause t'e number of C,U registers are limited and t'e# ma# be bus# doing some ot'er tas( T'en+ t'e variables are treated as auto 7C,U register 7An unpredi&table value 9garbage value: 7Lo&al to t'e blo&( in "'i&' defined 7Till &ontrol remains "it'in t'e blo&( in "'i&' it is defined

4 59 4

>e &annot use register storage &lass for all t#pes of variables 4or e3ample T'e follo"ing de&larations are "rong= register float 0M register double aM T'is is be&ause t'e C,U registers in a mi&ro&omputer are usuall# 11bit registers and t'erefore &annot 'old a folat value or double value "'i&' are of si.e more t'an 2b#tes !f "e de&lare also + it "ill not generate an error +it "ill simpl# treat t'ose as auto Stati& Storage Class Storage $efault initial value S&ope Life 63ample= main9: X in&rement9:M in&rement9:M in&rement9:M Z in&rement9: X stati& int numU1M printf9YCdPnY+num:M num U num A1M Z t'e output of t'e above program "ill be = 1 2 ? if t'e storage &lass is stati& t'en t'e statement stati& int numU 1 is e3e&uted onl# on&e+ irrespe&tive of 'o" man# times t'e same fun&tion is &alled 63ternal Storage Class Storage $efault initial value 7memor# 7_ero 7memor# 7_ero 7Lo&al to t'e blo&( in "'i&' defined 7value of variable persists bet"een different fun&tion &alls

4 60 4

S&ope Life

7)lobal 7as long as t'e program's e3e&ution doesn't &ome to an end

63ternal variables differ from t'ose "e 'ave alread# dis&ussed in t'at t'eir s&ope is global+ not lo&al 63ternal variables are de&lared outside all fun&tions+ #et are available to all fun&tions t'at "ant to use t'em 63ample= int num M main9: X printf9Y num U CdY+num:M in&9:M in&9:M de&9: Z in&9: X num UnumA1M printf9YPtnum U CdY+num:M Z de&9: X num Unum71M printf9YPtnumUCdY+num:M Z 'ere t'e output "ill be numU2 numU1 numU2 numU1 'ere num is available to t'e fun&tions in&9: and de&9: as it is de&lared outside all fun&tion and t'e &'anges made are available to all fun&tions 5B= T'e fun&tion t'at uses an e3ternal variable s'ould de&lare t'at variable e3ternal via t'e (e#"ord e:!e%n as s'o"n belo"= e3ample= int 3U21M main9: X e3tern int 3M printf9YPn3UCdY+3:M Z

4 61 4

'ere 3 is an e3ternal variable so t'e output "ill be :G3. but see "'at "ill 'appen in t'e follo"ing program= int 3U21M -B3 is an e3ternal variableBmain9: X int 3M-B3 is lo&al variableBprintf9YPn3UCdY+3:M Z 'ere as t'e e:!e%n (e#"ord is not t'ere in main9: +it treats 3 as anot'er lo&al variable of t#pe auto so t'e output "ill be an garbage value C P%e$%"ce##"%: T'ere are several steps involved from t'e stage of "riting a C program to t'e stage of getting it e3e&uted >'en "e e3e&ute a program prepro&essing+ &ompiling + lin(ing as "ell as e3e&ution of t'e program is done automati&all# T'e prepro&essor offers several features &alled prepro&essor dire&tives 6a&' of t'ese prepro&essor dire&tives begin "it' a a s#mbol T'e dire&tives &an be pla&ed an#"'ere in a program but are most often pla&ed at t'e beginning of a program+ before main9: >e "ould learn t'e follo"ing prepro&essor dire&tives 'ere= 1: ;a&ro e3pansion 2: 4ile in&lusion Mac%" e:$an#i"n 8ere +'ave a loo( at t'e follo"ing program adefine U,,6% 2E main9: X int nM for9nU1MnR U,,6%MnAA: printf9NPnCd N+n:M Z !n t'is program instead of "riting 2E in t'e for loop "e are "riting it in t'e form of U,,6%+ "'i&' 'as alread# been defined before main9: t'orug' t'e statement+ adefine U,,6% 2E T'is statement is (no"n as Lma&ro definition or &ommonl# +Tust a Lma&ro L $uring prepro&essing+ t'e prepro&essor repla&es ever# o&&urren&e of U,,6% in t'e program to 2E

4 6. 4

8ere+ U,,6% is (no"n as Lma&ro templates/ +"'ereas 2E is (no"n as Lma&ro e3pansions/ >'en "e &ompile t'e program +before t'e sour&e &ode passes to t'e &ompiler it is e3amined b t'e C prepro&essor for an# ma&ro definitions >'en it sees t'e #define dire&tive+ it goes t'roug' t'e entire program in sear&' of t'e ma&ro templateM "'enever it finds one +it repla&es t'e ma&ro "it' t'e appropriate ma&ro e3pansion *nl# after t'is pro&edure 'as been &ompleted is t'e program 'anded over to t'e &ompiler 63ample= adefine A5$ && adefine A%A5)6 9aS2E A5$ aR22: main9: X int aU?2M if9A%A5)6: printf9N"it'in rangeO:M else printf9Nout of rangeO:M Z 'ere not'ing but "e are giving a name to t'e L&&/ to A5$ and so on Mac%" 2i!' a%&u6en!# ;a&ros &an 'ave arguments +Tust li(e fun&tions 63ample= adefine A%6A93: 9? 1@B3B3: main9: X float r1U1 2E+r2U2 E+aM aU A%6A9r1:M printf9NPn area of &ir&le is =CfO+a:M aU A%6A9r2:M printf9NPn area of &ir&le is =CfO+a:M Z be &areful not to leave a blan( spa&e bet"een A%6A and 93:+ if #ou "ill do t'is +t'en A%6A "ill be&ome t'e ma&ro template and 93: "ill be&ome t'e ma&ro e3pansion for it File inclu#i"n: T'e se&ond prepro&essor dire&tive is file in&lusion T'is dire&tive &auses one file to be in&luded in anot'er file T'e prepro&essor dire&tive for file in&lusion is=

4 63 4

ain&lude NfilenameO !t simpl# &auses t'e entire &ontent of filena6e to be inserted into t'e sour&e &ode at t'at point in t'e program of &ourse it presumes t'at in&luded file is e3isting A&tuall# "e &an use #include in t"o different "a#s= ain&lude RfilenameS ain&lude NfilenameO T'e meaning of ea&' of t'ese forms is given belo"= ain&lude Ngoto &O T'is &ommand "ould loo( for t'e file &"!"/c in t'e &urrent dire&tor# as "ell as t'e spe&ified list of dire&tories as mentioned in t'e in&lude sear&' pat' t'at mig't 'ave been set up ain&lude Rgoto &S T'is &ommand "ould loo( for t'e file &"!"/c in t'e spe&ified list of dire&tories as mentioned in t'e in&lude sear&' pat'

C'apter 7 ,*!5T6%S >'i&' feature of C do beginners find most diffi&ult to understand D t'e ans"er is eas# = pointers ot'er languages 'ave pointers but fe" use t'em so freel# "it' su&' abandon as C does T'e diffi&ult# beginners 'ave "it' pointers 'as mu&' to "it' t'e terminolog# t'an t'e a&tual &on&ept Some of t'e &on&epts dis&ussed belo" 'ave alread# been dealt "it' to a &ertain e3tent in t'e previous &'apter but inspite of some repetition it/s "ort' "'ile to start off "it' pointers rig't from t'e s&rat&' >8AT !S A ,*!5T6%= As #ou (no" t'e memor# of t'e &omputer is divided into bit and b#tes 6a&' b#te is numbered beginning "it' b#te 2 T'e number of ea&' b#te is &alled t'e address and t'e address is said to point to a parti&ular b#te A pointer t'en is simpl# t'e address of a b#te in t'e &omputer/s memor# T'e C programming language allo"s #ou define variables &apable of storing pointers T'e language also provides operators t'at &an be used to a&&ess and manipulate pointers T86 & A5$ B *,6%AT*%= &onsider t'e de&laration int i U 9M
4 67 4

T'is de&laration tells t'e C &ompiler to = iv: %eserve spa&e in memor# to 'old t'e integer value v: Asso&iates t'e name L i L "it' t'is memor# lo&ation vi: Store t'e value 9 at t'is lo&ation >e ma# represent i/s lo&ation in t'e memor# b# t'e follo"ing memor# map

>e see t'at t'e &omputer 'as sele&ted memor# lo&ation 1@92 as t'e pla&e to store t'e value 9 T'e lo&ation number 1@92 is not a number to be relied upon some ot'er time t'e &omputer ma# &'oose a different lo&ation for a storing t'e value 9 T'e important point is i/s address in memor# is a number and ever# time a variable is de&lared of an# t#pe an appropriate amount of memor# is given to ea&' and ever# and a uni0ue address >e &an printf t'is address number t'roug' t'e follo"ing program main9: X int i U 9M printf9NAddress of i U CdPnO+&i:M printf9Nvalue of i U CdPnO+ i:M Z T'e output of t'e above program "ould be Address of i U 1@92 Falue of i U 9M Loo( at t'e first printf9: statement &arefull# L&/ is used in t'is statement is C/s address operator T'e e3pression &i returns t'e address of t'e variable i+ "'i&' in t'is &ase 'appens to be 1@92 >e 'ave been using t'e & operator in t'e s&anf9: statement T'e ot'er pointer operator present in C language is LB/ &alled t'e value at address operator !t gives t'e value stored at a parti&ular address T'e value at address operator is also &alled t'e indire&tion operator *bserve &arefull# t'e output of t'e follo"ing program main9: X int i U 9M
4 65 4

printf9NAddress of i U CdPnN+&i:M printf9NFalue of i U CdPnN+i:M printf9NFalue of i U CdPnN+ B9&i::M Z T'e output of t'e above program "ould be= Address of i U 1@92 Falue of i U 9 Falue of i U 9 5ote t'at printing t'e value of B9&i: is same as printing t'e value of i ,*!5T6% 6K,%6SS!*5S= Lets us no" see 'o" t'e pointers &an be used in e3pressions and in arit'meti& and &omparison operations ,ointer Assignments >e 'ave seen in t'e previous se&tion t'at t'e e3pression &i returns t'e address of i !f "e so desire t'is address &an be &olle&ted in a variable b# sa#ing + TU &iM But remember t'at T is not an ordinar# variable li(e an# ot'er integer variable but a pointer to integer t#pe of variable !t is a variable "'i&' &ontains t'e address of ot'er variable 9i in t'is &ase: as it/s value Sin&e T is a variable t'e &ompiler must provide it spa&e in memor# *n&e again t'e follo"ing memor# ma "ould be illustrate t'e &ontents of i and T

As #ou &an see i/s value is 9 and T/s value is i/s address But "e &an/t see T in a program "it'out de&laring it And sin&e T is a variable "'i&' &ontains t'e address of i it is de&lared as + int BTM T'is de&laration tells t'e &ompiler t'at T "ill be used to store t'e address of an integer variable 8ere is a program t'at demostrates t'e relations'ips "e 'ave been dis&ussing ;ain9: X int ! U ?M int BTM
4 66 4

TU &!M printf9NAddress of ! UCd PnO+&i:M printf9NAddress of ! U CdPnO+T:M printf9NAddress of ! U CdPnO+&T:M printf9NFalue of T U CdPnO+T:M printf9NFalue of i U CdPnO+i:M printf9NFalue of i U CdPnO+B9&i::M printf9NFalue of i U CdPnO+BT:M Z T'e output of t'e above program "ould be Address of i U 1@92 Address of i U 1@92 Address of T U ?271 Falue of T U 1@92 Falue of i U 9 Falue of i U 9 Falue of i U 9 ,*!5T6% A%!T8;AT!C 8aving learnt t'e basi&s of pointers it/s time to venture into somet'ing more &ompli&ated Let us start of "it' pointer arit'meti& main9: X int i U ?+ B3M float T U1 E+B#M &'ar (U/&/+B.M printf9NFalue of ! U CdPnO+!:M printf9NFalue of T U CfPnO+T:M printf9NFalue of ( U C&PnO+(:M 3 U &!M # U &TM . U &(M printf9N*riginal value in 3 U CdPnO+ 3:M printf9N*riginal value in # U CdPnO+#:M printf9N*rigianl value in . U CdPnO+.:M 3AAM #AAM .AAM

4 6& 4

printf9N5e" value in 3 U CdPnO+3:M printf9N5e" value of # U CdPnO+#:M printf9N5e" value of . U CdPnO+.:M Z Suppose !+T and ( are stored in memor# at address 1221 + 2221 and ?221 and t'e output "ould be Falue of ! U ? Falue of T U 1 E Falue of ( U & *riginal value in 3 U 1221 *riginal value in # U 2221 *riginal value in . U ?221 5e" value of 3 U 122? 5e" value of # U 222E 5e" value of . U ?222 *bserve t'e last t'ree lines of t'e output 122? is original value in 3 plus 2 222E is original value in # plus @ and ?221 is original value in . plus 1 T'is so 'appens be&ause ever# time a pointer is in&remented it points to t'e immediatel# ne3t lo&ation of its t#pe T'at is "'en integer pointer 3 is in&remented it points to an address t"o lo&ations after t'e &urrent lo&ation Sin&e an int is al"a#s 2 b#tes long+ similarl# points to an address @ lo&ation after t'e &urrent lo&ation and . points 1 lo&ation after t'e &urrent lo&ation ,ASS!5) A5 65T!%6 A%%A[ T* A 4U5CT!*5 Let us no" see 'o" to pass an entire arra# to a fun&tion 5ote t'at t'e arra# elements are stored in &ontiguous memor# lo&ation ea&' element o&&up#ing &ertain b#tes of memor# depending on t'e data t#pe t'e arra# is of t'at is ea&' element "ill be of t"o b#tes if it is an integer arra# Consider t'e follo"ing e3ample main9: X int num]^UX1+2+?+@+EZM displa#9&num]2^+E:M Z displa#9int BT +int n: X int i U1M "'ile9i R U n: X printf9Nelement U CdPnO+BT:M
4 66 4

!AAM TAAM-B in&rement pointer to point to ne3t lo&ationBZ Z 8ere displa# 9: fun&tion is used to print out t'e arra# elements 5ote t'at t'e address of t'e .erot' element is being passed to t'e disla#9: fun&tion !t is also ne&essar# to pass t'e total number of elements in t'e arra#+ ot'er"ise t'e displa#9: fun&tion "ould not (no" "'en to terminate t'e "'ile loop Also note t'at t'e address of t'e .erot' element 9man# times &alled t'e base address: &an also be passed b# Tust passing t'e name of t'e arra# T'us t'e follo"ing t"o fun&tion &alls are same= displa#9&num]2^+E:M displa#9num+E:M To pass an &'ara&ter arra# to a fun&tion t'e program &an be re"ritten as follo"s ;ain9: X &'ar name]22^UO& languageOM displa#9name:M -B fun&tion &all &an also be displa#9&name]2^:BZ displa#9&'ar B p: X printf9NCsO+p:M Z A%%A[ *4 ,*!5T6%S= T'e "a# t'ere &an be arra# of &'ara&ters or an arra# of integers similarl# t'ere &an be arra# of pointers Sin&e a pointer variable al"a#s &ontains an address an arra# of pointers "ould be not'ing but a &olle&tion of address All rules t'at appl# to an ordinar# arra# appl# in to t'e arra# of pointers as "ell T'is e3ample "ill 'elp us understand t'e &on&ept main9: X int arr]E^M int i + T + ( + l + mM int i U 27+ TUE@+ ( U 9 + l U 92+ mU @EM int nM arr]2^ U &iM arr]1^ U &TM arr]2^ U &(M arr]?^ U &lM arr]@^ U &mM
4 69 4

for9nU2MnRU@MnAA: printf9NCd N+ B9arr]n^::M Z figureBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB t'e above figure s'o"s t'e &ontents and t'e arrangement of t'at arra# of pointer in memor# An arra# of pointers &an also be used along &'ara&ter t#pes !t is popularl# used for storing several strings in memor# for e3ample

&'ar Bname]^UXNa(s'a#O NsrideviO+ O(alpanaO+ N'emant'O+ NraviO+ Npras'ant'O NraTes'O+ Nsand'#aO ZM !n t'is de&laration name]^ is an arra# of pointers !t &ontains t'e base address of Na(s'a#Ois stored in name]2^ 4igureBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB ,*!5T6%S T* ,*!5T6%S= T'e &on&ept of pointers &an furt'er be e3tended ,ointer "e (no" is a variable "'i&' &ontains address of a variable T'is variable itself &ould be anot'er pointer T'e follo"ing e3ample s'ould ma(e t'is point &lear main9: X int i U 9M int B TM int BB(M TU&iM (U&TM

4 &0 4

printf9NAddress of i N+&i:M printf9NAddress of i N+T:M printf9NAddress of T N+ &T:M printf9NAddress of T N+ (:M printf9NFalue of i CdO+i:M printf9NFalue of i CdO+ B9&i::M printf9NFalue of i CdO+ BT:M printf9NFalue of i CdO+ BB(:M Z T'e output of t'e above program "ould be Address of i U 1@92 Address of i U 1@92 Address of T U 7E?@ Address of T U 7E?@ Falue of i U 9 Falue of i U 9 Falue of i U9 Falue 2f i U 9 4U5CT!*5 %6TU%5!5) ,*!5T6%S= T'e "a# fun&tion return an int float and a double value or an# ot'er data t#pe it &an eve return s pointer 8o"ever to ma(e a fun&tion return a pointer it 'as too be e3pli&itl# mentioned in t'e &alling fun&tion as "all as in t'e fun&tion de&laration T'e follo"ing e3ample 'elps #ou in understanding t'e &on&ept main9: X int BpM int Bfun19:M pUfun19:M printf9NFalue returned CdO+Bp:M Z int B fun19: X int iU22M return9&i:M Z T'e output of t'e above program "ould be Falue returned 22 63er&ise=

4 &1 4

,*!5T6%S= 1 >rite a program to s"ap t'e &ontents of t"o variable using a fun&tionD 2 >rite a program to pass an entire arra# to a fun&tion and displa# t'e &ontents of an arra#D ? >rite a program to pass an entire arra# to a fun&tion and find t'e sum of all t'e values in an arra#D @ >rite a program to &onvert a de&imal number into it/s binar# e0uivalentD ]'int= use arra#s and fun&tions^ E >rite a program to stimulate t'e strcpy() + strcpy(), strcat() and strcmp() fun&tions b# defining user defined fun&tions for t'emD C'apter J ST%UCTU%6 A5$ U5!*5S

>e 'ave seen earlier 'o" ordinar# variables &an 'old one pie&e of information and 'o" arra#s &an 'old a number of pie&es of information Arra#s represent a group of items t'at belong to t'e same data7t#pe To represent a &olle&tion of data items of different data7t#pes "it' a single name "e &an not use arra#s 4or t'is C providing us a data7 t#pe (no"n as stru&ture A stru&ture is not'ing but grouping up of items of different data7t#pes under one name 4or e3ample to &onstru&t a stru&ture li(e 'ouse "e are grouping up various data items li(e &ement+ sand+ bri&(s and so on A stru&ture is a tool for 'andling a group of logi&all# related data items !t is used to represent a set of attributes !t is Tust similar to a re&ord in t'e database Defini!i"n "f #!%uc!u%e: A stru&ture is a template+ "'i&' &reates a format to de&lare stru&ture variables T'ese variables resemble t'e fields of a database 'en&e t'e# are also &alled as field variables T'e# are also termed as stru&ture elements or member elements !t is also termed as a user defined data t#pe 6a&' member ma# belong to different data7t#pe T'e s#nta3 "ill be as follo"s #!%uc! U#!%uc!u%eQna6eH ; !1$e 6e6<e%F.8 !1$e 6e6<e%F38 / / / !1$e 6e6<e%Fn8
4 &. 4

>8 T'e stru&tureHname ma# be of an# valid identifier and is used to de&lare variables t'at are of t'e same stru&ture an#"'ere in t'e program T'e stru&ture must follo" t'e follo"ing s#nta3 rules "'ile defining a stru&ture i: T'e &losing bra&e in t'e stru&ture t#pe de&lared must be follo"ed b# a semi&olon ii: !t is important to understand t'at a stru&ture t#pe de&laration does not tell t'e &ompiler to reserve an# spa&e in memor# iii: Usuall# stru&ture t#pe de&laration appears at t'e top of t'e sour&e &ode file before an# variables or fun&tion are defined 63amples= stru&t emplo#ee X int empnoM &'ar name]1E^M float salar#M ZM stru&t student X int rollnoM &'ar name]1E^M int mar(s]E^M float totalM float avgM ZM !n t'e above e3amples emplo#ee and student are stru&tures %emember until a variable of stru&ture is de&lared no memor# "ill be allo&ated to t'e data members of t'at stru&ture Decla%a!i"n "f #!%uc!u%e La%ia<le: T'e de&laration of stru&ture variables &an be done in 2 "a#s= i: $e&laration of stru&ture variable along "it' t'e stru&ture de&laration ii: $e&laration of stru&ture variable after de&laration of stru&ture using t'e Nstru&tO (e#"ord and t'e stru&ture name . Decla%a!i"n "f #!%uc!u%e La%ia<le al"n& 2i!' !'e #!%uc!u%e decla%a!i"n !n t'is t#pe t'e de&laration of variable &an be done along "it' t'e stru&ture 63ample= stru&t student X int rollnoM &'ar name]1E^M
4 &3 4

int mar(s]E^M float totalM float avgM Zstud1+stud2+stud?M 3 Decla%a!i"n "f #!%uc!u%e La%ia<le af!e% decla%a!i"n "f #!%uc!u%e !n t'is t#pe+ stru&ture variables are de&lared b# &ombining bot' t'e stru&t (e#"ord and stru&ture name stru&t emplo#ee X int empnoM &'ar name]1E^M float salar#M ZM stru&t emplo#ee emp1+emp2+emp?M )enerall# t'e stru&ture de&laration appears at t'e beginning of t'e program file before t'e de&laration of an# variables or fun&tions !t usuall# is defined above main9: and after ma&ro definition !n su&' &ases t'e definition is global and &an be used b# an# fun&tion But t'e de&laration of stru&ture variable ma# be internal or e3ternal depending upon t'e re0uirement of programmer !f t'e variables are de&lared "it'in a fun&tion 6ain( it is lo&al stru&ture variables or if it is de&lared outside of fun&tion it is global stru&ture variables A##i&nin& c"n#!an! Lalue# !" #!%uc!u%e La%ia<le#: T'e &onstant values are assigned to t'e stru&ture variables in a number of "a#s T'e# &an be assigned at t'e time of de&laration of stru&ture variable or after de&laration of variable !f it is at t'e time of de&laration t'en it is not'ing but initiali.ation Sin&e t'ere is one to one &orresponden&e bet"een t'e members and t'eir initiali.ing values t'e values must be provided as per t'e order t'at 'as been de&lared "it'in t'e stru&ture 5*T6= C does not permit t'e initiali.ation of individual stru&ture members "it'in t'e stru&ture sin&e non of t'e elements of t'e stru&ture "ill not get memor# "'en t'e stru&ture is being defined !t must be done onl# along "it' t'e a&tual variables 63ample= !nitiali.ation of stru&ture members at t'e time of variable de&laration "'ile t'e de&laration of stru&ture stru&t emplo#ee X int empnoM
4 &7 4

&'ar name]1E^M float salar#M Z emp U X 121+Y!5$!A5Y+J222 7E:M !nitiali.ation of stru&ture members at t'e time of stru&ture variable de&laration in t'e fun&tion stru&t emplo#ee X int empnoM &'ar name]1E^M float salar#M ZM main9: X stru&t emplo# emp U X 121+Y!5$!A5Y+J222 7E:M

Z Using t'e stati& variable is optional "'ile using A5S! &ompilers ACESSIND STRCCTCRE ELEMENTS 8aving de&lared t'e stru&ture t#pe and t'e stru&ture variables let us see 'o" t'e elements of t'e stru&ture &an be a&&essed !n arra#s "e &an a&&ess individual elements of an arra# using a subs&ript value Stru&ture uses a different s&'eme T'e# use a d"!(/ operator to a&&ess it/s stru&ture elements 6g= emp / empnoM emp / nameM emp / salar#M DiLin& Lalue# !" La%ia<le# af!e% decla%a!i"n: >e &an also assign values to t'e members after de&laration of variable using an operator R/R pronoun&ed as dot operator !t establis'es a lin( "it' t'e data members and stru&ture variable 63ample stru&t emplo#ee X int empnoM &'ar name]1E^M float salar#M ZM
4 &5 4

main9: X stru&t emplo#ee emp M emp / empnoU121M str&p#9emp / name+O!5$!A5O:M emp / salar#UJ222 7EM printf9Y emplo#ee Cd empno =Y+ emp / empno:M printf9Y emplo#ee Cs name =Y+ emp / name:M printf9Y enter emplo#ee Cf salar# =Y emp / salar#:M Z Z 8*> ST%UCTU%6 6L6;65TS A%6 ST*%6$ >'atever be t'e element of a stru&ture t'e# are al"a#s stored in &ontigious memor# lo&ations T'is &an be illustrated b# t'e follo"ing program main9: X stru&t boo( X &'ar name]22^M float pri&eM int pagesM ZM stru&t boo( b1UXN`AFA ,*!5TO+992+722ZM printf9NAddress of name U CdO+ &b1 name:M printf9NAddress of pri&e U CdO+ &b1 pri&e:M printf9NAddress of pages U CdO+ &b1 pages:M Z And t'e output of t'e program "ould be Address of name U 2221 Address of pri&e U 2221 Address of pages U222E A&tuall# t'e stru&ture elements are stored in memor# as s'o"n in t'e figure

4 &6 4

T'e value of t'e stru&ture variable &an be assigned to anot'er stru&ture variable of t'e same t#pe using t'e assignment operator !t is not ne&essar# to &op# t'e stru&ture elements pie&e b# pie&e T'is is s'o"n in t'e follo"ing e3ample stru&t emplo#ee X int empnoM &'ar name]22^M float salar#M ZM main9: X stru&t emplo#ee e1U X121+ N!5$!A5O+J222 7EZM stru&t emplo#ee e2+e?M e2 / empnoU e1/ empnoM str&p#9e2 / name+e1 / name:M e2 / salar#U e1 / salar#M -B&op#ing an entire stru&ture at a timeBe? U e1M printf9NCd Cs CfO+ e1 / empno+ e1 / name+ e1 / salar#:M printf9NCd Cs CfO+ e2 / empno+ e2 / name+ e2 / salar#:M printf9NCd Cs CfO+ e? / empno+ e? / name+ e? / salar#:M Z and t'e output is = 121 !5$!A5 J222 7E 121 !5$!A5 J222 7E 121 !5$!A5 J222 7E T'is &op#ing of all stru&ture elements at one go 'as been possible onl# be&ause t'e stru&ture elements are stored in &ontiguous memor# lo&ations A%%A[ *4 ST%UCTU%6S
4 && 4

>'enever it is re0uired to de&lare a number of variables of similar stru&ture it is better to de&lare arra# variable instead of de&laring ea&' individual variable of a stru&ture T'e general s#nta3 to de&lare an arra# of stru&ture is= #!%uc! #!%uc!u%eQna6e a%%a1 M #i+e N8 T'is defines an arra# t'at &onsists of 'si.e' number elements and ea&' element is defined to be of t#pe stru&ture stru&t emplo#ee X int empnoM &'ar name]1E^M float salar#M ZM stru&t emplo# emp ]E2^M T'is de&lares t'e emp as an arra# of E2 elements Sin&e emp is an arra#+ use t'e usual arra# a&&essing met'ods to a&&ess individual elements and member operator to a&&ess members A&&essing of arra# variable &an be done as follo"s S!%u!u%eFLa%ia<leM#u<#c%i$! La%ia<leN / 6e6<e% La%ia<le 63ample= emp] i ^ / empno emp] i ^ / name emp] i ^ / salar# et&\ stru&t emplo#ee X int empnoM &'ar name]1E^M float salar#M ZM main9: X stru&t emplo#ee emp ]12^M int iM for9iU2MiR12MiAA: X printf9Y enter emplo#ee empno =Y:M s&anf9YCdY+ & emp] i ^ / empno:M
4 &6 4

printf9Y enter emplo#ee name =Y:M s&anf9YCsY+ emp] i ^ / name:M printf9Y enter emplo#ee salar# =Y:M s&anf9YCdY+ & emp] i ^ / salar#:M Z for9iU2MiR12MiAA: X printf9Y emplo#ee empno Cd=Y+ emp] i ^ / empno:M printf9Y emplo#ee name Cs=Y+ emp] i ^ / name:M printf9Y emplo#ee salar# Cf=Y emp] i ^ / salar#:M Z Z

S!%uc!u%e and func!i"n#: . $a##in& #!%uc!u%e ele6en!# a# an a%&u6en! !" a func!i"n/ !n t'is program t'e data member of stru&ture are passed as argument to t'e fun&tion 63ample= stru&t emplo#ee X int empnoM &'ar name]1E^M float salar#M ZM main9: X stru&t emplo#ee empUX121+O!5$!A5O+J222 7EZM displa#9emp / empno + emp / name + emp / salar#:M Z displa#9int no+ &'ar B n+ float sal: X printf9NCd Pn Cs Pn Cf O+ no+ n+ sal:M Z 3 $a##in& en!i%e #!%uc!u%e a# an a%&u6en! !" !'e func!i"n/ !n t'is met'od t'e entire stru&ture is passed as an argument to t'e fun&tion &all and is treated li(e a stru&ture variable in t'e &alled fun&tion Sin&e a &op# of
4 &9 4

stru&ture is passed to t'e &alled fun&tion an# modifi&ations done to t'e formal stru&ture does not refle&t in t'e a&tual 63ample = stru&t emplo#ee X int empnoM &'ar name]1E^M float salar#M ZM main9: X stru&t emplo#ee empM printf9Y enter emplo#ee empno =Y:M s&anf9YCdY+ & emp / empno:M printf9Y enter emplo#ee name =Y:M s&anf9YCsY+ emp / name:M printf9Y enter emplo#ee salar# =Y:M s&anf9YCdY+ & emp / salar#:M displa#9emp:M -Bpassing an entire stru&ture to a fun&tionBZ displa#9stru&t emplo#ee e1: X printf9Y emplo#ee empno printf9Y emplo#ee name printf9Y emplo#ee salar# Z ST%UCTU%6 ,*!5T6%S= T'e "a# "e &an 'ave a pointer pointing to a int or a pointer pointing to a float or a &'ar similarl# "e &an 'ave a pointer pointing to a stru&ture Su&' pointers are (no"n as stru&ture pointers Let us &onsider an e3ample "'i&' demonstrates t'e usage of stru&ture pointer 63ample= stru&t emplo#ee X int empnoM &'ar name]1E^M float salar#M ZM main9: X stru&t emplo#ee empUX121+O!5$!A5O+J222 7EZM stru&t emplo#ee BptrM

Cd=Y+ e1 / empno:M Cs=Y+ e1 / name:M Cf=Y e1 / salar#:M

4 60 4

ptrU&empM printf9Y Cd Cs CfY+ emp / empno+ emp / name+emp / salar#:M printf9Y Cd Cs CfY+ ptr FHempno+ ptr FHme+ ptrFHsalar#:M Z T'e first printf9:is as usual T'e se&ond printf9: 'o"ever is pe&uliar >e &an/t use ptr / name or ptr / empno be&ause ptr is not a stru&ture variable but a pointer to a stru&ture and t'e dot operator re0uires a stru&ture variable on its left !n su&' &ases C provides an operator FH &alled an arro" operator to refer to t'e stru&ture elements Al"a#s remember t'at on t'e left 'and side of t'e V/B Stru&ture operator t'ere must al"a#s be a stru&ture variable "'ereas on to left 'and side of t'e FH operator t'ere must al"a#s be a pointer to a stru&ture T'e arrangement of t'e stru&ture variable and pointer to stru&ture in memor# is s'o"n in t'e figure belo"

ST%UCTU%6 >!T8!5 A ST%UCTU%6= *ne stru&ture &an be nested "it'in anot'er stru&ture Using t'is fa&ilit# &omple3 data &an be &reated follo"ing program s'o"s nested stru&tures at "or( 6g 1 stru&t address X &'ar &it#]2E^M &'ar p'one]7^M int pinM ZM stru&t emplo#ee X &'ar name]2E^M stru&t address eaM ZM
4 61 4

main9: X stru&t emplo#ee empUXNA%5*L$O+ N'#derabadO+ N7122299O+E221ZM printf9Nname UCs p'one CsO+emp / name+ emp / ea / p'one:M printf9N&it# Cs pin CdO+emp / ea / &it#+ emp / ea / pin:M Z 6g 2= stru&t dt X int ddM int mmM int ##M Z stru&t emplo#ee X int empnoM &'ar name]1E^M float salar#M stru&t dt dobM ZM main9: X stru&t emplo#ee empUX121+O!5$!A5O+J222 7E+1+12+2222ZM printf9Y Cd Cs CfY+ emp / empno+ emp / name+ emp / salar#:M printf9N Cd - Cd - Cd N+ emp / dt / dd+ emp / dt / mm+ emp / dt / ##:M Z t'e output of t'e above program "ould be 121 !5$!A5 J222 7E 1-12-2222 5oti&e t'e met'od used to a&&ess t'e elements of a stru&ture t'at ! a part of anot'er stru&ture 8ere t'e dot operator is used t"i&e as in t'e e3pression T'at is emp ea &it# or emp dt dd et&\+ Cni"n#: T'e &on&ept of unions is derived from stru&tures T'e# follo" t'e same s#nta3 of stru&tures T'e maTor differen&e bet"een t'ese is in terms of storage 6a&' and ever# member variables of a stru&ture o&&upies t'e memor# relative to t'eir data t#pes But in unions all t'e members use t'e same memor# lo&ation even t'oug' it ma# &ontain
4 6. 4

different data7t#pes !t 'andles onl# one member at a time be&ause onl# one lo&ation "ill be allo&ated to union variable irrespe&tive of its si.e T'e si.e of lo&ation is t'e largest among t'e members of a union i e if t'e union 'as a float t#pe of variable t'en t'e allo&ation of memor# si.e is @ b#tes $e&laration of union is as follo"s= union tag7name X t#pe member71M t#pe member72M t#pe member7?M 777 777 777 ZM T'e "a# to a&&ess a union variable is same as t'at of a stru&ture variable $uring a&&essing "e must ensure t'at "e are a&&essing t'e &urrentl# stored variable value or notD *t'er"ise it produ&es erroneous output 65U;6%AT6$ $ATA T[,6S T'e enumrated data t#pe gives #ou an opportunit# to invent #our o"n data t#pe and define "'at values t'e variable of t'is data t#pe &an ta(e T'is &an ma(e t'e program listing more readable "'i&' &an be anadvantage "'en a program gets &ompli&ated or "'en more t'an one programmer is "or(ing on it Using enumerated data t#pes one &an redu&e programmer errors As an e3ample one &ould event a data t#pe &alled de$a%!6en! "'i&' &an 'ave different department names e3isting in a perti&ular &ompan#+ li(e a&&ounts+ sales + mar(eting + produ&tion et& + no" a variable belonging to t'is enumerated data t#pe is allo"ed to 'old onl# t'e department names spe&ified in t'is enumerated list as its values T'e format of t'e enumerated data t#pe is similar to t'at of a stru&ture e3&ept for enu6 as t'e (e#"ord "'ile defining it enum department X a&&ounts+sales+mar(eting+produ&tionM ZM enum department deptHnameM Li(e stru&ture tis de&laration 'as t"o parts i: T'e first part de&lares t'e data t#pes and spe&ifies its possible values T'ese values are &alled enumerators ii: T'e se&ond part de&lares variables of t'is data t#pe 5o" t'at "e 'ave de&lared a variable of department t#pe it &an be assigned values as
4 63 4

deptHname U a&&ountsM deptHname U salesM et& + remember "e &annot use values t'at are/nt t'e original de&laration T'us t'e e3pression deptHname U manufa&turingM "ould &ause an error !nternall# t'e &ompiler treats t'e enumerators as integers 6a&' value on t'is list of permissible values &orresponds to an integer starting "it' 2 T'us in our e3ample a&&ounts is stored as 2 + sales is stored as 1+mar(eting as 2 and produ&tion as ? T'is "a# of assigning numbers &an be overridden b# t'e programmer b# initialising t'e enumerators to different integer values as s'o"n belo" enum department X a&&ountsU12+ salesU22+ mar(eting U?2+ produ&tion U @2 ZM enum department deptHnameM 63er&ise= ST%UCTU%6S= 1 >rite a program "'i&' defines a stru&ture &alled student &ontaining roll number + name + mar(s of E subTe&ts + total + average and grade in "'i&' t'e values for roll number +name and mar(s are inputted and total + average and grade are &al&ulatedD 2 %e"rite t'e above program using arra# of stru&turesD ? >rite a program "'i&' defines a stru&ture &alled emplo#ee + enter t'e details for ten su&' emplo#ees and displa# t'e detailsD]'int = use arra# of stru&tures^ @ C'apter 9 4ile !nput-*utput !n real time environment t'e storing of data permanentl# is ver# important to read and manipulate "'enever ne&essar# !t is ne&essar# to store t'e data in form of files eit'er in t'e dis( or in an# ot'er se&ondar# storage devi&es for t'e repetitive use C supports a number of fun&tions to deal "it' basi& file operations "'i&' in&ludes=
4 67 4

1: 2: ?: @: E:

*pening of files >riting to files %eading from files Closing of files %eading of errors during file operations

*pening of a file= *pening of a file establis'es a lin( bet"een t'e program and t'e operating s#stem about "'i&' file "e are going to a&&ess and 'o" T'is lin( bet"een our program and operating s#stem is a stru&ture &alled FILE "'i&' 'as been defined in t'e 'eader file Ystdio 'Y9standard input -output 'eader file: So+ it is al"a#s ne&essar# to in&lude t'is file "'en "e "ill do dis( !-* >'en "e re0uest t'e operating s#stem to open a file +"e get ba&( a pointer to t'e stru&ture FILE/ T'is file stru&ture &ontains t'e information about t'e file being used+ su&' as its &urrent si.e+ its lo&ation in memor# et& general format to open a file= fopen9YfilenameY+ YmodeY:M e3ample= 4!L6 BfpM fpUfopen9Yprg1 &Y+YrY: 'ere fp is a pointer variable + "'i&' &ontains address of t'e stru&ture 4!L6 returned b# fopen9: f"$en( "ill open t'e file Yprg1 &Y in YreadY mode So+ t'at "e &an onl# read t'e &ontents of t'e file T'e mode parameter implies t'e mode of opening a file T'e modes of a file opening &an be an# one of t'e follo"ing= YrY Y"Y YaY YrAY = opens t'e file for reading onl# if t'e file e3ists it opens it

= opens t'e file for "riting onl# if t'e file e3ists &ontents are over"ritten+ if file does not e3ist a ne" file is &reated = opens t'e file for appending at t'e end if t'e file e3ists loads it if file does not e3ist a ne" file is &reated = opens t'e file for reading e3isting+ "riting ne" and modif#ing e3isting if t'e file e3ists it opens it

Y"AY = opens t'e file for "riting ne" &ontents+ reading t'em ba&(+and modif#ing e3isting &ontents if t'e file e3ists &ontents are over"ritten+if file does not e3ist a ne" file is &reated

4 65 4

YaAY

= opens t'e file for reading e3isting &ontents+ appending ne" Cannot modif# e3isting &ontents if t'e file e3ists loads it if file does not e3ist a ne" file is &reated

5 B=

$uring opening if fopen9: is unable to open t'e file t'en it returns a 5ULL

Closing a file= "'ile &losing a file +first if an# &'ara&ters remaining in t'e buffer are "ritten to t'e dis( T'en it frees t'e lin( used b# t'e parti&ular file+ and t'e asso&iated buffers + so t'at t'ses are available for ot'er files T'e s#nta3 for &losing of a file is f&lose9file7pointer:M !nput and *utput operations on files= C provides fun&tions to read and "rite t'e data to t'e file )eneral form of t'ose fun&tions are 1: 2: ?: @: E: 1: fget&9fileptr: = to read a &'ara&ter at a time from t'e file fput&9&'+fileptr: = to "rite a &'ara&ter into file at a time fgets9str+si.e+fileptr: = to read a string at a time from t'e file fputs9str+fileptr: = to "riting a string at a time to t'e file fprintf9fp+YformatY+varlist: ="rites into file fs&anf9fp+YformatY+addr of var:=reads from t'e file into variables

'ere fileptr is t'e 4!L6 pointer+ &' means a &'ara&ter +str means t'e string name or a string T'e general s#nta3 for t'em is= T'e 4!L6 pointer moves b# one &'ara&ter for ever# operation of fget&9: and fput&9: fget&9: fun&tion returns an end7of7 file &'ara&ter 6*4 "'i&' is defined in stdio ' >'en it rea&'es to t'e end of t'e file +it returns 6*4 T'e reading of file s'ould terminate "'en 6*4 is en&ountered 63ample1= program to "rite &'ara&ter datas to t'e file ain&ludeRstdio 'S main9: X 4!L6 Bf1M &'ar &M f1Ufopen9YL6TT6% TKTY+Y"Y:M -Bopening t'e file in "rite mode Bprintf9YPn enter a &'ara&ter ot'er t'an 2 =Y:M fflus'9stdin:M &Uget&'e9:M
4 66 4

"'ile9&VU'2': X fput&9&+f1:M fflus'9stdin:M &Uget&'e9:M Z f&lose9f1:M Z 'ere till #ou "ill not enter a .ero +t'e &'ara&ters "ill be "ritten into t'e file e3ample 2 program to read t'e &'ara&ters from t'e file ain&ludeRstdio 'S main9: X 4!L6 Bf1M &'ar &M f1Ufopen9YL6TT6% TKTY+YrY:M "'ile91: X &Ufget&9f1:M if9&UU6*4: brea(M printf9YC&Y+&:M Z f&lose9f1:M Z e3ample ? "rite strings to t'e file ain&ludeRstdio 'S main9: X 4!L6 BfpM &'ar str]J2^M &lrs&r9:M fpUfopen9Ytest t3tY+Y"Y:M if9fpUU5ULL: X printf9YPnPa Unable to open Y:M e3it9:M Z printf9YPn6nter a string=Y:M "'ile99strlen9gets9str:::S2: X
4 6& 4

-Bopening t'e file in read mode B-

fputs9str+fp:M fputs9YPnY+fp:M printf9YPn6nter a string=Y:M Z f&lose9fp:M -B to t'e read t'e file Tust "ritten opened in read modeBfpUfopen9Ytest t3tY+YrY:M if9fpUU5ULL: X printf9YPnPa Unable to open Y:M e3it9:M Z &lrs&r9:M printf9YPn&ontents of file=PnY:M "'ile9fgets9str+J2+fp:VU5ULL: X printf9YCsY+str:M Z get&'9:M f&lose9fp:M Z Z e3mple of fprintf9: and fs&anf9: fun&tions= T'e fprintf9: and fs&anf9: fun&tions are used to 'andle group of mi3ed data simultaneousl# fs&anf9: fun&tion also returns an end7of7 file mar(er 6*4 T'e reading of file terminates "'en 6*4 is en&ountered T'e follo"ing e3ample illustrates about t'is fun&tions= 63ample= program to "rite t'ree students' data to a data file and reading t'e same data from t'e data file ain&ludeRstdio 'S stru&t student X int rollnoM &'ar name]1E^M ZM main9: X 4!L6 BfpM stru&t student stu]?^M int i+TM
4 66 4

fpUfopen9Ystudent datY+Y"Y:M if9fpUU5ULL: X printf9YPnPa Unable to open Y:M e3it9:M Z for9iU2MiR?MiAA: X printf9YPnenter studentCd's rollno and name=Y+iA1:M s&anf9YCdCsY+&stu]i^ rollno+stu]i^ name:M fprintf9fp+YCdCsPnY+stu]i^ rollno+stu]i^ name:M Z f&lose9fp:M fpUfopen9Ystudent datY+YrY:M if9fpUU5ULL: X printf9YPnPa Unable to open Y:M e3it9:M Z "'ile9fs&anf9fp+ YCdCsY+ &stu]i^ rollno+stu]i^ name: VU6*4: printf9Y rollno=CdPt name=CsY+stu]i^ rollno+stu]i^ name:M Z

Till no" "e "ere using t'e files are in te3t mode 5o" +"e "ill see t'e binar# mode files %andom a&&essing of files= T'e fun&tions t'at "e dealt till no" are for reading and "riting data se0uentiall# 8o"ever it is re0uired to read t'e files randoml# C provides fun&tions additional to t'e previous fun&tions T'ose fun&tions are ftell9:+ fsee(9: and re"ind et& ftell9: fun&tion= T'is fun&tion returns a long integer t'at &orresponds to t'e &urrent pointer position telling t'at it 'ad alread# read n no of b#tes T'e general form of t'is fun&tion is n U ftell9fp:M fsee(9: fun&tion= T'is fun&tion is used to move t'e pointer to a desired lo&ation "it'in a file from t'e referen&e position T'e general form of t'is fun&tion is
4 69 4

fsee(9file7pointer+ offset+ position:M T'e offset refers to t'e long integer and spe&ifies t'e number of positions to be moved !f t'e offset is positive t'e pointer move for"ard and id it is negative t'e pointer moves ba&("ards T'e position refers to an integer and spe&ifies from "'ere it s'ould read !t ta(es an# one of t'e follo"ing values 2 1 2 beginning of t'e file &urrent position of t'e file end of t'e file

Statement ;eaning fsee(9fp+2L+2: )o to t'e beginning of file fsee(9fp+2L+1: Sta# at t'e &urrent position fsee(9fp+2L+2: )o to t'e end of file+ past t'e last &'ara&ter of t'e file fee(9fp+m+2: ;ove to t'e mA1t' b#te position in t'e file from t'e beginning fsee(9fp+m+1: )o for"ard b# m b#tes from t'e &urrent position fsee(9fp+7m+1: )o ba&("ard b# m b#tes from t'e &urrent position fsee(9fp+7m+2: )o ba&("ard b# m b#tes from t'e end of file T'e follo"ing e3ample e3plains about t'ese fun&tions ain&ludeRstdio 'S main9: X 4!L6 BfpM long nM &'ar &M fpUfopen9YramdomY+Y"Y:M "'ile99&Uget&'ar9::VU6*4: X put&9&+fp:M Z printf9Y5o of &'ara&tersUCdPnY+ftell9fp::M f&lose9fp:M fpUfopen9YramdomY+YrY:M nU2LM "'ile9feof9fp:: X fsee(9fp+n+2:M printf9Yposition ofC& is CdPnY+get&9fp:+ftell9fp::M nUnAELM Z printf9YPnY:M
4 90 4

fsee(9fp+71L+2:M do X put&'ar9get&9fp::M Z"'ile9Vfsee(9fp+72L+1::M f&lose9fp:M Z 63ample= t'is is anot'er e3ample "'i&' e3plain about random a&&essing of files ain&ludeRstdio 'S stru&t inventor# X &'ar name]1E^M int numberM float pri&eM int 0uantit#M ZM main9: X stru&t inventor# itemM &'ar filename]12^M &'ar responseM 4!L6 BfpM long nM void append9stru&t inventor# B+4ile B:M printf9Yt#pe file name=Y:M s&anf9YCsY+&filename:M fpUfopen9filename+YaAY:M do X append9&item+fp:M printf9YPnitem Cs appendedPnY+item name:M printf9Y$o #ou "ant to enter anot'er item9#-n:=Y:M s&anf9YC&Y+&response:M Z"'ile9&'VU'n':M nUftell9fp:M f&lose9fp:M fpUfopen9filename+YrY:M do X fs&anf9fp+YCsCdCfCdPnY+item name+&item number+
4 91 4

&item pri&e+ &item 0uantit#::M fprintf9stdout+YCsCdCfCdPnY+item name+item number+ item pri&e+item 0uantit#::M Z"'ile9ftell9fp:Rn:M f&lose9fp:M Z void append9stru&t inventor# Bprodu&t+ 4!L6 Bfptr: X printf9Y6nter a item nameY:M s&anf9YCsY+ &produ&t7Sname:M printf9Y6nter a item numberY:M s&anf9YCdY+ produ&t7Snumber:M printf9Y6nter a item pri&eY:M s&anf9YCfY+ &produ&t7Spri&e:M printf9Y6nter a item 0uantit#Y:M s&anf9YCdY+ &produ&t7S0uantit#:M fprintf9fptr+ YCsPtY+ produ&t7Sname:M fprintf9fptr+ YCdPtY+ produ&t7Snumber:M fprintf9fptr+ YCfPtY+ produ&t7Spri&e:M fprintf9fptr+YCsPnY+ produ&t7S0uantit#:M Z

8andling of errors during file operations= T'e possible errors t'at o&&urs during file operations are 1: %eading t'e file be#ond t'e end of file mar( 2: Tr# to use t'e file t'at is alread# open ?: ;isusing i-o operations on files @: *pening a file "it' an invalid file name E: Tr#ing to a&&ess t'e "rite7prote&te file 1: $evi&e over flo" et& Unfortunatel# C does not an# tools to 'andle t'ese t#pes of error 'andling onl# t'e "a# is to use &onditional statement and to 'andle t'e errors and passing t'e &ontrol using goto statement to 'andle t'e errors "it' suitable messages T'e important fun&tions provided in C to &'e&( t'e errors are given belo" 1: feof9:= T'is fun&tion is used to find t'e end of file &ondition !f t'e reading of file is su&&essful it returns non7.ero integer ot'er"ise .ero 2: ferror9file7pointer:= t'is fun&tion reports t'e status of t'e file during pro&essing !f t'e reading of file is su&&essful it returns non7.ero integer ot'er"ise .ero

4 9. 4

?: !f t'e file is opened su&&essfull# a file pointer is returned else it returns 5ULL pointer

Command line arguments= A &ommand line argument is not'ing but a parameter supplied to t'e program "'en t'e program is invo(ed from t'e &ommand prompt T'e main9: &an ta(e t"o arguments &alled arg& and argv and t'e information t'at &ontained in t'e &ommand line is passed t'roug' t'ese variables to t'e program "'en it is &alled T'e first argument &ounts t'e number of arguments and se&ond one is an argument ve&tor and represents an arra# of &'ara&ter pointer t'at point to t'e &ommand line arguments T'e arra# si.e is e3a&tl# e0ual to t'e value of arg& 8ere is an e3ample to e3plain t'is ain&ludeRstdio 'S main9int arg&+ &'ar Bargv] ^: X int sumU2+ iM for9iU1MiRarg&MiAA: sumAUatoi9argv]i^:M printf9Yt'e sum of arguments isUCdY+sum:M Z 8ere an important point to note is t'at t'e argv al"a#s &onsists of e3e&utable file name 9program file name: as its first argument T'ts t'e reason t'e summing of values are &arried out from argv]1^ "it'in t'e for statement 63er&ise= 1: >rite a program to 'andle a file b# &op#ing t'e te3t from t'e &onsole and print t'em again to t'e &onsole in t'e reverse order 2: >rite a program to input t'e numeri& data to a file Y5U;$ATA $ATY from t'e &onsole and separate t'em as even and odd numbers in separate files Y6F65 $ATY and Y*$$ $ATY ?: A student stru&ture &onsists of rollno+ name age+ 'eig't and "eig't as members >rite a program to read t'e students data and "rite it to a file YSTU$$ATA $ATY @: An emplo#ee stru&ture &onsists of idno+ name+ basi& salar#+ 'ra+ da+ ta and netsal >rite a program to read t'e emplo#ees data and "rite it to t'e file Y6;,$ATA $ATY E: ;odif# t'e emplo#ee data of an emplo#ee basing on idno b# using random a&&essing of t'e file 4!L6S= 1 >rite a program to &op# one file into anot'er D 2 >rite a program to &op# one file into multiple filesD
4 93 4

? >rite a program to &ount t'e number of &'ara&ters + "ords and lines in a fileD @ >rite a program to read a file and displa# t'e &ontents on t'e s&reenD DATA STRCCTCRES !5T%*$UCT!*5 T* $ATA ST%UCTU%6= Da!a #!%uc!u%e :F A logi&al met'od of representing data in memor# using simple and &omple3 data t#pes provided b# t'e languages 9LC/ ,ASCAL+ et&: <no"ledge of data stru&ture is re0uired for people "'o design and develop &omputer programs of an# (ind S#stem soft"are or appli&ation soft"are As #ou 'ave learnt in earlier blo&(s topi&s data are represented b# data values 'eld temporaril# "it'in programs data area or re&orded permanentl# on a file *ften t'e different data values are related to ea&' ot'er To enable programs to ma(e use of t'ese relations'ips t'ese data values must be in an organi.ed form T'is organi.ed &olle&tion of data is &alled a data stru&ture >e ma# t'erefore sa# data represented as $ata stru&ture U organised data A allo"ed operations D1na6ic 6e6"%1 all"ca!i"n !t is a management te&'ni0ue to 'andle t'e memor# in su&' a "a# t'at YAllo&ate t'e spa&e "'enever and 'o" mu&' needed b# t'e programY Till no" "e dealt "it' arra#s of various data7t#pes li(e integers+ floats+ strings and stru&tures 6ver# time "e use to de&lare t'e memor# spa&e at t'e starting of t'e program i e in t'e de&laration 6ven t'oug' "e de&lare a ma3imum si.e of arra# "e ma# not use all t'e memor# resulting t'e "astage Similarl# some times t'e arra# si.e "'at "e fi3ed ma# not suffi&ient or some times it is re0uired to 'ave a gro"able memor# >e &an not &'ange t'e de&laration of memor# often getting into t'e sour&e &ode C is providing some fun&tions to 'andle t'ese problems $#nami& allo&ation means allo&ation of spa&e during run7 time of a program mallo&9:+&allo&9:+ reallo&9: and free9: are t'e fun&tions in stdlib ' and allo& '+ "'i&' are supporting allo&ation of memor# d#nami&all# T'ese are termed as memor# management fun&tions !n t'e above t'ree fun&tions first t"o are used for initial allo&ation of memor# "'ere as t'e reallo& fun&tion modifies t'e previousl# allo&ated memor# and t'e last fun&tion frees t'e memor# alread# allo&ated d#nami&all# All"ca!in& a <l"c= "f 6e6"%1: A blo&( of memor# ma# be allo&ated using t'e mallo& fun&tion T'is fun&tion allo&ates a blo&( of memor# spe&ified and returns a pointer of t#pe void+ "'i&' &an be assigned+ to
4 97 4

an# t#pe of pointer %emember t'at to t#pe7&ast to a pointer data t#pe "'ile assigning to it T'e general s#nta3 is as follo"s $!% G(ca#!F!1$e 6all"c(nT #i+e"f(ca#! !1$e 8 "'ere ptr is a pointer of t#pe &ast7t#pe and n is number of memor# lo&ations re0uired 63amples= int Biptr U 9int B: mallo& 9n B si.eof9int::M &'ar B&ptr U 9&'ar B: mallo& 9n B si.eof9&'ar::M ain&ludeRstdio 'S ain&ludeRallo& 'S main9: X int Ba+ i + nM printf9Yenter t'e si.e of arra#=Y:M s&anf9YCdY+ &n:M aU9int B: mallo& 9n T si.eof9int::M if9aUU5ULL: X printf9Yno spa&e availableY:M e3it91:M Z printf9Yenter t'e elements=Y:M for9iU2MiRnMiAA: s&anf9YCdY+ &a]i^:M printf9Yelements of arra# are=Y:M for9iU2MiRnMiAA: printf9YCdY+a]i^:M Z call"c( T'e general form of &allo& fun&tion is $!% G(ca#!F!1$e call"c(n* #i+e"f(ca#! !1$e 8 T'is fun&tion allo&ates a blo&( of memor# spe&ified and returns a pointer of t#pe void+ "'i&' &an be assigned+ to an# t#pe of pointer %emember t'at to t#pe&ast to a pointer point to t#pe "'ile assigning ;emor# allo&ation in t'e &ase of &allo& is same as t'at of mallo& e3&ept for t'e differen&e in t'e number of arguments t'at is &allo& ta(es t"o arguments "'ere as mallo& ta(es onl# one and t'e initial values stored in t'e &ase of memor# allo&ation "'ile using a &allo& fun&tion is .ero ain&ludeRstdio 'S ain&ludeRallo& 'S main9:
4 95 4

X float Bvalue int i + nM printf9Yenter t'e si.e of arra#=Y:M s&anf9YCdY+ &n:M valueU9float B: &allo& 9n T si.eof9float::M if9valueUU5ULL: X printf9Yno spa&e availableY:M e3it91:M Z printf9Yenter t'e elements=Y:M for9iU2MiRnMiAA: s&anf9YCfY+ &value]i^:M printf9Yelements of arra# are=Y:M for9iU2MiRnMiAA: printf9YCfY+value]i^:M Z Relea#in& "f 6e6"%1: T'e releasing of d#nami&all# allo&ated memor# &an be done "it' t'e 'elp of free fun&tion T'e general s#nta3 for t'is fun&tion is f%ee($"in!e% 8 ain&ludeRstdio 'S ain&ludeRallo& 'S ain&ludeRstring 'S main9: X &'ar BnameM int i + nM nUstrlen9Yrames"arY:M nameU9&'ar B: &allo&9n+si.eof9&'ar::M if9nameUU5ULL: X printf9Yno spa&e availableY:M e3it91:M Z str&p#9name+ Y rames"ar Y:M printf9Yt'e name is =CsY+name:M free9name:M printf9Ymemor# freedY:M Z

4 96 4

W'1 Da!a S!%uc!u%e# ? ? A&&essing-;anipulating data from t'e files demand more of C , U Ls time in terms of !-* operation 9i e + time ta(en to read-"rite information to-from a se&ondar# storage devi&e: Storing information in t'e memor# 9%A;: and a&&essing t'em saves t'e time ta(en for !-* operation t'us speeding up t'e e3e&ution of t'e appli&ation E:a6$le# "f da!a S!%uc!u%e# :F Arra#s+ Lin(7lists+ Binar# Trees+ et& + A%%A[S A5$ T86!% L!;!TAT!*5S 1 2 $iffi&ult in de&iding t'e optimal si.e of an arra# Tedious met'ods of insertion and deletion of information

L!5<7L!STS A &'ain of stru&tures in "'i&' ea&' stru&ture &onsists of data as "ell as pointers "'i&' store t'e address 9lin(: of t'e ne3t logi&al stru&ture in t'e list A$FA5TA)6S *4 L!5<6$ L!ST *F6% A%%A[S=7 1 2 Allo&ation of memor# &an be done as "'en elements are added into t'e lin( list !nsertions and deletions &an be 'andled effi&ientl# "it'out 'aving to restru&ture t'e lin( list

4 9& 4

*,6%AT!*5S ,6%4*%;6$-;A5!,ULAT!*5 *4 L!5< L!ST=7 1 2 ? @ E 1 %epresentation of stru&ture in LC/ Creation-!nsertion of info into lin( list Traversal in t'e lin( list Sear&'ing $eletion ;odifi&ation

%epresentation of Lin( Lest stru&ture in LC/ Stru&t listHtag X int itemHnoM stru&t listHtag Bne3tM ZM 63 =7 122 Start 122 1111 222 item7no ne3t

222 1112 ?22

?22 111? 5ULL

!n t'e above fig >e 'ave &reated a lin( list "'ere ? stru&tures are lin(ed up 5ote t'at t'e member of t'e stru&ture 56KT/ is a pointer "'ose data t#pe is same as t'at of t'e stru&ture ! e + ne3t/ is a stru&ture pointer "'i&' is &apable of 'olding-pointing to anot'er variable of t'e stru&t listHtag t#pe 5e3t is t'e pointer "'i&' is responsible for lin(ing up t'e stru&tures+ t'us &reating t'e lin(ed list T'e last node is t'e onl# node in t'e lin(list "'i&' does not point to an# node ! e + t'e &ontents of t'e pointer 56KT of t'is node is set to 5ULL 95ULL+ i e + a&ts as a flag to indi&ate t'e end of t'e flag
4 96 4

A##u6$!i"n# S N"!a!i"n# u#ed:F 1 An element in t'e lin(ed list in &alled a node 2 A pointer LSTA%T/ of stru&ture t#pe is used "'i&' al"a#s points to t'e starting-first node of t'e lin( list ? A pointer ne" is used to point to t'e node t'at is to be inserted into t'e lin( list @ ;emor# addresses t'at are used in t'e figure at "'i&' t'e nodes are s'o"n to be stored are arbitrar# addresses CREATIONJINSERTION INTO THE LIST Creation of t'e list is basi&all# insertion of a node to an empt# list !f t'e &ontents of t'e STA%T pointer is 5ULL !t implies t'at STA%T does not store t'e address of an# node i e + Creation of t'e list involves &reation of t'e first node of t'e list 1 2 Creating t'e ne" node Storing t'e address of t'e ne" node in STA%T

5o" t'at t'e list e3ists "it' atleast one element+ ne" nodes &an be inserted N"!e: Start "'en de&lared must be initialised to 5ULL INSERTION : 1 T'e ne" node is to be lin(ed to t'e first node

T'is &an be done b# storing t'e address of t'e ne" node in t'e ne3t pointer of t'e first node

4 99 4

i e + ptr 7 S is pointing to t'e first node T'en ptr 7 S ne3t U ne"M Start 122 122 222 1221 5ULL ,tr Start 122 UUS 122 5e3t 1222 5ULL 222 5e" 222

122 1221 222 5e3t

222 1222 5ULL

In#e%!i"n in!" !'e li#! li#! 77777S Ar start of t'e list 77777S !n middle 77777S end of t'e list In#e%!i"n a! S!a%! : Start 122 122 1121 222 E22 5e" node E22 5e" A299 5ULL 222 1122 ?22 ?22 112? 5ULL

Start 122 E22 5e" A299 5ULL 122 1121 222


4 100 4

222 1122 ?22

?22 112? 5ULL

E22 5e" 7S ne3t U Start Start E22 RUUUUUS Start E22 A299 122 122 1121 222 222 1122 ?22 ?22 112? 5ULL U ne"

Let us no" "rite a fun&tion &alled insert 9 : "'i&' "ill &reate t'e &ase of t'e L!ST !S empt# and "ill insert nodes at start of t'e list if t'e list is e3isting a in&lude Rstdio ' S Start list tag X !nt Stru&t ZM stru&t list Htag BStart+ Bne"+ BptrM start U 5ULL M main 9 : X ne" U 9Stru&t list HtagB: mallo& 9si.eof 9Stru&t\ : : M >'ile 9getnode 9 : : X insert 9 : M Z WW WW WW WW WW WW Z itemHno M listHtag Bne3t M

4 101 4

insert 9 : X if 9 start U U 5ULL: -B list is empt# B X start U ne" = -B store t'e address of t'e first node Breturn M - B in STA%T B Z ne"7 S ne3t U Start M start U ne" M return M Z in#e%!i"n in !'e 6iddle "f !'e li#! : F S!a%! 122 222 P%eL ?22 P!%

122 1221 222

222 122@ ?22

?22 1221 @22

@22 1229 5ULL

1E2 122E 1E2 5e" 5ULL

!nserting a node in t'e sorted list bet"een t"o nodes ma(es it ne&essar# for us to (no" t'e addresses of t'ese t"o nodes inorder to establis' t'e lin(s bet"een t'em and t'e ne" node i e + to insert t'e ne" node "it' info 122E 9i: 9ii: a pointer7,tr is to be positioned a t node "it' info 1221 to establis' t'e lin( anot'er pointer7,rev positioned at node "it' info 122@ to establis' t'e t'e lin( bet"een bot'

4 10. 4

,T% and ,%6F &an be positioned at t'eir respe&tive pla&es b# advan&ing ,T% from beginning of t'e list till it rea&'es t'e first node "it' !54* greater t'an t'e !54* to be inserted T'e pointer ,%6F is made to trail ,T% so t'at it points t'e node Tust before ,T% After t'is 'as been done prev 7 S ne3t ne" 7 S ne3t U U ne"M ptrM

"ill insert t'e node in t'e middle of t'e list In#e%!i"n a! !'e end "f !'e li#! To insert t'e node at t'e end of t'e list+ ,T% is positioned at t'e last node b# advan&ing ptr from t'e beginning of t'e list T'is as done till ptr 7S ne3t 'as t'e value 5ULL t'en= ,tr 7 S ne3t U ne"M

"ill add t'e node at t'e end of t'e list 1 Set ptr to start >'ile ptr is not e0ual to 5ULL X print t'e !54* part of t'e node to "'i&' ,T% is pointing to &urrentl# Advan&e t'e pointer ,T%+ so t'at it points to t'e ne3t node Z

4 103 4

63 =7 Traverse 9 : X stru&t listHtag BptrM ptrUstartM "'ile 9ptr: X print f9N T'e item number is CdO+ ptr 7S itemHno:M ptrUptr7S ne3tM Z Z SEARCHIND IN A LIN0 LIST:F 1 2 ? Set ,T% to STA%T !nput t'e itemHno to be sear&'ed >'ile ptr VU5ULL X &ompare t'e item no t'e node ,T% is pointing to &urrentl# >it' t'e given itemHno and if t'e# are t'e same+ brea( out of t'e loop set ,T% to point to t'e ne3t node in t'e list @ $ispla# t'e item e3ists if ,T% 'as not rea&'ed to t'e end of t'e list $ispla# t'e item doesnot e3ists if ,T% 'as rea&'ed to t'e end of t'e list 63 =7 stru&t listHtag Bsear&'9val: int valM X stru&t listHtag BptrM for 9ptrUstartM ptrVU5ULL && str&mp9val ptr 7S itemHno:7S2M ptr Uptr7S ne3t: !f 9V ,tr: -B if ,T% 7S itemHno: U U 2: return 5ULLM if 9str&mp9val ptr 7S itemHno: U U2: return 9ptr: else return 5ULLM Z

4 107 4

DELETION OF NODE FROM THE LIST Similar to insertion of node+ "e &an delete a node = i: ii: iii: start of t'e list middle of t'e list end of t'e list

T'e logi& remains t'e same+ t'e differen&e is to remove t'e node from t'e list 9i e + Brea( t'e lin(s "it' t'e ot'er nodes: and relin( t'e ot'er nodes in t'e list Dele!i"n a! #!a%! "f li#! 1 2 T'e STA%T s'ould point to t'e node ne3t to t'e first node 4ree t'e memor# of t'e node "'i&' 'as been delin(ed from t'e list 9i e + memor# allo&ated d#nami&all# 'as to be given ba&( to t'e poll of memor# b# using t'e free fun&tion e3pli&itl#: STA%T U ptr 7S ne3tM 4ree 9ptr:M Dele!i"n a! 6iddle "f li#! :F 1 2 Traverse t'e list to find t'e !54* to be deleted Sear&' logi& "ritten earlier &an be used to return a pointer+ to t'e node to be deleted T'is pointer "ill be referred as CurrH,tr !n&ase t'e !54* to be deleted e3ists in t'e list+ its &orresponding node "ill 'ave to be seperated from t'e list b# &onne&ting t'e node before it to t'e node after it 8en&e a pointer "ill be referred to as ,%6F

delete 9val: int valM

4 105 4

stru&t listHtag Bptr+ B&urrHptr+ BprevM ptr U startM &urrHptrUstartM prevUstartM "'ile 9&urrHptr && &urrHptr 7SitemHno 7S val: X if 9&urrHptr UU start: X startU&urrHptr7Sne3tM free 9&urrHptr:M brea(M Z if 9&urrHptr 7S itemHno UU val: X prev7S ne3t U &urrHptr7S ne3tM free 9&urrHptr:M brea(M Z prevU&urrHptrM &urrHptrU&urrHptr7Sne3tM Z if 9&urrHptr UU5ULL: print f9N!tem not availableO: Z A C"6$le!e P%"&%a6 a in&lude Rstdio 'S a in&lude Rmallo& 'S adefine S!_6H*4H!T6;H5* E adefine S!_6H*4H!T6;H$6SC 2E stru&t listHtag X &'ar itemHno]S!_6H*4H!T6;H5*^M &'ar itemHdes&]S!_6H*4H!T6;H$6SC^M float rateM int 0t#M stru&t listHtag Bne3tM ZM &'ar givenHitemHno9S!_6H*4H!T6;H5*:+ &'oe&eU/[OM stru&t listHtag BstartU5ULLM

4 106 4

main9 : X C'ar &'U/ L M >'ile 99menu&' VU Le/: && 9menu&' VU L6/:: X s#stem9N&lsO:M print f9NPn 1 $ispla# listO:M print f9NPn 2 Add to t'e listO:M print f9NPn ? $elete from t'e list O:M print f9NPn @ ;odif# listO:M print f9NPn 6 63itO:M print f9NPn 6nter #our &'oi&e = O:M &'Uget&'ar9 : M if 9&' UU/1/: disp9 :M if 9&' UU/2/: &reate Hinsert 9 :M if 9&' UU/?/: delete 9 :M if 9&' UU/@/: modif# 9 :M if 9&' UU/6/: e3it 9 :M Z Z disp 9 : X stru&t listHtag BptrM ptrUstartM "'ile 9ptr: X print f9NPn ! tem number CEO+ ,tr7S itemHno:M print f9NPn ! $es&ription CEO+ ,tr7S itemHdese:M print f9NPn ! %ate C1O+ ,tr7S rate:M print f9NPn ! Quantit# CaO+ ,tr7S 0t#:M ptrUptr7Sne3tM Z Z &reateHinsenrt9 : X stru&t listHtag Bgetnode9 : Bptr+ Bne" BprevM ne"Ugetnode9 :M -B&reate t'e ne" node Bif 9start UU 5ULL: -B L!ST !S 6;,T[ B-

4 10& 4

X startUne"M returnM Z WW WW WW WW WW WW Z -B t'e for loop advan&es ,T% and ,%6F to position t'em so t'at t'e ne" node &an be inserted bet"een t'em Bfor 9ptrUstartM ptr && str&mp9ne" 7Sinfo+ ptr7Sinfo: S 2M prevUptr7Sne3t:M

4 106 4

-B

t'e follo"ing &ode is e3e&uted "'eb t'e list e3ists Bif 9 ptr V U start : prev7S ne3t U ne" = - B ne" value is inserted eit'er in middle or B - ne"7 S ne3t ne" 7S ne3t U ptr M -B at t'e end of t'e list B Z else X ne"7S ne3t U start M start U ne" M Z return M

Z modif# 9 : Z -B Z

,lease "rite it up as an assignment B -

delete 9 : X &'ar value ]S!_6H*4H!T6;H52^ M stru&t listHtag Bptr+ Bprev M ptrUstartM prevUstart M print f 9 N6nter !tem number to be deleted = N: M S&an f 9 NCsO + Falue : M X "'ile 9ptr && ptr 7S itemHno S value: X if 9&urrHptrU U start & & &urrHptr I itemHno U U value: X start U ptr 7 S ne3t M -B !f itemHno is found at start of t'e Bfree 9 ptr : M -B list Bbrea( M Z if 9&urrHptr 7S itemHno UU value : -B !f itemHno is found at t'e BX ,rev 7S ne3t U ptr 7S ne3t M -B middle or end of t'e list B-

4 109 4

free 9 ptr : M brea( M Z prevUptr M ptrUptr 7S ne3t M Z if 9 ptr UU 5ULL: ,rintf 9 N !tem not available - foundO : M

Sta&(s and 0ueues= Sta&(s and 0ueues are ver# useful in &omputers s&ien&e Sta&(s are used in &ompilers in passing an e3pression b# re&ursionM in memor# management in operating s#stemsM et& + Queues find t'eir use in C,U s&'eduling in printer spooling in message 0ueuing in &omputer net"or( et& + T'e list of appli&ation of sta&(s and 0ueues in real life is enormous !n t'is unit "e first define bot' t'e stru&tures and subse0uentl# "e s'all dis&uss t'eir operations and implementation $efinition of sta&(s A sta&( is a linear data stru&ture in "'i&' data is inserted and deleted at one end 9same end:i e data is stored and retrieved in a last in first out 9L!4*: order T'e most re&entl# arrived data obTe&t is first one to depart from t'e sta&( A sta&(s operates some"'at li(e a bus# e3e&utive/s Nin bo3O = "or( piles up on a sta&( and "'enever t'e e3e&utive is read# to do some "or( 'e ta(es it off t'e top T'is mig't mean t'at somet'ing gets stu&( in t'e bottom of t'e sta&( for sometime but a good e3e&utive "ould presumabl# manage to t'e get t'e sta&( emptied periodi&all# !t turns out t'at sometimes a &omputer program is naturall# organi.ed in t'is "a#+ postponing some tas(s "'ile doing ot'ers and t'us pus' do"n Sta&(s appear as t'e fundamental data stru&ture for man# algorit'ms T'e open end of t'e sta&( is &alled t'e top of t'e sta&( T'e storage and retrieval operations for a sta&( are &alled pus' and pop operations T'e implementation of sta&(s in C language is given belo" ain&ludeRstdio 'S

4 110 4

t#pedef stru&t sta&( X int dataM stru&t sta&( Blin(M ZnodeM node Btop+Bne"M main9: X int &M int 3M top U 5ULLM "'ile91: X &lrs&r9:M printf9Y1 pus'Pn2 popPn? printPn@ e3itY:M printf9YPnenter &'oi&e =Y:M s&anf9YCdY+&&:M s"it&'9&: X &ase 1= pus'9:Mbrea(M &ase 2= 3Upop9:Mif93:printf9YCd is poped outY+3:Mget&'9:Mbrea(M &ase ?= print9:Mget&'9:Mbrea(M &ase @= default=e3it9:M Z Z Z pus'9: X int nM printf9Yenter numberY:M s&anf9YCdY+&n:M ne" U 9node B:mallo&9si.eof9node::M ne"7Sdata U nM ne"7Slin( U 5ULLM if9topUU5ULL: X top U ne"M top7Slin(U5ULLM Z else X ne"7Slin(U topM top U ne"M Z

4 111 4

Z int pop9: X int 3M if9top UU 5ULL: X printf9Ysta&( empt#Y:M return92:M Z 3 U top 7SdataM topU top7Slin(M return93:M Z print9: X node B tempM temp UtopM "'ile9temp VU 5ULL: X printf9YCdY+temp7Sdata:M temp Utemp 7S lin(M Z Z Queues A 0ueue is a linear data stru&ture in "'i&' data is inserted at one end and deleted at t'e ot'er end T'e information in su&' a list is pro&essed in t'e same order as it "as re&eived So+ t'e operations performed in first in first out basis or >e &an sa# it first &ome first serve basis T'e operations possible in a Wueue data stru&ture are inserting to a Queue and deleting from t'e Queue T'e insertion ta(es pla&e from one end of t'e 0ueue and deletion from ot'er end 4or an e3ample+ "'en "e "ill go to get a ti&(et for a movie+ "e 'ave to stand in a 0ueue and t'en after getting t'e ti&(et "e 'ave to &ome out in t'e ot'er end of t'e 0ueue T'e implementation of 0ueues t'roug' C language is given belo" ain&ludeRstdio 'S t#pedef stru&t 0ueue X int dataM stru&t 0ueue Blin(M ZnodeM

4 11. 4

stru&t 0ueue Bfront+BrearM node Bne"M main9: X int i+3M front U rearU 5ULLM &lrs&r9:M "'ile91: X printf9Y1 insertPn2 deletePn? printPn@ e3itY:M fflus'9stdin:M printf9YPnenter &'oi&e = Y:M s&anf9YCdY+&i:M s"it&'9i: X &ase 1= insert9:Mbrea(M &ase 2= 3Udelete9:Mif93:printf9YCd is deletedY+3:Mget&'9:Mbrea(M &ase ?= print9:Mget&'9:Mbrea(M &ase @= default=e3it9:M Z &lrs&r9:M Z Z insert9: X int nM printf9Yenter numberY:M s&anf9YCdY+&n:M ne" U 9node B: mallo&9si.eof9node::M ne"7Sdata U nM ne"7Slin( U 5ULLM if9front UU 5ULL: X front U rear U ne"M returnM Z else X rear7Slin( U ne"M rear U ne"M Z Z int delete9:

4 113 4

X int 3M if9front UU 5ULL: X printf9Y0ueue is empt#Y:M return92:M Z 3U front7SdataM front U front 7S lin(M if9frontUU 5ULL: front Urear U 5ULLM return93:M Z print9: X node BtempM tempUfrontM "'ile9tempVU5ULL: X printf9YCdY+temp7Sdata:M tempUtemp7Slin(M Z Z

4 117 4