Cs Class 12th Notes Kv

download Cs Class 12th Notes Kv

of 283

Transcript of Cs Class 12th Notes Kv

  • 8/13/2019 Cs Class 12th Notes Kv

    1/283

    6

    Kendriya Vidyalaya Sangathan18, Institutional Area, Shaheed Jeet Singh Marg,

    New Delhi - 110 60.

    S!"D# MA!$%IA& AND '(!S

    Class XII (Computer Science 2010-11)

    1

    KENDRIYA

    VIDYALA

    YA

    SANGATHAN

  • 8/13/2019 Cs Class 12th Notes Kv

    2/283

    S!"D# MA!$%IA& )(% *&ASS +II *(M"!$% S*I$N*$

    *hie atron Shri A.inash Di/shitCommissionerKVS, New Deli

    atron !oint Commissioner ("#mn)KVS, New Deli

    Ad.isor Ms &a/shi *hari"ssistant CommissionerKVS,"me#a$a# %e&ion

    2uidan3e Sh M&2eda'#ucation icerKVS, "me#a$a# %e&ionSh4 %angasri'#ucation icer

    KVS, "me#a$a# %e&ion*o-ordinator Sh Venugo5al

    *rincipal,KV,+esana

    Su7e3t *oordinator Sh%ahul Awasthi*(Comp.Sc.),KV +esana

    Sh %a7esh Dwi.edi*(Comp.Sc.),KV immatna&ar

    Su7e3t *ontriutors ShNaresh K %ana

    *(Comp.Sc.), K.V.No.1, "/S, u

    Sh #ogesh 2u5ta*(Comp.Sc.), K.V. a

    Sh Santosh K De.al*(Comp.Sc.), K.V.No.2, IN/ 3IN'S, !amna&ar

    St %a/sha &eu.a*(Comp.Sc.), K.V. an#ina&ar Cantt.

    Sh ( ra/esh Meena*(Comp.Sc.), K.V. "/S Samana

    Sh SS Mani*(Comp.Sc.), K.V.No.2, NC, Surat

    Sh Ahi.andan Mehta*(Comp.Sc.), K.V.No. 4, "/II, !amna&ar

    2

  • 8/13/2019 Cs Class 12th Notes Kv

    3/283

    Salient features of this study material

    This study material is in the form of question bank comprising of both solved and

    unsolved questions from each chapter of the syllabus.

    It is a collection of a number of challenging questions based on HighOrder Thinking

    Skill of students. Hoever! it shall prove to be a helping tool for all types of students.

    It aims at providing help to very high scorer students ho may miss 1"" out of 1""

    because of not being e#posed to ne type of questions! being used to only conventional

    types of question! and not paying attention toards the topics hich are given in the

    reference books and syllabus of $omputer Science as per $%S& guidelines

    '(ore#ample )elational *lgebra in database concepts and e#traordinary questions based

    on pointers in $++ programming,.

    It contains guidelines! hints! and solutions for really challenging questions and topics.

    It contains a number of fresh-ne questions'solved unsolved,! hich shall increase

    the confidence level of the students hen they solve them as per$%S& /uidelines

    Such questions shall dra the attention of both the students and the teachers! and the

    preparation to achieve 1""0 shall be boosted for all categories.

    ALL THE BEST TO OUR DEAR STUDENTS

  • 8/13/2019 Cs Class 12th Notes Kv

    4/283

    CBSE Mark Distribution for different Topics(Important Lessons)

    SlNo "nit Nae Mar/s

    1 "NI! 1 rograing in * 40 "NI! Data stru3tures 159 "NI! 9 Dataase and S:& 06; "NI! ; 4oolean &ogi3 06

    < "NI! < *ouni3ation and o5en sour3e 3on3e5t 10!otal Mar/s =0

  • 8/13/2019 Cs Class 12th Notes Kv

    5/283

    S!"D# MA!$%IA&

    IND$+

    SNo !#$S () :"$S!I(NS A2$ N(

    1 S!"D# MA!$%IA&>S !'$(%$!I*A& A%! ?Key oints@ 7

    S(&V$D :"$S!I(NS 111

    9 "NS(&V$D :"$S!I(NS 181

    ; %A*!I*$ :"$S!I(N A$% S$!S I 244

    < %A*!I*$ :"$S!I(N A$% S$!S II 250

    6 %A*!I*$ :"$S!I(N A$% S$!S III 256

    = S(&"!I(N () %A*!I*$ :"$S!I(N A$% S$!S III 298

    8 !IS )(% !'$ $+AM 2:7

    S!"D# MA!$%IA&>S !'$(%$!I*A& A%!

    S&N( !#$S () ::"$S!I(NS A2$ N(

    1 "NI! 1 B *ro&rammin& in C;; 7

    2 "NI! B Data Structures 92

    4 "NI! 9 B Data$ase an# S

  • 8/13/2019 Cs Class 12th Notes Kv

    6/283

    "NI! 1 B %(2%AMMIN2 IN *

    K$# (IN!SB

    Introdu3tion to *

    C;; is te successor o C lan&ua&e = #e>elope# $? arne Stroustrup at ell 3a$oratories, New

    !erse? in 18:8.!o/ens- smallest in#i>i#ual unit. /ollowin& are te toens

    Keyword-%eser>e wor# tat can@t $e use# as i#entiier

    Identiies-Names &i>en to an? >aria$le, unction, class, union etc.

    &iterals-Value o speciic #ata t?pe

    Variale- memor? $loc o certain siAe were >alue can $e store# an# can&e#.

    *onstant- memor? $loc were >alue can $e store# once $ut can@t can&e# later on

    (5erator B perorms some action on #ata

    o "ritmetic(;,-,,,E)

    o %elationalcomparison (F,G,FH,GH,HH,H).

    o 3o&ical("ND(==),%(JJ),N().

    o Con#itional ( L)

    re3eden3e o o5eratorsB

    ;;(post increment),--(post #ecrement) i&est

    3ow

    ;;(pre increment),--(pre #ecrement),siAeo (not),-(unar?),;unar? plus)(multipl?), (#i>i#e), E(mo#ulus);(a##),-(su$tract)F(less tan),FH(less tan or eMual),G(&reater tan), GH(&reater tan or eMual to)HH(eMual),H(not eMual)== (lo&ical "ND)JJ(lo&ical %)L(con#itional epression)H(simple assi&nment) an# oter assi&nment operators(aritmetic assi&nment

    operator)

    , Comma operator

    Data ty5e-" speciier to create memor? $loc o some speciic siAe an# t?pe

    3out - Ose# to #ispla? >alue on monitor.

    3in- o prompt >alue or speciic >aria$le.

    4

  • 8/13/2019 Cs Class 12th Notes Kv

    7/283

    3oent-Ose# or $etter un#erstan#in& o pro&ram statements an# escape# $? te compiler to compile

    e.g. B sin&le line () an# multi line(P.)

    *ontrol stru3ture B

    SeCuen3e

    3ontrol

    stateent?i@

    3onditional

    stateent

    ?i else@

    3ase 3ontrol

    stateent ?swit3h

    3ase@

    loo5 3ontrol stateent

    ?while ,do while, or@

    S?nta S?nta S?nta S?ntai(con#ition)

    Q

    statementsR

    I(con#ition)

    Q

    statementsR

    else

    Q

    statementsR

    switc(epression)

    Q

    case (epression1)L

    Tstatements

    $reaRU

    case (epression2)L

    Tstatements,

    $reaRU#eaultL

    StatementsR

    while?3ondition@

    Q

    statementsR

    do while loo5

    #o

    Q

    statementR wile(con#ition)R

    )or loo5

    or(initialiAationRcon#itionRincr#ecr)

    Q

    statementR

    Nested loo5-loop witin loop.

    eEit?@-to lea>e rom te pro&ram.

    rea/- eit rom te current loop.

    3ontinue-to transer control to loop control statement.

    goto-pro&ram to ump a #ierent location.

    *hara3ter IF( )un3tionB

    get?@-input sin&le caracter rom stan#ar# input #e>ice.

    5ut?@-output sin&le caracter rom stan#ar# output #e>ice

    get3h?@-rea# rom e?$oar# 5ut3h?@-write to screen.

    get3har?@-return sin&le caracter rom a stan#ar# input #e>ice.

    5ut3har?@-transmit sin&le caracter to stan#ar# output #e>ice.

    gets?@-use# to rea# a strin& o caracter rom te stan#ar# input ile(st#in).

    5uts?@-use# to cop? a null-terminate# strin& to stan#ar# output ile (st#iout).

    5

  • 8/13/2019 Cs Class 12th Notes Kv

    8/283

    Standard * liraries

    'eader Noe ur5osest#io. /ile input an# outputct?pe. Caracter testsstrin&. Strin& operationsmat. +atematical unctions suc as sin() an# cos()st#li$. Otilit? unctions suc as malloc() an# ran#()

    Soe More "seul header ile

    stream. &rapics. conio. ct?pe. iomanip. iostream.

    mat. st#li$. st#io. stream. strin&. time.

    'eader iles ?Soe i5ortant lirary un3tions@B

    stdioh B close closeall eo lus &etcar &ets ileno open print putcar putsrea# see write &etc &etcar &ets

    stringh B setmem stpcp? strcat strcr strcmp strcmpi strcp?strcspn stricmp strlen strlwr strncat strncmp strncmpi strncp?strnicmp strnset strre> strset strstr strupr

    athh B a$s cos ep a$s loor mo# mo#l a$s pow powl() sin sMrt tan

    stdlih B a$ort a$s ateit ato atoi atol calloc#i> eit ree ran# ran#om ran#omiAe realloc

    3onioh B cgets clrscr cprintf cputs cscanf getch getche gette#t putchputte#t te#tbackground te#tcolor

    Soe un3tions

    isal5ha?3@-cec weter te ar&ument is alpa$etic or not.

    islower?3@-cec weter te ar&ument is lowecase or not.

    isu55er?3@- cec weter te ar&ument is upercase or not.

    isdigit?3@-cec weter te ar&ument is #i&it or not.

    isalnu?3@-cec weter te ar&ument is alpanumeric or not.

    tolower?@-con>erts ar&ument in lowercase i its ar&ument is a letter.

    tou55er?3@-con>erts ar&ument in uppercase i its ar&ument is a letter.

    str3at?@- concatenates two strin&.

    str35-compare two strin&. 5ow?E,y@-return raise# to power ?.

    sCrt?E@-return sMuare root o .

    rando-return a ran#om num$er $etween 0 an# (num-1)

    randoiGe-intiliAeste ran#om num$er &enerator wit a ran#om >alue.

    Array- Collection o element o same t?pe tat are reerre# $? a common name.

    6

  • 8/13/2019 Cs Class 12th Notes Kv

    9/283

    (ne Diension array

    "n arra? is a continuous memor? location ol#in& similar t?pe o #ata in sin&le row or sin&le column

    !wo diensional array

    " two #iamensional arra? is a continuous memor? location ol#in& similar t?pe o #ata in o $ot row

    san# columns (lie a matri structure).

    )un3tion-Sel-containe# $loc o co#e tat #oes some speciic tas an# return a >alue.

    )un3tion 5rototy5es-/unction #eclaration tat speciies te return t?pe an# #ata t?pe an# no o

    ar&uments

    syntaEB returnHty5e un3tionHnae?arguentHty5e?s@ arguentHnae?s@@

    assing .alue to un3tion-

    *assin& $? >alue

    *a##in& $? a##ressreerence

    )un3tion o.erloading

    *rocessin& o usin& te same name or two or more unction.

    )un3tion re3ursion

    /unction tat call itsel eiter #irectl? or in#irectl?.

    &o3al .ariales

    Declare# insi#e te unction.

    2loal .ariales

    Declare# $eore main unction ().

    A3tual .ariales

    Varia$les associate# wit unction name #urin& unction call.

    )oral .ariales

    Varia$les wic accept te actual >aria$le insi#e te unction.

    Stru3ture-Collection o lo&icall? relate# o #ierent #atat?pes reerence# un#er one name.

    Nested stru3ture

    " Structure #einition witin anoter structure.

    ty5ede

    Ose# to #eine new #ata t?pe name

    deine Dire3ti.es

    Ose to #eine a constant num$er or unction or to replace an instruction.

    7

  • 8/13/2019 Cs Class 12th Notes Kv

    10/283

    1 Mar/s Cuestions

    1@ Nae the header iles that shall e needed or the ollowing 3odeB>oi# main( )Q

    car Strin&T U H WStrin&Rcout FF setw(2)FFStrin&R

    @ hi3h * header ile?s@ will e essentially reCuired to e in3lude to runFeEe3ute the ollowing

    * 3odeB *4S$-010L>oi# main()Q

    int %noH25R car nameT UH"lma +aterRcoutFFsetw(10)FF%noFFsetw(20)FFnameFFen#lR

    9@ Nae the header iles that shall e needed or the ollowing 3odeB

    >oi# main( )Q

    car wor#TUHoar# 'amRcoutFFsetw(20)FFwor#R

    ;@ Nae the header ile?s@ that shall e needed or su33essul 3o5ilation o the ollowing *

    3ode>oi# main( )Q

    car Strin&T20UR&ets(Strin&)Rstrcat(Strin&,CS')Rputs(Strin&)R

    oi# main( )Q

    car etT50URstrcp?(et,"ISSC')Rputs(et)R

    6@ Nae the header ile to whi3h the ollowing elowB(i) a$s( ) (ii) isupper( )

    =@ Nae the header ile to whi3h the ollowing elongL(i) pow ( ) (ii)ran#om( )

    8@ Nae the header iles to whi3h the ollowing elongB(i) a$s( ) (ii) strcmp( )

    @ Nae the header iles to whi3h the ollowing elongB AI 00)isalnum( )11@ Nae the header ile, to whi3h the ollowing uilt-in un3tion elongsB

    (i) strcmp( ) (ii)&etc( )1@ Nae the header iles o * to whi3h the ollowing un3tions elongB

    (i)&et( ) (ii)open( ) (iii)a$s( ) (i>)strcat( )19@ Nae the header ile to e in3luded or the use o the ollowing uilt in un3tionsB (i)&etc(

    (ii)strcat()1;@ Nae the header ile, to whi3h ollowing uilt in un3tion elongB

    1"

  • 8/13/2019 Cs Class 12th Notes Kv

    11/283

    (i) isupper( ) ( ii)setw() (iii)ep( ) (i>)strcmp( )1)clrscr( )1=@ Nae the header iles, to whi3h the ollowing uilt in un3tions elongs toB

    (i)cos( )(ii)setw( )(iii)toupper( )(i>)strcp?( )18@ Nae the header iles, to whi3h the ollowing uilt in un3tions elongs toB

    (i)cos( )(ii)setw( )(iii)toupper( )(i>)strcp?( )1@ Nae the header ile to, whi3h ollowing uilt-in un3tions elongB

    (i) strcp?() (ii) is#i&it() (iii) lo&() (iv) puts()0@ Nae the header ile to e in3luded or the use o ollowing uilt-in un3tionsB

    (i) rep() (ii) toupper() [CBSE Sample Paper-2]1@ Nae the header lies o * to whi3h the ollowing un3tions elongB

    (i) write() (ii) arc() (iii) open() (iv) strlen()@ Nae the header iles o *

    to whi3h the ollowingun3tions elongB[AI2002]

    (i) &et() (ii) open() (iii) a$s() (i>) strcat()9@ Nae the header iles o

    * to whi3h the ollowingun3tions elongB [Comptt

    2002](i) rea#() (ii) open() (iii) &et() (i>) strcmp()

    ;@ Nae the header &le,to whi3h the ollowing uilt-in un3tions elongB(i) strcp? 0 (ii) &ets()

    ) strcp?()=@ rite the naes othe header lies to whi3h the ollowing elongB[AI 2004]

    (i) &ets() (ii) strcmp() (iii) a$s() (i>) isalnum()8@ rite the nae o header lies to whi3h the ollowing elongB[Comptt 2004]

    (i) sMrt() (ii) strcp?() (iii) isalpa() (i>) open()

    Mar/s CuestionsB

    1) %ewrite the ollowing 5rogra ater reo.ing the synta3ti3al error?s@ i any "nderline ea3h3orre3tion.

    inclu#eFiostream.G>oi# main( )Q / H 10, S H 20R

    test(/RS)Rtest(S)R >oi# test(int , int ? H 20)Q H;?RcountFFGG?R

    @ )ind the out5ut o the ollowing 5rograBinclu#eFiostream.G>oi# main( )Q int OH10,VH20Ror(int IH1RIFH2RI;;)

    11

  • 8/13/2019 Cs Class 12th Notes Kv

    12/283

    Q coutFFT1UFFO;;FF=FFV 9 FFen#lRcoutFFT2UFF;;VFF=FFO ; 2 FFen#lR

    4) %ewrite the ollowing * 5rogra ater reo.ing the syntaE error?s@ i any "nderline ea3h3orre3tion *4S$ 010Linclu#eFiostream.G

    class /3IQ

    3on& /li&tCo#eRCar DescriptionT29UR

    pu$lic>oi# a##Ino()QcinGG/li&tCo#eR &ets(Description)R>oi# sowIno()Q

    coutFF/li&tCo#eFFLFFDescriptionFFen#lR R

    >oi# main( )Q /3I /R

    a##Ino./()RsowIno./R

    ;@ %ewrite the ollowing 5rogra ater reo.ing the syntaE error?s@ i any "nderline ea3h3orre3tion

    inclu#eFiostream.G>oi# main( )Q neH10,woH20RCallme(ne,wo)RCallme(wo)R >oi# Callme(int "r&1,int "r&2)Q "r&1H"r&1;"r&2RCountFF"r&1GG"r&2R

    oi# main( )Q ran#omiAe( )Rcar Cit?T UT10UHQWD'3, WCN, WK3, W+, WNRint /l?Ror(int IH0R IF4RI;;) Q/l?Hran#om(2) ; 1RcoutFFCit?T/l?UFF WLR

    (ut5utsB(i) D'3 L CN L K3L (ii) CNL K3 L CNL

    (iii) K3 L + L NL (i>) K3 L CN L K3L6@ In the ollowing 5rogra, ind the 3orre3t 5ossile out5ut?s@ro the o5tionsB

    inclu#eFst#li$.Ginclu#eFiostream.G>oi# main( )Q ran#omiAe( )Rcar "reaT UT10UHQW N%, WSO, W'"S, WY'SRint ooRor(int IH0R IF4RI;;) QooHran#om(2) ; 1R

    12

  • 8/13/2019 Cs Class 12th Notes Kv

    13/283

    coutFF"reaTooUFFLR (ut5utsB(i) SO L '"S L SO L (ii) N% L SO L '"S L(iii) SO L '"S L Y'S L (i>) SO L '"S L '"S L

    =@ %ewrite the ollowing 5rogra ater reo.ing the synta3ti3al error?s@ i any "nderline ea3h3orre3tion

    inclu#eFiostream.Gconst int +a 10R>oi# main()

    Q int Num$ersT+aURNum$ers H Q20,90,10,40,50Ror(3ocH+a-1R3ocGH10R3oc--)coutGGNum$ersT3ocUR

    8@ In the ollowing * 5rogra what is the eE5e3ted .alue o Mysore ro o5tions ?i@ to ?i.@ gi.enelowJustiy your answer

    inclu#eFst#li$.Ginclu#eFiostream.G>oi# main( )Q ran#omiAe( )Rint ScoreT U H Q29,20,45,97,:2,74,+?scoreRcoutFF+?scoreFFen#lR

    Ii) 29 (ii) 45 (iii) 20 (i>) None o te a$o>e.@ )ind the out5ut o the ollowing 5rogra

    inclu#eFiostream.G>oi# main( )Q lon& NO+H1245954R

    int /H0,SH0R#oQ int %HNO+ E 10R

    i (% E2 H 0)/ ;H %R

    elseS ;H %R

    NO+ H 10R wile (NO+G0)RcoutFF/-SR

    10@ %ewrite the ollowing 5rogra ater reo.ing the synta3ti3al error?s@, i any "nderline ea3h3orre3tion

    inclu#eFiostream.Gconst int +ultiple 4R>oi# main( )Q >alue H 19Ror(int Counter H 1RCounter H F9RCounter ;;, Value -H 2)i(ValueE+ultiple H H 0)coutFFValue +ultipleR

    coutFFen#1RelsecoutFFValue ; +ultiple FFen#lR

    11@ )ind the out5ut o the ollowing 5rograinclu#eFiostream.Ginclu#eFstrin&.Ginclu#eFct?pe.G>oi# Con>ert(car StrT U,int 3en)Q or(int CountH0RCountF3enRCount;;)

    Q i(isupper(StrTCountU))

    1

  • 8/13/2019 Cs Class 12th Notes Kv

    14/283

    StrTCountUHtolower(StrTCountU)Relse i (islower(StrTCountU))

    StrTCountUHtoupper(StrTCountU)Relse i(is#i&it(StrTCountU))

    StrTCountUHStrTCountU;1Relse StrTCountUH..R

    >oi# main( )Q car etT UHCS' 'am 2009R

    int SiAe H strlen(et)RCon>ert(et,SiAe)RcoutFFetFFen#lRor(int CH0,%HSiAe . 1RCFHSiAe2RC;;,%--)Q car empHetTCUR

    etTCUHetT%URetT%UHempR

    coutFFetFFen#lR 1@ !he ollowing 3ode is ro a gae, whi3h generate a set o ; rando nuers raul is

    5laying this gae, hel5 hi to identiy the 3orre3t o5tion?s@ out o the our 3hoi3es gi.en elowas the 5ossile set o su3h nuers generated ro the 5rogra 3ode so that he wins thegae Justiy your answer *4S$ 010L

    inclu#eFiostream.Ginclu#eFst#li$.Gconst int 3YH29R>oi# main()Q ran#omiAe()R

    int *INH9, Num$erRor(int IH1RIFH5RI;;)Q Num$erH3Y;ran#om(*IN)R

    coutFFNum$erFFZLZ FFen#lR*IN--R

    (i) 28L27L29L26L (ii)25L26L29L27L(iii) 28L27L25L26R (i>)28L27L29L27L

    19@Rewrite the following program after removing the syntactical errors (if any). Underline eachcorrection.

    inclu#e Tiostream.Uclass +'+'%Qint +noRloat /eesR*O3ICL>oi# %e&ister()QcinGG+noGG/eesR>oi# Displa?QcoutFF+noFFZ L ZFF/eesFFen#lRR

    >oi# main()Q+'+'% +R%e&ister()R+.Displa?()R

    9 Mar/s CuestionsB'otsL

    1@ )ind the out5ut o the ollowing 5rogra Delhi 008L

    1

  • 8/13/2019 Cs Class 12th Notes Kv

    15/283

    inclu#eFiostream.Ginclu#eFct?pe.G>oi# main( )Q car etT U H W+in#[worRor(int IH0R etTIUH@\0@RI;;)Q i(isalpa(etTIU))etTIUHRelse i(isupper(etTIU))etTIUHetTIU;1R

    elseetTIU H etTI;1UR coutFFetR

    @ )ind the out5ut o the ollowing 5rograBinclu#eFiostream.Ginclu#eFct?pe.G>oi# main( )Q car +?strin&T U H Zwat[O*OZR

    or(int IH0R +?strin&TIUH@\0@RI;;)Q i(isalpa(+?strin&TIU))+?strin&TIUH@@Relse i(isupper(+?strin&TIU))

    +?strin&TIUH+?strin&TIU;1Relse

    +?strin&TIU H+?strin&TI;1UR coutFF+?strin&R

    9@ )ind the out5ut o the ollowing 5rograinclu#eFiostream.G>oi# Yit#e(int isNumH40)Q or(int IH20RIFHisNumRI;H9)

    coutFFIFF,RcoutFFen#lR

    >oi# Control(int =+?Num)Q +?Num;H10R

    Yit#e(+?Num)R >oi# main()Q int ]ourNumH20R

    Control(]ourNum)RYit#e()RcoutFF.Num$erH.FF]ourNumFFen#lR

    ;@ )ind the out5ut o the ollowing 5rograBinclu#eFiostream.G>oi# In#irect(int empH20)Q or(int IH10RIFHempRI;H9)

    coutFFIFF,RcoutFFen#lR

    >oi# Direct(int =Num)Q Num;H10R

    In#irect(Num)R >oi# main( )Q int Num$erH20R

    Direct(Num$er)RIn#irect( )RcoutFFNum$er HFFNum$erFFen#lR

  • 8/13/2019 Cs Class 12th Notes Kv

    16/283

    inclu#eFct?pe.G>oi# Secret(car +s&TU,int N)R>oi# main( )Q car S+SH r'*orm'R

    Secret(S+S,2)RcoutFFS+SFFen#lR

    >oi# Secret(car +s&TU,int N)Q or(int cH10R+s&TU1H@\0@Rc;;)

    i(cE2HH0)

    +s&TcUH +s&TcU;NRelse i (isupper(+s&TcU))+s&TcUHtolower(+s&TcU)Relse+s&TcUH +s&TcU-NR

    6@ )ind the out5ut o the ollowing 5rograB *4S$ 010Linclu#eFiostream.Gstruct tree^#Q int ,?,AR R

    >oi# mo>ein(tree^# =t, int stepH1)Q t.;HstepR

    t.?;HstepR

    t.A;HstepR >oi# mo>eout(tree^# =t, int stepH1)Q t.-HstepR

    t.?;HstepRt.A-HstepR

    >oi# main()Q tree^# t1HQ10,20,9,t2HQ40,10,50R

    mo>ein(t1)Rmo>eout(t2,9)RcoutFFt1.FFZ,ZFFt1.?FFZ,ZFFt1.AFFen#lRcoutFFt2.FFZ,ZFFt2.?FFZ,ZFFt2.AFFen#lRmo>ein(t2,10)R

    coutFFt2.FFZ,ZFFt2.?FFZ,ZFFt2.AFFen#lR =@ rite the out5ut o the ollowing 5rograB

    inclu#eFiostream.Gint unc(int =,int ?H10)Q i(E?HH0) return ;;Relse return ?- -R >oi# main( )Q int pH20,MH24R

    MHunc(p,M)RcoutFFpFFMFFen#lRpHunc(M)RcoutFFpFFMFFen#lRMHunc(p)R

    coutFFpFFMFFen#lR 8@ )ind the out5ut o the ollowing 5rogra *4S$ 010L

    inclu#eFiostream.Ginclu#eFct?pe.G>oi# +?co#e(car +s&TU,car c)Q or(int cntH0R+s&TcntUH_\0_Rcnt;;)

    Q i(+s&TcntUGH__== +s&TcntUFH__)+s&TcntUHtolower(+s&TcntU)R

    elsei(+s&TcntUHH_"_JJ+s&TcntUHH_a_)

    14

  • 8/13/2019 Cs Class 12th Notes Kv

    17/283

    +s&TcntUHcRelse

    i(cntE2HH0)+s&TcntUHtoupper(+s&TcntU)R

    else+s&TcntUH+s&Tcnt-1UR

    >oi# main()Q car +?etTUHZ"p'"CeDriV'ZR

    +?co#e(+?et,_[_)RcoutFFZN'Y 'XL ZFF+?etFFZ ZFFen#lR

    @ Yrite a unction in C;; to mer&e te contents o two sorte# arra?s " = intotir# arra? C. "ssumin& arra? " an# are sorte# in ascen#in& or#er an# teresultant arra? C is also reMuire# to $e in ascen#in& or#er.

    10@ Yrite a unction in C;; to searc or a ooNo rom a $inar? ile ZK.D"Z,assumin& te $inar? ile is containin& te o$ects o te ollowin& class. 4classQint noR

    car itleT20URpu$licLint %no()Qreturn noR>oi# 'nter()QcinGGnoR&ets(itle)R>oi# Displa?()QcoutFFnoFFitleFFen#lRR

    Answer to :uestions

    1 Mar/s Answer1@ Ans) iomanip.

    iostream.@ Ans) iostream.iomanip.

    9@ AnsB iostream.iomanip.

    ;@ Ans@ st#io. strin&.) isalnum( ) - ct?pe.

    11@ AnsB

    15

  • 8/13/2019 Cs Class 12th Notes Kv

    18/283

    (i) strcmp( ) - strin&.(ii)&etc( ) - st#io.

    1@ AnsB(i) &et( ) - iostream.(ii) open( ) - stream.(iii) a$s( ) - mat., st#li$.(i>) strcat( ) - strin&.

    19@ AnsB(i) &etc( ) - st#io.

    (ii) strcat( ) - strin&.1;@ Ans@

    (i) isupper( ) - ct?pe.(ii)setw( ) - iomanip.(iii)ep( ) - mat.(i>)strcmp( ) - strin&.

    1

  • 8/13/2019 Cs Class 12th Notes Kv

    19/283

    et(/,S)R Comma to come instea# o Ret(S)R>oi# et(int , int ?)Q H;?RcoutFFFF?R utput operator FF reMuire#

    AnsButputLT1U10=19T2U21=14T1U11=17

    T2U22=159AnsB inclu#eFiostream.G

    class /3IQ

    lon& /li&tCo#eRcar DescriptionT29UR

    pu$licL>oi# a##Ino()QcinGG/li&tCo#eR &ets(Description)R>oi# sowIno()

    QcoutFF/li&tCo#eFFLFFDescriptionFFen#lR

    R>oi# main( )Q /3I /R

    /.a##Ino()R/.sowInoR

    ;AnsB>oi# Callme(int "r&1,int "r&2H20)Rinclu#eFiostream.G>oi# main( )Q int neH10,woH20R

    Callme(ne,wo)R i>en R instea# o ,Callme(wo)R >oi# Callme(int "r&1,int "r&2)Q "r&1H"r&1;"r&2RcoutFF"r&1FF"r&2R

    < Ans@Since ran#om(2) &i>es eiter 0 or 1, /l? >alue will $e eiter 1 or 2.(ran#om(n) &i>es ?ou an? num$er $etween 0 to n-1) Cit?T1U is .CN.Cit?T2U is .K3.Since I >alue rom 0 to 2 (ieF4), 4 iterations will taes place.So te possi$le output consists 4 strin&s separate# $? L, eac otem ma? $e eiter .CN. or .K3..

    So the 5ossile out5ut will e?ii@ *'N B K(& B *'NB?i.@ K(& B*'N B K(&B

    6Ans@ Since ran#om(2) &i>es eiter 0 or 1, oo >alue will $e eiter 1 or 2.(ran#om(n) &i>es ?ou an? num$er $etween 0 to n-1) "reaT1U is .SO.

    "reaT2U is .'"S.Since I >alue rom 0 to 2 (ieF4), 4 iterations will taes place. So te possi$le output consists 4 strin&sseparate# $? L, eac o tem ma? $e eiter .SO. or .'"S..So the 5ossile out5ut will e?i@ S("!' B $AS! B S("!' B

    17

  • 8/13/2019 Cs Class 12th Notes Kv

    20/283

    ?i.@ S("!' B $AS! B $AS! B= Ans@inclu#eFiostream.G

    const int +aO10RConstant Varia$le .+a. must $einitialiAe#. Declaration S?nta 'rror>oi# main( )Q int Num$ersT+aUOP0,

  • 8/13/2019 Cs Class 12th Notes Kv

    21/283

    So etTIU HetTIU;1So etT0UHetT0U;1etT0U H::("SCII Value o +) ; 1 H :6 HN(:6 is "SCII Value o N)Now te Strin& etT U H

    hen IO1Since etT1U is `i@, Yic is a caracter, $ut wic is not Oppercase,else part will $e eecute#.Ie etTIUHetTI;1Uere etT1UHetT1;1UHetT2UIe `n@ will $e store# in place o `I@Now te Strin& etT U H

    hen IOSince etT2U is `n@, Yic is a caracter, $ut wic is not Oppercase, else part will $e eecute#.Ie etTIUHetTI;1Uere etT2UHetT2;1UHetT4UIe `#@ will $e store# in place o `n@Now te Strin& etT U H

    hen IO9Since etT4U is @#@, Yic is a caracter, $ut wic is not Oppercase, else part will $e eecute#.Ie etTIUHetTI;1Uere etT4UHetT4;1UHetT5UIe `[@, will $e store# in place o ,@#@Now te Strin& etT U H

    hen IO;Since etT5U is `[@, Since wic is not an alpa$et,(isalpa(etTIU)) will $ecomes true.Ie i?isal5ha?!eEtIL@@!eEtILO>T>Ie etT5UH@@

    21

  • 8/13/2019 Cs Class 12th Notes Kv

    22/283

  • 8/13/2019 Cs Class 12th Notes Kv

    23/283

    hen IOSince etT8U is `@, Since wic is not an alpa$et,(isalpa(etTIU)) will $ecomes true.Ie i?isal5ha?!eEtIL@@!eEtILO>T>Ie etT8UH@@Ie `@ will $e store# in place o `@Now te Strin& etT U H

    utputL NndUT+r/T@ AnsB

    utputL hatUTV":V"T9@AnsButputL

    20,29,40,20,29,40,Num$erH40

    ;@AnsButputL 10,19,20,29,40,

    10,19,20,Num$er H40

    oi# "##NSa>e(int "T U,int T U,int CT U,int N,int +, int =K) 4Qint IH0,!H0RKH0Rwile (IFN == !F+)i ("TIUFT!U)CTK;;UH"TI;;URelse

    2

  • 8/13/2019 Cs Class 12th Notes Kv

    24/283

    i ("TIUGT!U)CTK;;UHT!;;URelseQCTK;;UH"TI;;UR!;;Ror (RIFNRI;;)

    CTK;;UH"TIURor (R!F+R!;;)CTK;;UHT!UR

    10 AnsB(ut5utB

    >oi# ooSearc()Qstream /I3R/I3.open(ZK.D"Z,iosLL$inar?JiosLLin)RK Rint $n,/oun#H0R

    coutFFZ'nter oo No. to searcPZR cinGG$nRwile (/I3.rea#((car)=S,siAeo(S)))i (/I3.%no()HH$n)QS.Displa?()R/oun#;;Ri (/oun#HH0) coutFFZSorr? oo not oun#ZFFen#lR/I3.close()R

    2

  • 8/13/2019 Cs Class 12th Notes Kv

    25/283

    4ASI* *(N*$!S () ((S

    Some o te important o$ect oriente# eatures are namel?L

    $ects Classes Ineritance Data "$straction Data 'ncapsulation *ol?morpism >erloa#in& %eusa$ilit?

    (7e3tsB

    $ect is te $asic unit o o$ect-oriente# pro&rammin&. $ects are i#entiie# $? its uniMue name. "n o$ectrepresents a particular instance o a class..

    "n $ect is a collection o #ata mem$ers an# associate# mem$er unctions also nown as meto#s.

    *lassesB

    Classes are #ata t?pes $ase# on wic o$ects are create#.

    us a Class represent a set o in#i>i#ual o$ects. Caracteristics o an o$ect are represente# in aclass as *roperties. e actions tat can $e perorme# $? o$ects $ecomes unctions o te class an#is reerre# to as +eto#s.

    Inheritan3eB

    Ineritance is te process o ormin& a new class rom an eistin& class or $ase class. e $ase class

    is also nown as parent class or super class, e new class tat is orme# is calle# #eri>e# class.

    Deri>e# class is also nown as a cil# class or su$ class. Ineritance elps in re#ucin& te o>erallco#e siAe o te pro&ram, wic is an important concept in o$ect-oriente# pro&rammin&.

    Data Astra3tionB

    Data "$straction increases te power o pro&rammin& lan&ua&e $? creatin& user #eine# #ata t?pes.

    Data "$straction also represents te nee#e# inormation in te pro&ram witout presentin& te#etails.

    23

  • 8/13/2019 Cs Class 12th Notes Kv

    26/283

    Data $n3a5sulationB

    Data 'ncapsulation com$ines #ata an# unctions into a sin&le unit calle# Class.

    Data 'ncapsulation ena$les te important concept o #ata i#in& possi$le.

    olyor5hisB

    *ol?morpism allows routines to use >aria$les o #ierent t?pes at #ierent times. "n operator or unction can $e &i>en #ierent meanin&s or unctions.

    *ol?morpism reers to a sin&le unction or multi-unctionin& operator perormin& in #ierent wa?s.

    (.erloadingB

    >erloa#in& is one t?pe o *ol?morpism.

    It allows an o$ect to a>e #ierent meanin&s, #epen#in& on its contet.

    Yen an eitin& operator or unction $e&ins to operate on new #ata t?pe, or class, it is un#erstoo# to

    $e o>erloa#e#.

    %eusailityB

    is term reers to te a$ilit? or multiple pro&rammers to use te same written an# #e$u&&e# eistin&class o #ata.

    e pro&rammer can incorporate new eatures to te eistin& class, urter #e>elopin& te application

    an# allowin& users to acie>e increase# perormance.

    24

  • 8/13/2019 Cs Class 12th Notes Kv

    27/283

    IM&$M$N!A!I(N () ((S IN **onstru3tors and Destru3tors

    Constructors an# #estructors are special mem$er unctions o classes tat are use# to construct an##estro? class o$ects. Construction ma? in>ol>e memor? allocation an# initialiAation or o$ects.

    Destruction ma? in>ol>e cleanup an# #eallocation o memor? or o$ects.!he ollowing restri3tions a55ly to 3onstru3tors and destru3torsL

    Constructors an# #estructors #o not a>e return t?pes not e>en >oi# nor can te? return >alues. %eerences an# pointers cannot $e use# on constructors an# #estructors $ecause teir a##resses

    cannot $e taen. Constructors cannot $e #eclare# wit te e?wor# >irtual. Constructors an# #estructors cannot $e #eclare# static, const, or >olatile. Onions cannot contain class o$ects tat a>e constructors or #estructors. e compiler automaticall? calls constructors wen #einin& class o$ects an# calls #estructors wen

    class o$ects &o out o scope. . " constructor #oes not allocate memor? or te class o$ect its tis pointer reers to, $ut ma?

    allocate stora&e or more o$ects tan its class o$ect reers to. I memor? allocation is reMuire# oro$ects, constructors can eplicitl? call te new operator. Durin& cleanup, a #estructor ma? releaseo$ects allocate# $? te correspon#in& constructor. o release o$ects, use te #elete operator.

    Deri>e# classes #o not inerit constructors or #estructors rom teir $ase classes, $ut te? #o call teconstructor an# #estructor o $ase classes.

    Constructors are also calle# wen local or temporar? class o$ects are create#, an# #estructors arecalle# wen local or temporar? o$ects &o out o scope.

    ]ou can call mem$er unctions rom constructors or #estructors. contr!ctoris a mem$er unction wit te same name as its class.

    /or eampleLclass X Q

    pu$licL X()R constructor or class X

    R "etr!ctorare usuall? use# to #eallocate memor? an# #o oter cleanup or a class o$ect an# its

    class mem$ers wen te o$ect is #estro?e#. " #estructor is calle# or a class o$ect wen tat o$ect passes out o scope or is eplicitl? #elete#. " #estructor is a mem$er unction wit te same name as its class preie# $? a (til#e).

    /or eampleLclass X Q

    pu$licL

    X()R Constructor or class XX()R Destructor or class X

    R

    Class mem$ers tat are class t?pes can a>e teir own #estructors. ot $ase an# #eri>e# classes can a>e#estructors, altou& #estructors are not inerite#. I a $ase class " or a mem$er o " as a #estructor, an#a class #eri>e# rom " #oes not #eclare a #estructor, a #eault #estructor is &enerate#.e #eault #estructor calls te #estructors o te $ase class an# mem$ers o te #eri>e# class.e #estructors o $ase classes an# mem$ers are calle# in te re>erse or#er o te completion o teirconstructorLe #estructor or a class o$ect is calle# $eore #estructors or mem$ers an# $ases are calle#.Destructors are implicitl? calle# wen an automatic o$ect (a local o$ect tat as $een #eclare# auto ore&ister, or not #eclare# as static or etern) or temporar? o$ect passes out o scope. e? are implicitl?calle# at pro&ram termination or constructe# eternal an# static o$ects. Destructors are in>oe# wen ?ouuse te #elete operator or o$ects create# wit te new operator.

    25

  • 8/13/2019 Cs Class 12th Notes Kv

    28/283

    Deault *onstru3tors and Destru3torsI ?ou #on_t #eclare a constructor or a #estructor, te compiler maes one or ?ou. e #eault constructoran# #estructor tae no ar&uments an# #o notin&.Yat &oo# is a constructor tat #oes notin& In part, it is a matter o orm. "ll o$ects must $e constructe#an# #estructe#, an# tese #o-notin& unctions are calle# at te ri&t time."sing 3onstru3tors and destru3tors

    Demonstrates #eclaration o a constructors an# #estructor or te Cat class

    inclu#e Fiostream.G or cout

    class Cat $e&in #eclaration o te classQ pu$licL $e&in pu$lic section *at?int initialAge)R constructor *at?@ #estructor int et"&e()R accessor unction >oi# Set"&e(int a&e)R accessor unction >oi# +eow()R pri>ateL $e&in pri>ate section int its"&eR mem$er >aria$le R

    CatLLCat(int initial"&e) constructor #einition o Cat, Q its"&e H initial"&eR

    CatLLCat() #estro? te o$ect o cat wen it is no lon&er reere#. Q

    et"&e, *u$lic accessor unction returns >alue o its"&e mem$er int CatLLet"&e() Q return its"&eR

    Deinition o Set"&e, pu$lic accessor unction

    >oi# CatLLSet"&e(int a&e) Q set mem$er >aria$le its a&e to >alue passe# in $? parameter a&e its"&e H a&eR

    #einition o +eow meto# returnsL >oi# parametersL None actionL *rints ZmeowZ to screen >oi# CatLL+eow() Q cout FF Z+eow.\nZR

    26

  • 8/13/2019 Cs Class 12th Notes Kv

    29/283

    create a cat, set its a&e, a>e it meow, tell us its a&e, ten meow a&ain. int main() Q Cat /ris?(9)R /ris?.+eow()R cout FF Z/ris? is a cat wo is Z R cout FF /ris?.et"&e() FF Z ?ears ol#.\nZR

    /ris?.+eow()R /ris?.Set"&e(:)R cout FF ZNow /ris? is Z R cout FF /ris?.et"&e() FF Z ?ears ol#.\nZR return 0RutputL +eow./ris? is a cat wo is 9 ?ears ol#.+eow.Now /ris? is : ?ears ol#.

    *o5y *onstru3tor " cop? constructor is a special constructorin te C;;pro&rammin& lan&ua&euse# to create a new

    o$ectas a cop?o an eistin& o$ect. Normall? te compilerautomaticall? creates a cop? constructor or eacclass(nown as a #eault

    cop? constructor) $ut or special cases te pro&rammercreates te cop? constructor, nown as auser-#eine# cop? constructor. In suc cases, te compiler #oes not create one.

    Cop?in& o o$ects is acie>e# $? te use o a cop? constructor an# a assi&nment operator. " cop?constructor as as its irst parameter a reerence to its own class t?pe. It can a>e more ar&uments,$ut te rest must a>e #eault >alues associate# wit tem. e ollowin& woul# $e >ali# cop?constructors or class XL

    X(const X= cop?/rom+e)RX(X= cop?/rom+e)RX(const X= cop?/rom+e, int H 10)RX(const X= cop?/rom+e, #ou$le H 1.0, int H 50)R

    !he ollowing 3ases ay result in a 3all to a 3o5y 3onstru3torB Yen an o$ect is returne# $? >alue

    Yen an o$ect is passe# (to a unction) $? >alue as an ar&ument

    Yen an o$ect is trown

    Yen an o$ect is cau&t

    Yen an o$ect is place# in a $race-enclose# initialiAer list"n o$ect can $e assi&ne# >alue usin& one o te two tecniMuesL

    'plicit assi&nment in an epression InitialiAation

    $E5li3it assignent in an eE5ression$ect "R

    $ect R" H R translates as $ectLLoperatorH(const $ect=), tus ".operatorH() is calle#

    (in>oe simple cop?, not cop? constructor)InitialiGation

    "n o$ect can $e initialiAe# $? an? one o te ollowin& wa?s.a. !hrough de3laration$ect H "R translates as $ectLL$ect(const $ect=) (in>oe cop? constructor) !hrough un3tion arguentst?pe unction ($ect a)R3 !hrough un3tion return .alue

    27

    http://en.wikipedia.org/wiki/Constructor_(computer_science)http://en.wikipedia.org/wiki/C%2B%2Bhttp://en.wikipedia.org/wiki/Programming_languagehttp://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Object_copyhttp://en.wikipedia.org/wiki/Compilerhttp://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Programmerhttp://en.wikipedia.org/wiki/Assignment_operator_in_C%2B%2Bhttp://en.wikipedia.org/wiki/Constructor_(computer_science)http://en.wikipedia.org/wiki/C%2B%2Bhttp://en.wikipedia.org/wiki/Programming_languagehttp://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Object_copyhttp://en.wikipedia.org/wiki/Compilerhttp://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Programmerhttp://en.wikipedia.org/wiki/Assignment_operator_in_C%2B%2B
  • 8/13/2019 Cs Class 12th Notes Kv

    30/283

    $ect a H unction()Re cop? constructor is use# onl? or initialiAations, an# #oes not appl? to assi&nments were teassi&nment operator is use# instea#.e implicit cop? constructor o a class calls $ase cop? constructors an# copies its mem$ers $? meansappropriate to teir t?pe. I it is a class t?pe, te cop? constructor is calle#. ? usin& a user-#eine# cop?constructor te pro&rammer can #eine te $ea>ior to $e perorme# wen an o$ect is copie#.Examples

    ese eamples illustrate ow cop? constructors wor an# w? te? are reMuire# sometimes.I5li3it 3o5y 3onstru3tor3et us consi#er te ollowin& eample.cop? constructorinclu#e FiostreamGclass *ersonQpu$licL int a&eR*erson(int a) Q a&eHaRRint main()Q *erson timm?(10)R *erson sall?(19)R *erson timm?^clone H timm?R cout FF timm?.a&e FF Z Z FF sall?.a&e FF Z Z FF timm?^clone.a&e FF en#lR timm?.a&e H 24R cout FF timm?.a&e FF Z Z FF sall?.a&e FF Z Z FF timm?^clone.a&e FF en#lR return 0Rutput10 19 1024 19 10

    "s epecte#, timm#as $een copie# to te new o$ect, timm#$clone. Yile timm#%a&e was can&e#,timm#$clone%a&e remaine# te same. is is $ecause te? are totall? #ierent o$ects.e compiler as &enerate# a cop? constructor or us, an# it coul# $e written lie tisL*erson( *erson= cop?) Q a&eHcop?.a&eR

    IN'$%I!AN*$ Ineritance is te process $? wic new classes calle# &erive&classes are create# rom eistin&

    classes calle# 'ae classes. e #eri>e# classes a>e all te eatures o te $ase class an# te pro&rammer can coose to a##

    new eatures speciic to te newl? create# #eri>e# class.)eatures or Ad.antages o Inheritan3eB

    Reusability: Ineritance elps te co#e to $e reuse# in man? situations.

    e $ase class is #eine# an# once it is compile#, it nee# not $e rewore#.

    Osin& te concept o ineritance, te pro&rammer can create as man? #eri>e# classes rom te $aseclass as nee#e# wile a##in& speciic eatures to eac #eri>e# class as nee#e#

    Saves Time and Effort:

    "

  • 8/13/2019 Cs Class 12th Notes Kv

    31/283

    e a$o>e concept o reusa$ilit? acie>e# $? ineritance sa>es te pro&rammer time an# eort.te main co#e written can $e reuse# in >arious situations as nee#e#.Increases Program Structure which results in greater reliability.

    Polymorphismeneral /ormat or implementin& te concept o IneritanceL

    class derived_classname: access specifier baseclassname/or eample, i te 'aeclass is eor#an# te #eri>e# class is sample it is speciie# asL

    class sampleL pu$lic eors?s

    e a$o>e maes sample a>e access to $otp!'lican#protecte&>aria$les o $ase class eor#.%einder aout 5uli3, 5ri.ate and 5rote3ted a33ess s5e3iiersB I a mem$er or >aria$les #eine# in a class is pri>ate, ten te? are accessi$le $? mem$ers o te

    same class onl? an# cannot $e accesse# rom outsi#e te class..

    *u$lic mem$ers an# >aria$les are accessi$le rom outsi#e te class..

    *rotecte# access speciier is a sta&e $etween pri>ate an# pu$lic. I a mem$er unctions or >aria$les

    #eine# in a class are protecte#, ten te? cannot $e accesse# rom outsi#e te class $ut can $eaccesse# rom te #eri>e# class.Ineritance 'ampleL

    3lass eEorsysQ 5uli3B eors?s(>oi#) Q H0R >oi# (int n1) Q H n19R

    >oi# output(>oi#) Q coutFFR 5ri.ateL int R Rclass sampleL pu$lic eors?sQ5uli3B sample(>oi#) Q s1H0R >oi# 1(int n1)Qs1Hn110R

    >oi# output(>oi#)Qeors?sLLoutput()Rcout FF s1Rpri>ateLint s1R R

    int main(>oi#)Q sample sRs.(10)R

    1

  • 8/13/2019 Cs Class 12th Notes Kv

    32/283

    s.output()Rs.1(20)Rs.output()R

    e output o te a$o>e pro&ram is90200

    ra3ti3e 1L- "nswer te Muestions ater &oin& trou& te ollowin& class.class 'amQ

    car Su$ectT20U Rint +ars R

    pu$lic L'am() /unction 1Q

    strcp?(Su$ect, WComputer ) R+ars H 0 R'am(car *T U) /unction 2Qstrcp?(Su$ect, *) R+arsH0 R

    'am(int +) /unction 4Q

    strcp?(Su$ect, WComputer) R+ars H + R

    'am(car *T U, int +) /unction 5

    Qstrcp?(Su$ect, *) R

    +ars H + R R

    a) Yic eature o te $ect riente# *ro&rammin& is #emonstrate# usin& /unction 1,/unction2, /unction 4 an# /unction 5 in te a$o>e class 'am

    "nsL- /unction >erloa#in& (Constructor o>erloa#in&)

    $) Yrite statements in C;; tat woul# eecute /unction 4 an# /unction 5 o class 'am.

    AnsL- 'am a(10)R an# 'am $(WComp, 10)R

    ra3ti3e L Consi#er te ollowin& #eclaration Lclass welcomeQpu$licL

    welcome (int , car c)R constructor wit parameterwelcome()R constructor witout parameter >oi# compute()R

    pri>ateLint Rcar cR

    Rwic o te ollowin& are >ali# statements

    2

  • 8/13/2019 Cs Class 12th Notes Kv

    33/283

    welcome o$ (44, `a8@)Rwelcome o$1(90, `8@)Rwelcome o$4()Ro$1H welcome (59, `@)Ro$4H welcomeR

    Ans. Vali# an# in>ali# statements arewelcome o$ (44, `a8@)R .alidwelcome o$1(90, `8@)R .alidwelcome o$4()R in.alido$1H welcome (59, `@)R .alido$4H welcomeR in.alid

    !y5es o Inheritan3e

    1 Single 3lass Inheritan3eB

    Yen class a &as inerite# in class as nown as $ase class an# class is now as #eri>e#class. ere onl? two classes a>e line# to eac oter.

    it is a ase class (super)

    it is a su$ class (#eri>e#)

    Multile.el Inheritan3eB

    In tis t?pe o ineritance, tere are num$er o le>el an# it as use# in tat cases were wewant to use all properties in num$er o le>els accor#in& to te reMuirement

    it is a ase class (super) o automo$ile

    it is a su$ class (#eri>e#) o automo$ilean# $ase class o class car

    $lass automobile

    $lass car

    $lass automobile

    $lass vehicle

  • 8/13/2019 Cs Class 12th Notes Kv

    34/283

    #eri>e# class(su$) o class automo$ile

    9 Multi5le Inheritan3esB

    In tis t?pe o ineritance, num$er o classes as inerite# in a singleclass.

    Yere two or more classes are, now as $ase class an# one is #eri>e class.

    %ase class

    8erived class

    ; 'ierar3hi3al Inheritan3eB

    is t?pe o ineritance elps us to create a $aseless or num$er o classes an# tose num$ers o

    classes can a>e urter teir $rances o num$er o class.

    ase class (super)

    Sub $lass' derived,

  • 8/13/2019 Cs Class 12th Notes Kv

    35/283

  • 8/13/2019 Cs Class 12th Notes Kv

    36/283

    Rclass p?sics$ooL pu$lic tet$ooQcar topicT20URpu$licL>oi# rea#p?sics$oo()R>oi# sowp?sics$oo()RR

    (i) Name te mem$ers, wic can $e accesse# rom te mem$er unctions o class p?sics$oo.

    (ii) Name te mem$ers, wic can $e accesse# $? an o$ect o Class tet$oo.(iii) Name te mem$ers, wic can $e accesse# $? an o$ect o Class p?sics$oo.(i>) Yat will $e te siAe o an o$ect (in $?tes) o class p?sics$oo.

    Ans?i@ stan#ar# , rea#tet$oo(),sowtet$oo() an# topicR?ii@ rea#tet$oo() an# sowtet$oo()?iii@ rea#p?sics$oo(), sowp?sics$oo(), rea#tet$oo() an# sowtet$oo()?i.@ e siAe o o$ect o p?sics$ooH siAe o $oo ; siAe o et$oo ; siAe o p?sics$oo.

    H 52;7;20 H 76 $?tes

    DA!A )I&$ 'AND&IN2 IN *Key ointsB

    9 et ileL " tet ile stores inormation in rea#a$le an# printa$le orm. 'ac line o tet is terminate#wit an $(&('n# o 3ine) caracter.

    9 inar? ileL " $inar? ile contains inormation in te non-rea#a$le orm i.e. in te same ormat in wicit is el# in memor?.

    9 StreamL " stream is a &eneral term use# to name low o #ata. Dierent streams are use# torepresent #ierent in#s o #ata low.

    9 ere are tree ile I classes use# or ile rea# write operations.o istrea - can $e use# or rea# operations.o ostrea - can $e use# or write operations.o strea - can $e use# or $ot rea# = write operations.

    9 streahL9 is ea#er inclu#es te #einitions or te stream classes istream, ostream an# stream. In C;; ile

    in5ut out5ut acilities implemente# trou& stream. ea#er ile.9 It contain pre#eines set o operation or an#lin& ile relate# input an# output stream. class ties a

    ile to te pro&ram or input an# output operation.9 " ile can $e opene# usin&L

    o ? te constructor o te stream. is meto# is preerre# wen sin&le ile is use# wit te

    stream. (onl? or input onl? or output)o ? te open() unction o te stream.

    9 )ile odesB9 iosBBout - It creates ile in output mo#e an# allows writin& into te ile.9 iosBBin - It creates ile in input mo#e an# permit rea#in& rom te ile.9 iosBBa55 - o retain te pre>ious contents o te ile an# to appen# to te en# o eistin&

    ile.9 iosBBate - o place te ile pointer at te en# o te ile, $ut ?ou can write #ata an? were

    in te ile.9 iosBBtrun3 - It truncates te eistin& ile (empties te ile).9 iosBBno3reate - I ile #oes not eist tis ile mo#e ensures tat no ile is create# an# open()

    4

  • 8/13/2019 Cs Class 12th Notes Kv

    37/283

    ails.9 iosBBnore5la3e - I ile #oes not eist, a new ile &ets create# $ut i te ile alrea#? eists, te

    open() ails.9 iosBBinary pens a ile in $inar?.

    eo?@B9 is unction #etermines te en#-o-ile $? returnin& true or en# o ile oterwise returnin& alse.

    o5en?@BI ?ou want to mana&e multiple ile wit same stream use open().

    Stream$o'*ect.open(+,ilename(,ilemo&e))/e.&., stream ioRio.open(+'oo.&at io11o!t io11in io11'inar#)/

    3lose?@B is unction terminates te connection $etween te ile an# stream associate# wit it.Stream$o'*ect.cloe()/

    read(): e rea#() unction rea#s a ie# num$er o $?tes rom te speciie# stream an# puts tem in te$uer.Stream_objectread((char !)" #bject$ si%eof(#bject))&

    write?@B e write() unction writes ie# num$er o $?tes rom a speciic memor? location to te speciie#stream.

    Stream_object'rite((char !)" #bject$ si%eof(#bject))&

    NoteLot unctions tae two ar&uments.9 e irst is te a##ress o >aria$le, an# te secon# is te len&t o tat >aria$le in $?tes. e a##ress o

    >aria$le must $e t?pe cast to t?pe car(pointer to caracter t?pe)9 e #ata written to a ile usin& write( ) can onl? $e rea# accuratel? usin& rea#( ).

    get 5ointerB " &et pointer in#icates te position in te ile at wic te net input is to occur.

    5ut 5ointerB It in#icates te position in te ile at wic te net output is to $e place#.

    see/g?@B It places te &et pointer to te speciie# position in a stream.

    see/5?@B It places te put pointer to te speciie# position in a stream.

    tellg?@B is unction returns te current position o te &et pointer in a stream.tell5?@B is unction returns te current position o te put pointer in a stream.

    Ste5s !o ro3ess A )ile

    Determine te t?pe o lin reMuire#.

    Declare a stream or te #esire# t?pes o lin. "ttac te #esire# ile to te #eclare# stream.

    *rocess te ile.

    Close te ile lin wit stream.

    5

    e.g

    ifstream fin(book.txt);char ch;

    fin>>ch; //fin.get(ch);

    cout

  • 8/13/2019 Cs Class 12th Notes Kv

    38/283

    2eneral 5rogra stru3ture used or o5erating a !eEt )ile

    !eEt iles in in5ut odeB

    rite a un3tion in a * to 3ount the nuer o lower3ase al5haets 5resent in a teEt ileW4((KtEtXint countalpa()Q istream /in(WK.tt)R

    car cRint countH0Rwile(/in.eo())Q

    /in.&et(c)Ri (islower(c))

    count;;R/in.close()Rreturn countR

    )un3tion to 3al3ulate the a.erage word siGe o a teEt ile

    >oi# calculate()Q

    stream /ileR/ile.open(W$oo.tt,iosLLin)Rcar aT20URcar cRint iH0,sumH0,nH0Rwile(/ile)Q

    )ileget?3h@aTiUHcRi;;Ri((cHH@ `) JJ c(HH `.@))Q

    i --RsumHsum ;iRiH0RN;;R

    coutFFa>era&e wor# siAe is WFF(sumn)R

    rite a 5rogra that 5rints a teEt ile on the 5rinterinclu#eFiostream.G

    6

    e.g!:

    ofstream fout(book.txt);char ch;

    cin>>ch;

    fout

  • 8/13/2019 Cs Class 12th Notes Kv

    39/283

    inclu#eFstream.Ginclu#eFprocess.Gint main()Q

    car ilenameT14U, cRcoutFFenter te tet ile name LRcin.&etline(ilename,14)Ristream inRin.open(ilename)R

    i(in)QcerrFF\n/ile can@t $e opene# \nReit(-1)Rostream outRout.open(W*%N)Rwile(in.&et(c)H0)out.put(c)Rreturn 0R

    Assue a teEt ile W3oordinatetEtX is already 3reated "sing this ile 3reate a * un3tion to3ount the nuer o words ha.ing irst 3hara3ter 3a5ital

    'ampleL"o le ining an& pa# more attention to #o!r eart. "o 5e Ac6!iring an& pa# more Attention to7at #o! alrea ave. "o 5e Complaining an& pa# more Attention to giving. "o 5e critici8ingan& pa# more Attention to Complementing. "o le taling an& pa# more attention to SI5E9CE.

    utput will $e L otal wor#s are 17

    int co!nt7or&(): itream ,in(+B;;0/7ile(?,in.eo()):

    inch&i (i!pper(c[0]))

    co!nt@@/,in.cloe()/ret!rn co!nt/

    )un3tion to 3ount nuer o lines ro a teEt iles ?a line 3an ha.e aEiu =0 3hara3tersor ends at Y>@int countwor#()Q istream /in(WK.tt)R

    car cT:0URint countH0Ri (/in)Q

    coutFF'rror openin& ile Reit(0)R

    7

  • 8/13/2019 Cs Class 12th Notes Kv

    40/283

    wile(1)Q

    )ingetline?3h,=0,Y>@i (/in.eo())

    $reaRcount;;R

    /in.close()R

    return countR

    A 5rogra to dis5lay the siGe o a ile in ytesinclu#eFiostream.Ginclu#eFstream.Ginclu#eFprocess.Ginclu#eFconio.Gint main()Q

    car ilenameT14URclrscr()RcoutF'nter /ilenameL\nRcin.&etline(ilename,14)Ristream inile(ilename)Ri(inile)Q

    coutGGsorr? Can not open WFFilename FFile\nReit(-1)R

    int no^$?tesH0Rcar cRwile(cin.&et(c))Q

    no^$?tes ;;R

    coutFF/ile SiAe isFFno^$?tesFF$?tes\nRreturn 0R

    !eEt iles in out5ut odeB

    C;; pro&ram, wic initialiAes a strin& >aria$le to te content Were is an islan# o opportunit? in te mi##leo e>er? #iicult?. an# output te strin& one caracter at a time to te #is ile WO.X.incl!&etream.Dint main()

    :otream o!t(+;.F)/car Gtr > ere i an ilan& o opport!nit# in te mi&&le o ever# &iic!lt#. /int i>0/i(?o!t):

    co!t,ile cannot 'e opene& +/ret!rn 0/

    7ile (tr[i]?>H0H)

    "

  • 8/13/2019 Cs Class 12th Notes Kv

    41/283

    :o!ttr[i]/i@@/

    o!t.cloe()/

    $Eer3iseB1. te a unction in a C;; to count te num$er o uppercase alpa$ets present in a tet ile WK.tt2. Yrite a unction in a C;; to count te num$er o alpa$ets present in a tet ile WK.tt4. Yrite a unction in a C;; to count te num$er o #i&its present in a tet ile WK.tt5. Yrite a unction in a C;; to count te num$er o wite spaces present in a tet ile WK.tt9. Yrite a unction in a C;; to count te num$er o >owels present in a tet ile WK.tt7. Yrite a unction in a C;; to count te a>era&e wor# siAe in a tet ile WK.tt:. Yrite a unction in C;; to print te count o te wor# Wte as an in#epen#ent wor# in a tet ile

    S%].X.

    /or eample, i te content o te ile S%].X isere was a mone? in te Aoo.

    e mone? was >er? nau&t?.en te output o te pro&ram soul# $e 2.

    6. "ssume a tet ile West.tt is alrea#? create#. Osin& tis ile, write a unction to create tree ilesW3Y'%.X wic contains all te lowercase >owels an# WO**'%.X wic contains all teuppercase >owels an# WDII.X wic contains all #i&its.

    8. Create a unction /ile3owerSow() in c;; wic tae ile name(tet iles)as a ar&ument an# #ispla?its all #ata into lower case

    10. Yrite a unction in C;; to count te num$er o lines present in a tet ile WStor?.tt.

    '(!S )I&$ 'AND&IN21. Yrite a unction in a C;; to count te num$er o consonants present in a tet ile Wr?.tt

    2. Yrite a unction in a C;; to count te num$er o uppercase >owels present in a tet ile WNo>el.tt4. Yrite a unction in a C;; to #ispla? te sum o #i&its present in a tet ile W/ees.tt.5. Yrite a unction in a C;; to #ispla? te pro#uct o #i&its present in a tet ile WNum$er.tt.9. Yrite a unction in a C;; to in# te lar&est #i&it present in a tet ile W+ars.tt

    2eneral 5rogra stru3ture used or o5erating a 4inary )ile

    rogra to read and write a stru3ture using read?@ and write?@ using inary ile

    struct stu#entQcar nameT19UR

    loat percentR

    >oi# main()Q

    clrscr()Rstu#ent sRstrcp?(s.name,rasa)Rs.percentH68.90Rostream outRout.open(Wsa>in&, iosLLout J iosBB inary)R

    1

  • 8/13/2019 Cs Class 12th Notes Kv

    42/283

    i(out)Q

    coutFFW/ile can@t $e opene#R$reaR

    out.write((car ) = s,siAeo(stu#ent))Rout.close()Ristream inRin.open(Wsa>in&,iosLLin J iosLL $inar?)R

    in.rea#((car ) = s,siAeo(stu#ent))RcoutFFs.nameRcoutFFW\n as te percentL FFs.percentRin.close()R

    )un3tion to add ore o7e3ts elonging to 3lass J(K$ at the end o J(K$SDA! ile

    >oi# appen#()Q

    stream aileRaile.open(W!K'S.D", iosLL$inar? J iosLLapp)R

    !K' 3"OR int n,iR coutFFow man? o$ects ?ou want to a## LR cinGGnR or (iH0RiFnRi;;)

    Q3"O.Newoeentr?()R

    aile.write((car )= 3"O, siAeo (!K'))Raile.close()R

    rite a un3tion showile?@ to read all the re3ords 5resent in an already eEiting inary ile S$$DDA!and dis5lay the on the s3reen, also 3ount the nuer o re3ords 5resent in the ile Assuing the3lass Vehi3le as ollowsB

    class >eicleQ

    car >eiclet?peT10URint no^o weelsRpu$licL>oi# &et#etials()Q

    &ets(>eiclet?pe)R

    cinGGno^o^weelsR>oi# sow#etails()UQ

    coutFFVeicle ?peFF>eiclet?peRcoutFFNum$er o YeelsHFFno^o^weelsR

    R

    voi& o7ile()

    2

  • 8/13/2019 Cs Class 12th Notes Kv

    43/283

    :itream in/in.open(+SPEE"."Aio11in io11'inar#)/veicle vJ/int co!nt>0/7ile (?in.eo()):

    in.rea&((car G)KvJi8eo(vJ))/co!nt@@/

    vJ.o7&etail()/co!total n!m'er o recor& are +co!nt/

    'erciseL1. Yrite a unction in C;; to searc or a ooNo rom a $inar? ile WK.D", assumin& te $inar?

    ile is containin& te o$ects o te ollowin& class.class KQint noRcar itleT20UR

    pu$licLint %no()Qreturn noR>oi# 'nter()QcinGGnoR&ets(itle)R>oi# Displa?()QcoutFFnoFFitleFFen#lRR

    2. Yrite a unction in C;; to a## new o$ects at te $ottom o a $inar? ile WSOD'N.D", assumin&te $inar? ile is containin& te o$ects o te ollowin& class.class SODQint %noRcar NameT20UR

    pu$licL>oi# 'nter()QcinGG%noR&ets(Name)R>oi# Displa?()QcoutFF%noFFNameFFen#lRR

    4. $ser>e te pro&ram se&ment careull? an# answer te Muestion tat ollowsLclass itemQint item^noR

    car item^nameT20URpu$licL>oi# enterDetail( )R>oi# sowDetail( )Rint &etItem^no( )Q return item^noRR>oi# mo#i?(item , int ? )Qstream /ileR/ile.open( Witem.#at, iosLL$inar? J iosLLin J iosLLout) R

  • 8/13/2019 Cs Class 12th Notes Kv

    44/283

    item iRint recor#s%ea# H 0, oun# H 0Rwile(oun# == /ile.rea#((car) =i , siAeo (i)))Qrecor#s%ea#;;Ri(i . &etItem^no( ) H H ? )Q

    ^^^^^^^^^^^^^^^^^^^^^^^^^+issin& statement/ile.write((car) = , siAeo ())R

    oun# H 1Ri( oun#)coutFF%ecor# or mo#iication #oes not eist R/ile.close() RI te unction mo#i?( ) is suppose# to mo#i? a recor# in te ile W item.#at W, wic item^no is ?, witte >alues o item passe# as ar&ument, write te appropriate statement or te missin& statemenusin& seep( ) or see&( ), wice>er is nee#e#, in te a$o>e co#e tat woul# write te mo#iie#recor# at its proper place.

    5. $ser>e te pro&ram se&ment careull? an# answer te Muestion tat ollowsLclass itemQint item^noRcar item^nameT20URpu$licL>oi# enterDetails( )R>oi# sowDetail( )Rint &etItem^no( )Q return item^noRR>oi# mo#i?(item )Qstream /ileR/ile.open( Witem.#at, ^^^^^^^^^^^^^^^ ) R parameter missin&

    item iRwile(/ile .rea#((car) = i , siAeo (i)))Qi( . &etItem^no( ) H H i . &etItem^no( ))Q/ile.seep(/ile.tell&( ) B siAeo(i))R/ile.write((car) = , siAeo ())Relse/ile.write((car) =i , siAeo (i))R/ile.close() RI te unction mo#i?( ) mo#iies a recor# in te ile W item.#at W wit te >alues

    o item passe# as ar&ument, write te appropriate parameter or te missin&parameter in te a$o>e co#e, so as to mo#i? recor# at its proper place.

    9. $ser>e te pro&ram se&ment careull? an# answer te Muestion tat ollowsLclass itemQint item^noRcar item^nameT20URpu$licL>oi# enterDetail( )R

  • 8/13/2019 Cs Class 12th Notes Kv

    45/283

    >oi# sowDetail( )Rint &etItem^no( )Q return item^noRR>oi# mo#i?(item )Qstream /ileR/ile.open( Witem.#at, iosLL$inar?JiosLLinJiosLLout ) Ritem iRwile(/ile .rea#((car) = i , siAeo (i)))Statement 1

    Qi( . &etItem^no( ) H H i . &etItem^no( ))Q/ile.seep(/ile.tell&( ) B siAeo(i))R/ile.write((car) = , siAeo ())R/ile.close() RI te unction mo#i?( ) mo#iies a recor# in te ile W item.#at wit te >alues o item passe# asar&ument, rewrite statement 1 in te a$o>e co#e usin& eo( ), so as to mo#i? recor# at its propeplace.

    (IN!$%SKey 5oints to reeerBointerB

    9 " in# o memor? >aria$le tat ol#s te a##ress o oter >aria$le o same #ata t?pe.9 %eeren3e o5erator ?Z@ "s soon as we #eclare a >aria$le, te amount o memor? nee#e# is

    assi&ne# or it at a speciic location in memor? (its memor? a##ress).9 is reerence to a >aria$le can $e o$taine# $? prece#in& te i#entiier o a >aria$le wit an

    ampersan# si&n (=), nown as reerence operator, an# wic can $e literall? translate# as Za##ressoZ.

    /or eampleLte# H =an#?RConsi#er te ollowin& co#e ra&mentLan#? H 29Rre# H an#?Rte# H =an#?R

    e >alues containe# in eac >aria$le ater te eecution o tis, are sown in te ollowin& #ia&ramL/irst, we a>e assi&ne# te >alue 29 to an#? (a >aria$le wose a##ress in memor? we a>e assume# to $e1::7).

    Dereeren3e o5erator ?T@9 a >aria$le wic stores a reerence to anoter >aria$le is calle# a pointer.9 *ointers are sai# to Zpoint toZ te >aria$le wose reerence te? store.Osin& a pointer we can #irectl?

    access te >alue store# in te >aria$le wic it points to.9 o #o tis, we simpl? a>e to prece#e te pointer_s i#entiier wit an asteris (), wic acts as

    dereeren3e o5eratoran# tat can $e literall? translate# to Z>alue pointe# $?Z.9 ereore, ollowin& wit te >alues o te pre>ious eample, i we writeL

    $et H te#R(tat we coul# rea# asL Z$et eMual to >alue pointe# $? te#Z) $et woul# tae te >alue 29, since te# is 1::7an# te >alue pointe# $? 1::7 is 29. ]ou must clearl? #ierentiate tat te epression te# reers to te >alue1::7, wile te# (wit an asteris prece#in& te i#entiier) reers to te >alue store# at a##ress 1::7, wic

    3

  • 8/13/2019 Cs Class 12th Notes Kv

    46/283

    in tis case is 29. Notice te #ierence o inclu#in& or not inclu#in& te #ereerence operator (I a>e inclu#e#an eplanator? commentar? o ow eac otese two epressions coul# $e rea#)L$et H te#R $et eMual to te# ( 1::7 )$et H te#R $et eMual to >alue pointe# $? te# ( 29 )

    De3laring .ariales o 5ointer ty5es Due to te a$ilit? o a pointer to #irectl? reer to te >alue tat it points to, it $ecomes necessar? to

    speci? in its #eclaration wic #ata t?pe a pointer is &oin& to point to. It is not te same tin& to pointto a car as to point to an int or a loat.

    e #eclaration o pointers ollows tis ormatL t?pe nameR were t?pe is te #ata t?pe o te >aluetat te pointer is inten#e# to point to. is t?pe is not te t?pe o te pointer itsel $ut te t?pe o te#ata te pointer points to. /or eampleL

    o int num$erRo car caracterR

    o loat &reatnum$erR

    Now a>e a loo at tis co#eL m? irst pointerinclu#e FiostreamG

    int main ()Qint irst>alue, secon#>alueRint m?pointerRm?pointer H =irst>alueRm?pointer H 10Rm?pointer H =secon#>alueRm?pointer H 20Rcout FF Zirst>alue is Z FF irst>alue FF en#lRcout FF Zsecon#>alue is Z FF secon#>alue FF en#lRreturn 0R

    irst>alue is 10secon#>alue is 20

    more pointersinclu#e FiostreamGint main ()Qint irst>alue H 9, secon#>alue H 19Rint p1, p2Rp1 H =irst>alueR p1 H a##ress o irst>aluep2 H =secon#>alueR p2 H a##ress o secon#>aluep1 H 10R >alue pointe# $? p1 H 10

    p2 H p1R >alue pointe# $? p2 H >alue pointe# $?p1p1 H p2R p1 H p2 (>alue o pointer is copie#)p1 H 20R >alue pointe# $? p1 H 20cout FF Zirst>alue is Z FF irst>alue FF en#lRcout FF Zsecon#>alue is Z FF secon#>alue FF en#lRreturn 0Rirst>alue is 10secon#>alue is 20

    4

  • 8/13/2019 Cs Class 12th Notes Kv

    47/283

    Notice tat tere are epressions wit pointers p1 an# p2, $ot wit an# witout #ereerence operator ().e meanin& o an epression usin& te #ereerence operator () is >er? #ierent rom one tat #oes notYen tis operator prece#es te pointer name, te epression reers to te >alue $ein& pointe#, wile wena pointer name appears witout tis operator, it reers to te >alue o te pointer itsel (i.e. te a##ress owat te pointer is pointin& to).

    ointers and arrays e concept o arra? is >er? muc $oun# to te one o pointer.

    In act, te i#entiier o an arra? is eMui>alent to te a##ress o its irst element, as a pointer is eMui>alentto te a##ress o te irst element tat it points to, so in act te? are te same concept./or eample, supposin& tese two #eclarationsLint num$ers T20URint pRe ollowin& assi&nment operation woul# $e >ali#Lp H num$ersR

    "ter tat, p an# num$ers woul# $e eMui>alent an# woul# a>e te same properties.

    e onl? #ierence is tat we coul# can&e te >alue o pointer p $? anoter one, wereas num$erswill alwa?s point to te irst o te 20 elements o t?pe int wit wic it was #eine#.

    ereore, unlie p, wic is an or#inar? pointer, num$ers is an arra?, an# an arra? can $econsi#ere# a contant pointer. ereore, te ollowin& allocation woul# not $e >ali#L

    num$ers H pR ecause num$ers is an arra?, so it operates as a constant pointer, an# we cannot assi&n >alues to

    constants. Due to te caracteristics o >aria$les, all epressions tat inclu#e pointers in te ollowin& eample

    are perectl?>ali#L more pointersinclu#e FiostreamGint main ()Qint num$ersT9UR

    int pRp H num$ersR p H 10Rp;;R p H 20Rp H =num$ersT2UR p H 40Rp H num$ers ; 4R p H 50Rp H num$ersR (p;5) H 90Ror (int nH0R nF9R n;;)cout FF num$ersTnU FF Z, ZRreturn 0R10, 20, 40, 50, 90,In arra?s we use# $racets (TU) to speci? te in#e o an element o te arra? to wic we wante# to reerYell, tese $racet si&n operators TU are also a #ereerence operator nown as oet operator. e?#ereerence te >aria$le te? ollow ust as #oes, $ut te? also a## te num$er $etween $racets to tea##ress $ein& #ereerence#. /or eampleLaT9U H 0R a Toset o 9U H 0(a;9) H 0R pointe# $? (a;9) H 0ese two epressions are eMui>alent an# >ali# $ot i a is a pointer or i a is an arra?.

    ointer initialiGation

    Yen #eclarin& pointers we ma? want to eplicitl? speci? wic >aria$le we want tem topoint toL

    int num$erR5

  • 8/13/2019 Cs Class 12th Notes Kv

    48/283

    int tomm? H =num$erRe $ea>ior o tis co#e is eMui>alent toLint num$erRint tomm?Rtomm? H =num$erR

    Yen a pointer initialiAation taes place we are alwa?s assi&nin& te reerence >alue to were tepointer points (tomm?), ne>er te >alue $ein& pointe# (tomm?).

    "s in te case o arra?s, te compiler allows te special case tat we want to initialiAe te content at wicte pointer points wit constants at te same moment te pointer is #eclare#Lcar terr? H ZelloZRIn tis case, memor? space is reser>e# to contain ZelloZ an# ten a pointer to te irst caracter o tismemor? $loc is assi&ne# to terr?. I we ima&ine tat ZelloZ is store# at te memor? locations tat start ata##resses 1:02, we can represent te pre>ious #eclaration asL It is important to in#icate tat terr? containste >alue 1:02, an# not __ nor elloZ, altou& 1:02 in#ee# is te a##ress o $ot o tese. /or eample, wecan access te it element o te arra? wit an? o tese two epressionL(terr?;5)terr?T5Uot epressions a>e a >alue o _o_ (te it element o te arra?).

    ointer aritheti3s o con#uct aritmetical operations on pointers is a little #ierent tan to con#uct tem on re&ularinte&er #ata t?pes.

    o $e&in wit, onl? a##ition an# su$traction operations are allowe# to $e con#ucte# wit tem, teoters mae no sense in te worl# o pointers.

    ut $ot a##ition an# su$traction a>e a #ierent $ea>ior wit pointers accor#in& to te siAe o te#ata t?pe to wic te? point.

    /or eample, let_s assume tat in a &i>en compiler or a speciic macine,3har ta/es 1 yte, short ta/es ytes and long ta/es ;.

    Suppose tat we #eine tree pointers in tis compilerLcar m?carRsort m?sortR

    lon& m?lon&Ran# tat we now tat te? point to memor? locations 1000, 2000 an# 4000 respecti>el?.So i we writeLm?car;;Rm?sort;;Rm?lon&;;R

    m?car, as ?ou ma? epect, woul# contain te >alue 1001. ut not so o$>iousl?, m?sort woul# contain te>alue 2002, an# m?lon& woul# contain 4005, e>en tou& te? a>e eac $een increase# onl? once. ereason is tat wen a##in& one to a pointer we are main& it to point to te ollowin& element o te samet?pe wit wic it as $een #eine#, an# tereore te siAe in $?tes o te t?pe pointe# is a##e# to tepointer. is is applica$le $ot wen a##in& an# su$tractin& an? num$er to a pointer. It woul# appeneactl? te same i we writeL

    m?car H m?car ; 1Rm?sort H m?sort ; 1Rm?lon& H m?lon& ; 1Rot te increase (;;) an# #ecrease (--) operators a>e &reater operator prece#ence tan te #ereerenceoperator (), $ut $ot a>e a special $ea>ior wen use# as sui (te epression is e>aluate# wit te >alueit a# $eore $ein& increase#). ereore, te ollowin& epression ma? lea# to conusionLp;;ecause ;; as &reater prece#ence tan , tis epression is eMui>alent to (p;;). ereore, wat it #oes isto increase te >alue o p (so it now points to te net element), $ut $ecause ;; is use# as posti te wole

    6

  • 8/13/2019 Cs Class 12th Notes Kv

    49/283

    epression is e>aluate# as te >alue pointe# $? te ori&inal reerence (te a##ress te pointer pointe# to$eore $ein& increase#).Notice te #ierence witL(p);;ere, te epression woul# a>e $een e>aluate# as te >alue pointe# $? p increase# $? one. e >alue o p(te pointer itsel) woul# not $e mo#iie# (wat is $ein& mo#iie# is wat it is $ein& pointe# to $? tis pointer).I we writeLp;; H M;;Recause ;; as a i&er prece#ence tan , $ot p an# M are increase#, $ut $ecause $ot increase

    operators (;;) are use# as posti an# not prei, te >alue assi&ne# to p is M $eore $ot p an# M areincrease#. "n# ten $ot are increase#. It woul# $e rou&l? eMui>alent toLp H MR;;pR;;MR3ie alwa?s, I recommen# ?ou to use parenteses () in or#er to a>oi# unepecte# results an# to &i>e morele&i$ilit? to te co#e.

    ointers to 5ointers C;; allows te use o pointers tat point to pointers, tat tese, in its turn, point to #ata (or e>en to

    oter pointers). In or#er to #o tat, we onl? nee# to a## an asteris () or eac le>el o reerence inteir #eclarationsL

    car aRcar $Rcar cRa H _A_R$ H =aRc H =$Ris, supposin& te ran#oml? cosen memor? locations or eac >aria$le o :240, 6082 an# 10902, coul# $erepresente# asL e >alue o eac >aria$le is written insi#e eac cellR un#er te cells are teir respecti>ea##resses in memor?. e new tin& in tis eample is >aria$le c, wic can $e use# in tree #ierent le>elso in#irection, eac one o tem woul# correspon# to a #ierent >alueLb c as t?pe car an# a >alue o 6082b c as t?pe car an# a >alue o :240b c as t?pe car an# a >alue o _A_

    Null 5ointer

    " null pointer is a re&ular pointer o an? pointer t?pe wic as a special >alue tat in#icatestat it is not pointin& to an? >ali# reerence or memor? a##ress.

    is >alue is te result o t?pe-castin& te inte&er >alue Aero to an? pointer t?pe.int pRp H 0R p as a null pointer >alue

    Do not conuse null pointers wit >oi# pointers.

    " null pointer is a >alue tat an? pointer ma? tae to represent tat it is pointin& to ZnowereZ,

    wile a >oi# pointer is a special t?pe o pointer tat can point to somewere witout a speciict?pe. ne reers to te >alue store# in te pointer itsel an# te oter to te t?pe o #ata itpoints to.

    Dynai3 Meory Ontil now, in all our pro&rams, we a>e onl? a# as muc memor? a>aila$le as we #eclare# or ou

    >aria$les, a>in& te siAe o all o tem to $e #etermine# in te source co#e, $eore te eecution ote pro&ram.

    7

  • 8/13/2019 Cs Class 12th Notes Kv

    50/283

    ut, wat i we nee# a >aria$le amount o memor? tat can onl? $e #etermine# #urin& runtime /oreample, in te case tat we nee# some user input to #etermine te necessar? amount o memor?space.

    e answer is namic memor#, or wic C;; inte&rates te operators new an# #elete.

    (5erators new and newL In or#er to reMuest #?namic memor? we use te operator new.

    new is ollowe# $? a #ata t?pe speciier an# -i a seMuence o more tan one element is reMuire#- te num$er o

    tese witin $racets TU. It returns a pointer to te $e&innin& o te new $loc o memor? allocate#. Its ormisL

    5ointer O new ty5e5ointer O new ty5e nuerHoHeleentsL

    e irst epression is use# to allocate memor? to contain one sin&le element o t?pe t?pe. e secon# oneis use# to assi&n a $loc (an arra?) o elements o t?pe t?pe, were num$er^o^elements is an inte&er >aluerepresentin& te amount o tese. /or eampleLint $o$$?R$o$$? H new int T9URIn tis case, te s?stem #?namicall? assi&ns space or i>e elements o t?pe int an# returns a pointer to teirst element o te seMuence, wic is assi&ne# to $o$$?. ereore, now, $o$$? points to a >ali# $loc o

    memor? wit space or i>e elements o t?pe int. e irst element pointe# $? $o$$? can $e accesse# eiterwit te epression $o$$?T0U or te epression $o$$?. e secon# element can $e accesse# eiter wit$o$$?T1U or ($o$$?;1) an# so on...

    (5erators delete and delete L Since te necessit? o #?namic memor? is usuall? limite# to speciic moments witin a pro&ram, once

    it is no lon&er nee#e# it soul# $e ree# so tat te memor? $ecomes a>aila$le a&ain or oterreMuests o #?namic memor?.

    is is te purpose o te operator #elete, wose ormat isLo #elete pointerRo #elete TU pointerR

    e irst epression soul# $e use# to #elete memor? allocate# or a sin&le element, an# te secon#one or memor? allocate# or arra?s o elements.

    ra3ti3eL- %ewrite te ollowin& co#es ater remo>in& errors, i an?, in te ollowin& snippet. 'plain eacerror.>oi# main()Qconst int i H 20Rconst int const ptr H =iR(ptr);;Rint H 19Rptr H =R

    ra3ti3eL i>e te output o te ollowin& pro&ramL>oi# main()Qcar p H WScoolRcar cRc H ;; p ;;RcoutFFcR

    3"

  • 8/13/2019 Cs Class 12th Notes Kv

    51/283

    ra3ti3eL i>e te output o te ollowin& pro&ramL>oi# main()Qint TU H Q 90, 50, 40, 20, 10Lint p, M, tRp H Rt H ; 1RM H =tRcout FF p FF W, FF M FF W, FF t;;R

    ra3ti3eL i>e te output o te ollowin& pro&ram( "ssume all necessar? ea#er iles are inclu#e#)L>oi# main( )Qcar H WYor3# Cu*Rcar cRc H ;; ;;RcoutFFcRra3ti3eL i>e te output o te ollowin& pro&ram("ssume all necessar? ea#er iles are inclu#e#) L>oi# main( )

    Qcar H WYor3D Cu*Rcar cRc H ( (;1) ) ;; RcoutFFcR

    ra3ti3e. Yat will $e te output o te pro&ram( "ssume all necessar? ea#er iles are inclu#e#) L>oi# print (car p )Qp H ZCompZRcoutFFZ>alue is ZFFpFFen#lR

    >oi# main( )Qcar H ZClass XIIZRprint()RcoutFFZnew >alue is ZFFFFen#lR

    ra3ti3eL i>e output o ollowin& co#e ra&mentLcar ms& H Wa *ro/ileRor (int i H 0R i F strlen (ms&)R i;;)i (islower(ms&TiU))ms&TiU H toupper (ms&TiU)R

    elsei (isupper(ms&TiU))i( i E 2 H 0)ms&TiU H tolower (ms&Ti-1U)Relsems&Ti--URcout FF ms& FF en#lR

    31

  • 8/13/2019 Cs Class 12th Notes Kv

    52/283

    "NI! B DA!A S!%"*!"%$S

    " data stru3tureis a particular wa? o storin& an# or&aniAin& #ata in a computer so tat it can $e use#eicientl?.Dierent in#s o #ata structures are suite# to #ierent in#s o applications.!y5es o data stru3tureere are two t?pes o #ata structures&inear data stru3ture-"rra?,3ine# list,Stac,orsL one #imensional an# multi-#imensional arra?s. '>er?one o te pictures a$o>e

    represents a sin&le #imensional arra?.

    De3laring an Array

    3ie an? oter >aria$le, te s?nta o #eclarin& an arra? isL

    Data?pe "rra?NameT#imensionor#erU

    e arra? is irst i#entiie# $? its in#, wic coul# $e a car, an int, a loat, etcR ollowe# $? its name tatollows te C;; namin& rules. e name is ten ollowe# $? sMuare $racets tat speci? te #imension ote arra? or its siAe.

    32

  • 8/13/2019 Cs Class 12th Notes Kv

    53/283

    ere are eamples o #eclarin& arra?sL

    int a&eT12URloat &ra#eT100UR#ou$le an&leT470UR

    int "&eT12UR #eclares a &roup or arra? o 12 >alues, eac one $ein& an inte&er.

    loat ra#eT100UR #eclares an arra? o 100 loatin&-point >alues.

    #ou$le "n&leT470UR #eclares an arra? o #ou$le-precision num$ers. ere are 470 o tese items inte &roup.

    InitialiGing an Array

    !ust lie an? >aria$le can $e initialiAe#, an arra? also can $e initialiAe#. o accomplis tis, or aone-#imensional arra?, te s?nta use# isL

    *ataType +rray,ame-dimension. / 0 element1$ element2$ 3$ elementn4&

    ere are eamples o #eclarin& an initialiAin& arra?sL

    int num$erT12U H Q16, 52, 29, 12, 45, 19, 74, :2, 82, 27, 27, 12R#ou$le #istanceT9U H Q55.15, :20.92, 87.06, 576.:6, 7.26R

    *rocessin& te 'lements o an "rra?inclu#e FiostreamGint main()Q

    #ou$le #istanceTU H Q55.15, :20.92, 87.06, 576.:6, 7.26Rcout FF Z2n# mem$er H Z FF distan3e1LFF en#lRcout FF Z9t mem$er H Z FF distan3e;LFF en#lRreturn 0R

    is woul# pro#uceL2n# mem$er H :20.929t mem$er H 7.26

    (5erations on Arraysinclu#e FiostreamGint main()Q

    Ye now tat we nee# a constant num$er o elementsconst int ma H 10Rint num$erTmaUR Ye will calculate teir sum

    int sum H 0Rcout FF Z*lease t?pe 10 inte&ers.\nZRor( int i H 0R i F maR i;; )Q

    cout FF ZNum$er Z FF i ; 1 FF ZL ZRcin GG num$erTiURsum ;H num$erTiUR

    cout FF Z\n\ne sum o tese num$ers is Z FF Sum FF Z\n\nZRreturn 0R

    3

  • 8/13/2019 Cs Class 12th Notes Kv

    54/283

    Arrays and )un3tions

    "n arra? can $e passe# to a unction as ar&ument.

    "n arra? can also $e returne# $? a unction. o #eclare an# #eine tat a unction taes an arra? asar&ument, #eclare te unction as ?ou woul# #o or an? re&ular unction an#, in its parentesesspeci? tat te ar&ument is an arra?.ere is an eampleL

    inclu#e FiostreamG.oid Dis5lay!heArray?doule eeroi# Displa?e"rra?(#ou$le mem$erTU)Q

    or(int i H 0R i F 9R ;;i)cout FF Z\nDistance Z FF i ; 1 FF ZL Z FF mem$erTiUR

    cout FF en#lR

    int main()Q

    const int num$erItems H 9R

    3

  • 8/13/2019 Cs Class 12th Notes Kv

    55/283

    #ou$le #istanceTnum$erItemsU H Q55.15, :20.92, 87.06, 576.:6, 7.26Rcout FF Z+em$ers o te arra?ZRDis5lay!heArray?distan3e@return 0R

    is woul# pro#uceL

    +em$ers o te arra?

    Distance 1L 55.15Distance 2L :20.92Distance 4L 87.06Distance 5L 576.:6Distance 9L 7.26

    ra3ti3e B-]inclu#e FiostreamG>oi# Displa?e"rra?(#ou$le mem$erTU)Q

    or(int i H 0R i F 9R ;;i)cout FF Z\nDistance Z FF i ; 1 FF ZL Z FF mem$erTiUR

    cout FF en#lR

    int main()Q

    const int Num$erItems H 9R#ou$le #istanceTNum$erItemsU H Q55.15, :20.92, 87.06, 576.:6, 7.26Rcout FF Z+em$ers o te arra?ZRDis5lay!heArray?distan3e9L@return 0R

    ra3ti3eB-inclu#e FiostreamG

    .oid Dis5lay!heArray?doule r L, int 3ount@int main()Q

    #ou$le #istanceTU H Q55.15, :20.92, 87.06, 576.:6, 7.26, 76.05, 475.99, 7245.12R *rocessin& 9 mem$ers o te arra?cout FF Z+em$ers o te arra?ZRDis5lay!heArray?distan3e,

  • 8/13/2019 Cs Class 12th Notes Kv

    56/283

    +em$ers o te arra?Distance 1L 55.15Distance 2L :20.92Distance 4L 87.06Distance 5L 576.:6Distance 9L 7.26+em$ers o te arra?

    Sear3hing&inear sear3hB &inear sear3hor seCuential sear3his a meto# or in#in& a particular >alue in a list, tatconsists o cecin& e>er? one o its elements, one at a time an# in seMuence, until te #esire# one is oun#.unction or linear searc

    inclu#e FiostreamGint &inearSear3h?int ArrayL, 3onst int SiGe, 3onst int Val!oSear3h@P ool Not)ound O true

    int i O 0while?i R SiGe ZZ Not)ound@P

    i?Val!oSear3h O ArrayiL@ielse

    Not)ound O alseQi? Not)ound OO alse @

    return ielse

    return -1Q

    int main()

    Q int Num$erTU H Q 7:, 2:6, 574, 2, 5764, 612, 247, 46 Rint

  • 8/13/2019 Cs Class 12th Notes Kv

    57/283

  • 8/13/2019 Cs Class 12th Notes Kv

    58/283

    >oi# main()Q clrscr()R int siAeR coutFFZ\n 'N'% ' NO+'% / '3'+'NS %'

  • 8/13/2019 Cs Class 12th Notes Kv

    59/283

    return 0R

    Sele3tion SortSele3tion sortis a sortin& al&oritm, speciicall? an in-place comparison sort. It as (n2) compleit?,main& it ineicient on lar&e lists, an# &enerall? perorms worse tan te similar insertion sort>oi# SelectionSort(int "TU, int len&t)

    Q int i, , min, minatRor(i H 0R iF(len&t-1)R i;;)Q

    minat H iRmin H "TiUR

    or( H i;1R F len&tR ;;) select te min o te rest o arra? Q

    i(min G "TU) ascen#in& or#er or #escen#in& re>erse Q

    minat H R te position o te min elementmin H "TUR

    int temp H "TiUR "TiU H "TminatUR swap"TminatUHtempR

    en# selection sort

    9 4ule Sort

    4ule sortis a simple sortin& al&oritm. It wors $? repeate#l? steppin& trou& te list to $e sorte#,

    comparin& eac pair o a#acent items an# swappin& tem i te? are in te wron& or#erinclu#e FiostreamGusin& namespace st#Rint compare(int, int)R>oi# sort(intTU, const int)Rint compare(int , int ?)Q return( G ?)R>oi# sort(int ta$leTU, const int n)Qint tR or(int i H 0R i F nR i;;) Q or(int H 0R F n-1R ;;) Q i(compare(ta$leTU, ta$leT;1U))

    QtHta$leTURta$leTUHta$leT;1URta$leT;1UHtR

    37

    http://en.wikipedia.org/wiki/Big_O_notationhttp://en.wikipedia.org/wiki/Big_O_notation
  • 8/13/2019 Cs Class 12th Notes Kv

    60/283

    int Muantit?Rint ta$T100UR

    int main()Qcout FF ZInput Muantit?L ZR

    cin GG Muantit?Rcout FF ZInput num$ersL \n\nZRor (int i H 0R i F Muantit?R i;;)Q int H iR cout FF ZZ FF ;; FF ZL ZR cin GG ta$TiURcout FF Z\neore sortin&L ZR

    or (int i H 0R i F Muantit?R i;;)Q cout FF ta$TiU FF Z ZR

    cout FF Z\n"ter sortin&L ZRsort(ta$, Muantit?)Ror(int i H 0R i F Muantit?R i;;)Q

    cout FF ta$TiU FF Z ZRreturn 0R

    !wo-Diensional Arrays" 2-#imensional arra? is an arra? o arra?s. In oter wor#s, it is an arra? were eac mem$er o te arra? isalso an arra?. Consi#er te $elow ta$le

    De3laring and InitialiGing a -Diensional Array

    *ountry\Data Ma5 )lag Area ?sC /@ o5ulation

    "nited States 8,728,081 2:2,748,706

    *aeroon 5:9,550 19,597,082

    2uateala 106,680 12,449,960

    Italy 401,240 97,:49,140

    (an 212,570 2,557,759

    4"

  • 8/13/2019 Cs Class 12th Notes Kv

    61/283

    Like te a$o>e ta$le, a 2-#imensional arra? is ma#e rows an# columns. o #eclare it, use #ou$le pair o aopenin& an# closin& sMuare $racets. ere is an eampleL

    int num$erStu#ents*erClassT12UT90UR

    ase# on tis, wen initialiAin& a 2-#imensional arra?, mae sure ?ou pro>i#e a num$er o >alues tat isless tan or eMual to te num$er o mem$ers.

    ere is an eampleL

    #ou$le #istanceT2UT5U H Q55.15, :20.92, 87.06, 576.:6, 7.26, 76.05, 475.99, 7245.12R

    ro3essing a -Diensional Array

    inclu#e FiostreamGint main()Q

    #ou$le #istanceTUT5U H QQ 55.15, :20.92, 87.06, 576.:6 ,Q 7.26, 76.05, 475.99, 7245.12

    R

    Scan te arra? rom te 4r# to te :t mem$ercout FF Z+em$ers o te arra?ZRor(int i H 0R i F 2R ;;i)

    or(int H 0R F 5R ;;)cout FF Z\nDistance TZ FF i FF ZUTZ FF FF ZUL Z FF #istanceTiUTUR

    cout FF en#lRreturn 0R

    S!A*KS

    Stacs are commonl? use# Data Structures wile writin& co#e. It_s concept is reall? simple wicmaes it e>en simpler to write it in co#e. Consi#er tis situation. ere are a pile o 9 oos on a a$le. ]ouwant to a## one $oo to te pile. Yat #o ?ou #o ]ou simpl? a## te $oo on te * o te pile. Yat i?ou want te tir# $oo rom te new 7 $oo pile ]ou ten lit eac $oo one $? one rom te * until tetir# $oo reaces te top. en ?ou tae te tir# $oo an# replace all te oters $ac into te pile $?a##in& tem rom te *.

    inclu#e FiostreamG#eine +"X 10 +"XI+O+ S"CK CN'Nclass stacQ

    pri>ateL int arrT+"XUR Contains all te Data int topR Contains location o opmost Data puse# onto Stac pu$licL

    stac() ConstructorQ topH-1R Sets te op 3ocation to -1 in#icatin& an empt? stac>oi# pus(int a) *us ie. "## Value /unctionQ

    top;;R increment to $? 1

    41

  • 8/13/2019 Cs Class 12th Notes Kv

    62/283

    i(topF+"X)Q

    arrTtopUHaR I Stac is Vacant store Value in "rra?elseQ

    coutFFZS"CK /O33ZFFen#lRtop--R

    int pop() Delete Item. %eturns te #elete# itemQ i(topHH-1)

    QcoutFFZS"CK IS '+*]ZFFen#lRreturn NO33R

    elseQ int #ataHarrTtopUR Set opmost Value in #ata

    arrTtopUHNO33R Set ri&inal 3ocation to NO33top--R Decrement top $? 1return #ataR %eturn #elete# item

    R

    int main()Qstac aRa.pus(4)RcoutFFZ4 is *use#\nZRa.pus(10)RcoutFFZ10 is *use#\nZRa.pus(1)R

    coutFFZ1 is *use#\n\nZRcoutFFa.pop()FFZ is *oppe#\nZRcoutFFa.pop()FFZ is *oppe#\nZRcoutFFa.pop()FFZ is *oppe#\nZRreturn 0R

    utputL4 is *use#10 is *use#1 is *use#

    1 is *oppe#10 is *oppe#4 is *oppe#

    Clearl? we can see tat te last #ata puse# is te irst one to $e poppe# out.at_s w? a Stac is alsonown as a 3I/ Data Structure wic stan#s or Z3astIn,/irst utZ an# I &uess ?ou now w?.

    3et us see ow we implemente# te stac. Ye irst create# a >aria$le calle# top tat points to te top o testac. It is initialise# to -1 to in#icate tat te stac is empt?. "s Data is entere#, te >alue in top incrementsitsel an# #ata is store# into an arra? arr. Now tere_s one #raw$ac to tis Data Structure. ere we state te

    42

  • 8/13/2019 Cs Class 12th Notes Kv

    63/283

    +aimum num$er o elements as 10. Yat i we nee# more tan 10 Data 'lements In tat case wecom$ine a Stac alon& wit a 3ine# 3ist wic will $e eplaine# later.1 Array i5leentatione array i5leentationaims to create an arra? were te irst element (usuall? at te Aero-oset) is te$ottom. at is, arra?T0U is te irst element puse# onto te stac an# te last element poppe# o. epro&ram must eep trac o te siAe, or te len&t o te stac. e stac itsel can tereore $e eecti>el?implemente# as a two-element structure in CL t?pe#e struct Q int siAeR int itemsTS"CKSI'UR S"CKRe pus() operation is use# $ot to initialiAe te stac, an# to store >alues to it. It is responsi$le or insertin&(cop?in&) te >alue into te ps-GitemsTU arra? an# or incrementin& te element counter (ps-GsiAe). In aresponsi$le C implementation, it is also necessar? to cec weter te arra? is alrea#? ull to pre>ent ano>errun. >oi# pus(S"CK ps, int ) Q i (ps-GsiAe HH S"CKSI') Q coutFFZ'rrorL stac o>erlow\nZR a$ort()R else

    ps-GitemsTps-GsiAe;;U H R e pop() operation is responsi$le or remo>in& a >alue rom te stac, an# #ecrementin& te >alue o ps-GsiAe. " responsi$le C implementation will also nee# to cec tat te arra? is not alrea#? empt?. int pop(S"CK ps) Q i (ps-GsiAe HH 0)Q coutFFZ'rrorL stac un#erlow\nZR a$ort()R else

    return ps-GitemsT--ps-GsiAeUR

    &in/ed list i5leentatione lin/ed-list implementation is eMuall? simple an# strai&torwar#. In act, a stac line#-list is mucsimpler tan most line#-list implementationsL it reMuires tat we implement a line#-list were onl? te ea#no#e or element can $e remo>e#, or poppe#, an# a no#e can onl? $e inserte# $? $ecomin& te new ea#no#e.Onlie te arra? implementation, our structure t?pe#e correspon#s not to te entire stac structure, $ut to asin&le no#eL t?pe#e struct stac Q int #ataR struct stac netR S"CKR

    Suc a no#e is i#entical to a t?pical line#-list no#e, at least to tose tat are implemente# in C.e pus() operation $ot initialiAes an empt? stac, an# a##s a new no#e to a non-empt? one. It wors $?recei>in& a #ata >alue to pus onto te stac, alon& wit a tar&et stac, creatin& a new no#e $? allocatin&memor? or it, an# ten insertin& it into a line# list as te new ea#L >oi# pus(S"CK ea#, int >alue) Q S"CK no#e Hnew S"CKR create a new no#e

    i (no#e HH NO33)Q coutFFZ'rrorL no space a>aila$le or no#e\nZR

    4

    http://en.wikipedia.org/wiki/Buffer_overflowhttp://en.wikipedia.org/wiki/Buffer_overflow
  • 8/13/2019 Cs Class 12th Notes Kv

    64/283

    a$ort()R else Q initialiAe no#e no#e-G#ata H >alueR no#e-Gnet H empt?(ea#) NO33 L ea#R insert new ea# i an? ea# H no#eR

    " pop() operation remo>es te ea# rom te line# list, an# assi&ns te pointer to te ea# to te pre>ioussecon# no#e. It cec weter te list is empt? $eore poppin& rom itL

    int pop(S"CK ea#) Q i (empt?(ea#)) Q stac is empt? coutFFZ'rrorL stac un#erlow\nZR a$ort()R else Q pop a no#e S"CK top H ea#R int >alue H top-G#ataR ea# H top-GnetR Delete topR return >alueR

    IniE, ostiE and reiE

    IniE notationB + #perators are written in-$etween teir operan#s. is is te usual wa? we write epressions. "nepression suc as " ( ; C ) D is usuall? taen to mean sometin& lieL Z/irst a## an# Cto&eter, ten multipl? te result $? ", ten #i>i#e $? D to &i>e te inal answer.Z Ini notation nee#setra inormation to mae te or#er o e>aluation o te operators clearL rules $uilt into te lan&ua&ea$out operator prece#ence an# associati>it?, an# $racets ( ) to allow users to o>erri#e tese rules.

    ostiE notation ?also /nown as [%e.erse olish notation[@B + #

    perators are written ater teir operan#s. e ini epression &i>en a$o>e is eMui>alent to

    " C ; D . e or#er o e>aluation o operators is alwa?s let-to-ri&t, an# $racets cannot $e use#to can&e tis or#er. ecause te Z;Z is to te let o te ZZ in te eample a$o>e, te a##ition mus$e perorme# $eore te multiplication. perators act on >alues imme#iatel? to te let o tem.

    reiE notation ?also /nown as [olish notation[@B + #

    perators are written $eore teir operan#s. e epressions &i>en a$o>e are eMui>alento " ; C D. "s or *osti, operators are e>aluate# let-to-ri&t an# $racets are superluous.perators act on te two nearest >alues on te ri&t. I a>e a&ain a##e# (totall? unnecessar?)$racets to mae tis clearL( ( " (; C) ) D)

    'amplesL

    IniE ostiE reiE Notes

    " ; C D " C D ; ; " C D multipl? " an# , #i>i#e C $? D, a## te results

    " ( ; C) D " C ; D " ; C D a## an# C, multipl? $? ", #i>i#e $? D

    " ( ; C D) " C D ; " ; C D #i>i#e C $? D, a## , multipl? $? "

    4

  • 8/13/2019 Cs Class 12th Notes Kv

    65/283

    'ample-1

    :"$"$S

    ere_s a u&e crow# at ?our local &rocer? store. ere are too man? people tr?in& to $u? teirrespecti>e items an# te Sopeeper #oesnt now rom were to start. '>er?one wants teir o$ #one