Вы находитесь на странице: 1из 174

12- ge':lata(\Od.

13.

14: cout« 'Enter name: '; On» name; 15: cout ce 'fnl!flge : '; On »age; 16: cout « 'EnW df!p:ee: '; till» degIee;

17: }

18:}; I

19:

20: maln( )

.\ 21:{ . lf~ahls!tJIY

;;~ ::.~i; IfGeldatJf(fh01!Jr1 i \

.! 24: ~OR'I~

~ ~(d.ar·)~·

26: outfile. ..... ..

21:}

Microsoft Windows'

AUNG MYINT (M.E., AUSTRALIA)

CHAPTER 1 C++ BASICS

1.1. A Brief History of C and c++ 10
1.2. My First C++ Program 12
r: 1.3. Identifiers 15
1.4. Keywords 16
1.5. Variables 17
1.6. Constants 24
1.7. Expressions 30
1.8. Assignments 31 CHAPTER 2 FUNCTIONS

2.1. Create a Simple Function 46
2.2. Pass the Variables by Value 50
2.3. Pass Variables by Reference 59
2.4.' Default Function Arguments 63
2.5. Inline Functions 65
2.6. Local and Global Variables 65
2.7. Overloaded Functions 69
2.8. Recursion 73
2.9. Passing Structure Variables 77 ,.

...... - ... ~ :' ..

CHAPTER 3

PROGRAM FLOW CONTROL

3.1. The if Statement 82
3.2. The goto Statement 86
3.3. The if-else Statement 92
3.4. Nested if Statement 96
3.5. The while Statement 101
3.6. The do-while Statement 108
3.7. The for Statement 114
3.8. Nested Loops 120
3.9. The switch Statement 123
3.10. The break Statement 127
3.11. The continue Statement 129 \

............

.' .

" . ~~-- - .. -," _ .

CHAPTER 4

POINTERS AND ADDRESSES

4.1. Referencing Variables with Pointers 133
4.2. Pointers and Arrays 136
4.3. Pointers to Structures 140
4.4 .. Pointers as Function Arguments 142
4.5. Passing Arrays by Pointers 145
4.6. Pointers and Strings 151
4.7. Arrays of Pointers to Strings 156
4.8. Pointers to Pointers 158
4.9. Memory Allocation 164
4.10. Using Reference Variables 168 \

~'"

dI#'

\

eo I .....

1979 y,S ,S2:~8:GC\.)')oSm 94GQqm~§~G0Y.>84? I New Jersy §~~oS I AT & T Bell Laboratories '{->0(8a?8G~o? Bjarne Stroustrup ci?~C76~<-lIllO')')o%o~~Q')mS2:m C language o?94G§~B: C++ et?o? object-oriented programming language mSya?Gsr::1)'):~olmoSll 94Q)m C++ Qoo0501:n:1I C with Classes c894Q"~Go:~olmoSll 1983 a&SGh'OoSQ C++ d3£,)Q"~Gr,,,,8:d3oS

L IL L. ~ a L J -L- J LoT ~ Lf..l L

0')')0111 C++ m C o?94:;o9@90Y.>:o? version 01011 C++ source code G"6a? C compiler G"6GoT '(->

o c C Cf to'" t to.~' ceo C 0 C' t 0

run 1'CG$4')C ron C!(O? In erpre er O(94~:t:1l~mo)Gc\)1I mQ)~l.m ++ 0( q. superse or.

Gr,"'~olmoSll C language Q') C\)8d3!:1O')')94m~ro:GC\)')oS65 C++ Q')C\)~: C\)8d31:'10')')65:11 mSaGO')')

lj""U J L L· -L L'f L L J c:. L L· -L L L •

~moS I C++ language '{->94~S<x>8§~0Y.>:o? keyword G"6m C language '{-> Q01:Jj(:ci?G~ 003

k dOC id tif ,. ~ 0 c '1 ,G 0 C 0 _0 eywor G"6o( program '{-> I en I rer G"694G~'f. 94~:t:1lor.~mo)GO!" 9480( program QJl:o(

C++ m compile C\)803Ql:'l01:n:1I C compiler mo compile C\)8~: run Go:~8Q')0101l :D')oC:SC:S

L Lo-l IL Ltf LJ [jlj

c , C I 0 0 [§ 0 8 C 0 C .c ''1 C '1

O')~m~94G££ anguage m~G£ :::1)')::;01:'1 ++ m:;omC\)O)GC\)C\.)')m94 a I C\)O)mGaI')GQ')Q')OIIl

IL T To L T L -L L • 0 a IL iJ - J

C++ Basics

0.0 A Brief History of C and C++

C language dS Dennis Ritchies £~ m~olltOY.logOQ~ooo:>See:m AT & T Bell Lab 00 coS

L L IL 0 T -J '0 -L J L

dStG£Qt: 1970 ;;lc§iSOO interpreted programming language BCPL dS ~:~:GQ:::D':l:~OY.l~Solo:>uSll

\. T -l L J J l J t1 -L • L1

C C C C" I I I 0 0 A bl I 0 " C 0 CO" " C C

qe::§O)~mm 1': ow- eve programmmg ar ssem y anguage 0(0 O(O~C<f,0IOIl oomq;>O)

£~:m coo%:8tl:::D:G':.[c8 couSmoo high-level language ~ooch~uSOY.lJl:Go111 Ritchie <JY) ~cochg

TC IL L L tf La 0 IL 0 T. 0 iJ 0 IL jl

8tl:::D:G':.[G£OO UNIX system PDP-ll 0ch~')0 C dScochGO:> 0S:r;::;:~GOY.l G8tl')tG':.t~'):olo:>uSll

L t1 T 0 J L o- ~u 0 LJ 0

~8tl;;l1'P UNIX developer §So? Ken Thompson mco~: UNIX system d2 C ~ G~t:O)Gq:::D':l:

0:> uS GCO II C <JY) UNIX system 'P ~S8tl~~:O:>~~G'i"~olo:>uSll

o:>S~~oo AT & T mG£ UNIX system dS o:>m:i3aSGo:>oo8tl:::D:G':.[a8tlo:>ch 8tlco0)'):GCI.)')ch

iJT J T L en L OJ L t1 La 0

e ~"" CI 0 C C "e c. I C ~C "" C

'i":'l':1':C\fI[~GOY.l, anguage <JY) o:>g;>~CO Gmpc:::D':l:G061': 8tl'i":000l:(: anguage O:>0Y[j0~:~0IO:>o)lI

O)t:8tla5fl:oochm o:>m:i3aSG0)I')t:::D':l:GO:> Gmnt:mCX)ch~:8tlcoSot::D':l:008tl;%OOGOY.l high level

iJ m L ,,- 0 l,J- 0 t1 L 0 0 iJT J •

language 'P~:?:G",o? COBOL ~ low level language 'P~:?:G",o? Assembly language ~d2

o co" C" 0 C C 0 C~ " "e 0 COt CP/M to

~O?O:>O:>~CI.)')O? 1': O(m<X(o:>O(mtjGo!1I 8tl!38tl~'i"m rrucrocornpu er G06'P opera mg

system m<]~:~:G'i"a)oll1 high-level language 8tlG'i"~8tl~:~p:G'i"OY.lm BASIC language §Solo:>uSll 1979 ;;lc§iSOO Brian Kernighan ~ Dennis Ritchie dSo:ooGQ:::D':l:oo The C Programming

L J J T· LOlL 0 'T 0

La COp to H II C 0 C c,," c" c" e c" C " C

nguage 0')8foar ren Ice a 0')8f0O(mmG'i"<X(O:>GO~OIO:>o)lI GIGO~O? 8tlG0')8f0'P0locO?

I °fi to 0 t d dOC C 0 c" C " r,- v-v C "CI 0

anguage speo rca Ion G06ar san ar ~ ~~O:>~O:>~CG~:OI~:1I G;;lO:>00)'):1':Gtj.,qqc assic

C" 0" 'T' " C 0 C e co" C C c[9 K&R C _Q 'T'

(\)OG;;l1 QOOGOIII O:>0;;l'lmco~:!30')8tlom 0')GQ:~GO:>Q £')~~8tl01'):OOO:>cx)~ : co G;;ll 0Y.l

La -lJ • I,j. c:. L L 'T IL 0 -LoT c.::. iJ 0 Ci. La

CO" 0 C 0 C 0 C 0 C IBM C 0 fCC 1981 C PC

CO~:~Q II cocococosoccoc cococx mam rame GO:>cx)O:>COOG£=~ ;;lc§i000 GCI.)')m

c:. J -1.0 L L L L c.:. 0 L L T -L - J L J J

rodS ot CO') 0:> uS GCOII IBM d5O:>a) IBM clone Go:>mco~:Go1~Go1Go111 Microsoft dSuSdStm

L L L • 0 C. .J 0 L L

co ~ocx)~;;O:G8tl'JtG':.tCl.)')a) Windows 30X operating system dS C language ~oGQ!c8choo8tl;;lloo

ILO -,lea L t::1 0 L To 'T L 0 J

C08tl~I'):m C dS cochcoch0)lch0)lch coch~::D':l:OY.l~oo~:GOY.lo1:),):1I ~8tlGh8tlG£GO:><JY) C language

IL '1- L 0 0 OJ OJ 0 T. IL L:1 T 0

C C cr;::;: C~C "c

=c= Gqm'i"8tl~9e.:1')8tl~9[j0~:G00IO:>o)ll

1983 ;;lc§iSOO ANSI m C language definition dS 8tlQ8~ch~chlJl_: ISO (International

L J J L "I J tJ

Standards Organization) dSoochcocho:>tG':.QQ')oo 1990 ;;lc§iScn~ C standard document dS~chgS

L t1 a -L- J L J .- -lJ J L L J

§~~~t~olo:>uSll ro~0')8fS<JY) Standard C 01011 international standard C++ document d2 1998 ;;lc§iSoo8tl~:~chCX)chGogtQo1o:>uSll 0')0ch~8tlG££ C 1 C++ dSQdS:o:>chC':SGoT~ timeline

L J J lj L LOlL T T· L. -.. L [j JL

d2 8tl06uSo:>~ GC\?CI.)')a?,qG8tl'Jt (".0)'): (0. 0) 'PG0T§CX>'J:01o:>uS I GC\?CI.)')§e?0ln

C++ Basics

00

L'lUY.): (::>. o C and C++ Timeline

Year Event

I

1970

UNIX system a'3 minicomputer Gmlncr;)~:~·~8Gan8 Assembly

~ -0 J L C::lI. L

language ~ Ken Thompson mG'rOY.>:olrouSli

1972

C programming language o? Dennis Ritchie a: Q)m83¥:O?oB:

Thompson m UNIX system o? C t ~:J.)S§8Gq:01muSll

1978

Kernighan and Ritchie ~ ;Se:Q)oO(G'rOY.>:o} C Programming Language 4Y.>Sfoo? Prentice Hall m~oS,o§t~olrouSu

1979

C language q ~G§;;'B: Bjarne Stroustrup m C with Classes (1st version) q cr;)aJ9~9Gq:OY.>:o1rouSll

1980

CP/M 8080 microcomputer operatmq system G06~ oo~:§i '80} C compiler GCYJ Q)ro8cgoSpo1rou)u

1983

C with Classes pg~q C++ a?, ~g~G[p8:c\)olmuSll C q standardize O)oa~rooS ANSI mG£Q)m8Q)~:Go:o1rouSll

L L· 0 T c:.

, .. ~ ... ~ ._, .' ...... ..,,- ...,.. <\ ......... _. ' .... .,.....,-----

1985

C++ q§80'f'oo~:§l~8Gan8 Cfront interpreter o? AT&T mG~ §~~Go:o1Q)uSlI Stroustrup G'rOY.>:o} The C++ Programming Language 4Y.>9foO)~:cgoSFo1rou)J1 3~t'f' MS-DOS platform ooQ';)~:~tg8o) C compiler GQ)O)"':GoT (\)")ollRu

J Lt1l· 0 ~ tf

0::>

C++ Basics

1986

Cfront d3 MS-DOS g')ootGo:oloouSll MS-DOS C compiler ooS~d3

L J L L

Microsoft (),)G,,§~~~oloouSll

t .. _

1987

Borland (),)G, ~a5"t8a? Turbo C (for MS-DOS) ox: oo~ version Gooco0588G()')")e:Q S 01000511

o LL 0"

'.,. '.

1989

1990

C standard document ~ ANSI (),)Gi' ~'S~cf.,Go~oloooSl1 Borland (),)Gi' C++ compiler (for MS-DOS) ~§~~olo:>oSll

1991

Microsoft (),)G" C compiler (for MS-DOS) ~ §~~oloouSll

1998

ANSI t ISO ~(),)G" C++ standard definition document ~ . ml:t::x>a5 o2ScooSGo~s~~0100oSll

tf L J L lj'f. ij.

o, J My First C++ Program

C++ Basics

II Listing 1.1: My First C++ program

<~~ExlOl.cpp

#include <iostream>

int mainO {

II Display a message on the screen

cout « "My First C++ program" « endl;

return 0;

~ (0. 0)

3 program o? Compile C\(8~: Run o?d)cm~ 06~'-1IllcmID0)9.8'f' My First C++ program .&n0')G~8: GuT C\Y.)cmd5GOO Qu1c{3~~oSll 0 (0. J) d5r;::;:.~u111

,". ~J L o.-L • L L~C!.

caQuincy99



IDIDClJ8:'f'GOJ.9.o? II Listing 1.1: My First C++ program ~o? statement q.a;l1D0) double-slash characters II o? single-line comment ~GClT u1000Sn rn3G4od)0)

C++ Basics

GC16d2 rnyd? /* * / format ~8cf)~:GE>(:G():()111 Gl~E>(8~cf)~a5GC16~~: compiler m ~()lO)oSli

tOO c c §' §' GO, ,

commen GO)mC\)rn()o)GSQ'")Go)g) cn:-D:::DC:G(): C:G7.): C G program m cococoo

o L LoT -L- 0 J Ci. 0 0 L IL

c c c c "l 0, "l 'h"t 0,

(.J)O)(.J)O) <:'Ic:C\)c:C\)oomGSg)()11I program m run O)rnQIg)C\):-D: W I e space GO)C\)()

l' 0 IL T J L 0 J COL

ffect 0 "l c 0 t ~ 0 0 c t I"

e •• e g<:'l()I:J):1I coecococo com men g) I!Y)rngl'): :GQ:(.J)C\)QC commen me

11 IL LO J iJ- -L LO L-L

• C++ CJY) free-form language rn~l:rnl!Y):§So?rnC16a5 program d2 compile ar8 o?rnQl'f-> new lines I spaces I tabs I blank lines rnl!)~o? white-space character Go)dS rn8GO)rnGs~ :::DaSgaS~: compilation g) rnG.sotrnooa5gg Q'~CD?:~g) ~S()l

o L LoT To J tj J J 0 J ]1 iJ T • J l:j

c c c I" t" hit o. ~ 0, 0,

0)0011 O)l!)mOOG~ program IS Ing 'f-> W I e space GC160C rn::A,?:gt:llq.c~:~E>(c

source code Go)CJY) (.J)aScS Qa5~()lcS~goSli 2()g') Listing 1.1 ciS rnQcSG(;''''t:GQ!Qt

o LO. L L L L:1 J 'T -L

o 0, d ,0, "l'

Program a: run coccocco program co e Go)CJY) (.J)O)C\)gGO)')C:oy')G:::DQI')()IO)OOIl

L Lo-L • o !_II i,J-

#include <iostream>

int main() { II Display a message on the screen

cout « "My First C++ program"; return 0; }

,0 "l c "l §:>'o to. § 0 "l lost

rnmS<:'IGS() 10)0011 GIG cc COU a: program g)rn:::D: lC\)QOY.)()III <lOS ream>

LT'jIT oLe L J L L.-L

• #include<iostream> statement d2 preprocessing directive ~G;;lT ()1 0) oS II current program 'f-> <iostream> header ~tcnt&G0:~ #include directive mG<j> compiler d2rn~~G():G<j>0Y.)()111 console input/output rnC16a5~~:§tgoS classes I functions ~ global value Go)CJY) <iostream> standard library header 8toog)

To 0 L J

I b k to, ,0 "l' G h dO' 0 "I

g) ang e rac e < > ccococccoccecoxcoeacoicoc» G ea er occo compr er

J 0 L CL • 0 L L

t I' "l 0 0 0 "l c c ,0 0 ,0, h d 0, 0

sys em mGS supp y C\)()G0:()IC\) :;QC\)()IO)OOIl coocococo cocooc ea er (.J)CGmm

T L LO L L LO L L L ~o L

" I d c c ,0, b k t t (" ") 0 . ~ "l c

me u e C\(()G():;;lJcmOO~E>1c rae e GC16rnl!Y): quo e GC160C rn::l(:t:llE>1()lgOOIl

2()g') #include "myheader.h" ~OY.)~l:G()ll1

• int maine ) statement CJY)~E>1t maine ) function mG<j> integer(int) value mSy d? return ar8G():()1~ G6lPOY.)()111 maine ) function q. rnot'f-> ::JY.) argument ~ ~ .. ~()1:J):"

L

.-

• left brace { :::DGci)(Y)(J)')~Qt maine ) function moo statement block Goxi5

L -I 0 L

0rotG§§1t:G~~oS~ G§lPoy.>ol11

• cout « "My First C++ program"; ~a? .staternent (J)')~9t cout object d2

8d::D:~'~: My first C++ program ~m string constant roSad3 screen g)GoT

L t:1l1j L 0 L L J

cmGG'nt compiler d5 display (\)8~t:OY.lo111 cout (J)') BASIC language 00 PRINT

L L L

statement ~:::DGO")")8d0j20j201011 ~0j2OY.lm PRINT (J)') BASIC language ~8dSa5 8d~t:roSy§SGO~~ cout <Y.lJG~ std:: prefix mG~ compiler d2 ( cout (J)')roS[p: identifier G0'6~ ~0j2G[§-:>t:d2 ) 8d~Go:[9: standard input/output library header 8tmGsG:::Dal')a)roa58 8d8~Go:0Y.lr,:SolrooSll cout object ~ mCXY:l:m < < stream

L T ij- 0 L to ~ L:1 To 0 0

insertion operator d2 :::Dd5§l§~ol11 stream insertion operator < < (J)') data

object G0'6d2 output stream m~ro~Go:~ta?8d0'6aS output operator ~GaT (\)~:901rooSll §:>:~ direction mG~ data object cm:E>p8d9885t:d2 G~§G~olrooSll cin ~9t input operator > > d28d~:§l9'P0111 C++ statement roSyG9:[9:a?t: semicolon (;) ~8a5Go:Qo1~oSll ol~ statement :il::::D'):OY.ld5 compiler m~g)ol11

To -L J L 0 L J

< < end I 00 next line statement d5m:~t:OY.lr,:SolrooSll ol~~(])a5 < < '\n' a3

L IL L lj J L L·

C '1 c

G9:(\)~:90 lromll



GS'JaS:il:S'J:g)GQ!CXY:l:m return 0; statement m~Q8 maine ) function d58d(\)8

T L T J 'T • L -L L L

Q8~t:~: constant integer (0) value d5 operating system ~ return (\)8Go:0Y.l

-lLt1 L L

01011 right brace ( } ) :::DGcbro(J)') statement block Grod3 Gr,:~8:a3~::::D'):G~8:

o L lj'jl L~ 0 ~J

G 6lPOY.l 01 II ol~98 EX101.cpp program (J)')[9:~:01[911

o.~

Identifiers

C++ program roS?~ variables 1 functions 1 classes 8d0~a? element ~l:~(J)')olotG~[9: element d5t:g) s'J~d;roSa~ ~GSr;:;;rooSG(\)1l 3s')~d;Grod3 identifier a3 GaT OY.lo1011 (\)oS(\)oSGr,'",~oS

L J T c:. L J T~ T c:. 0 L LO 0 0 tj-'

~Qt identifiers ~0Y.l variable name GrooGo111 mJ~Ga:f.>d5 identifier roSad3:::Da5~a5m8da1g)

L "l L 0 0 OJT Lo L L J • J

C++ Basics

identifier O')Sy'P 0':>a?:GOJ (letters) I om~:GOJ (digits) ~ underscore ( _ ) character GO') u10665Qu10')oSn 81GugoS identifier ~ 0)2Q:84OOro()Y.) letter -::i3gmcfJ

o L· -1 • -I.- Q -L- L- L

underscore O')Syo§S6)u1goSn underscore (2) yGcm6 §Sa?,g6)u1::Ji(:n ~§la?,c\) :;SGcm ~3 identifier Ji[:GO')d3 system 84O')~O :i5::).)~:).)cfJgcfJ(XY.):65u111 C++

L • iJ 0 L 0 Te J L·

program O')Syoo CD~:)')~Go? identifier ~l:G"6()Y.) 2uIn salary I Amount I TAX I

GrossPay I sum_it I TaxRate 840)~:).)~~§Su10')oSlI CD~:).)~gao? identifier gJl:

G"6a2 G84')~'PG<.OT§(XY.):u10')oS I GC\?(\)")6~u111

"Amount"

identifier ~ G~ ~:84OOro()Y.) om~:r,;:S65gQu1::n:1I

-1.0 ]1. L Q -L - T tj L. -L IL

identifier In special character ( " ) GO') u165gQu1::n:1I

J 0 L· -IlL

4th_July

Kount-l num2

_C c c. ')

84&O')CDmC'l!Y.)CD~: CDoogaUI::n:n

L --Q ~ ~

id tifl C ceo ')

I en I rer In space OOOOCDU~£CDgQUI::n:1I

J 0 --.IT La -L IL

letter GO')d3 0':>ru:84~: (uppercase letter) -::i3gmcfJ 0':>ru:84G:)'): (lowercase

o L l ~ L· L L

letter) §~sp~ :).)d)'tcfJGu:a?,6)u10')oSlI 81GugJ? C++ ()Y.) case-sensitive §So?

840')~ MyFunc I myFunc -::i3gmcfJ myfunc :;Sci) identifier GO')()Y.)O')Sa~O')Sa

o L· L LaO LT- L

gO')::n::;Scmd3:).)d3~tu1n 2Uln area = pi * r * r :;Sci) statement d3 MyFunc =

ILILL L t1 LO L

myFunc*myfunc * myfunc 65Gr,''''t:GQ!Q6 :)')G~840')0')u1ol1

L· I,j..l -r-L It IL

ld tif 0 r,:;9. C C C -S; co,) C ') C •

I en I rer name 0( t::1lOO:)')G(\)")OO pg~~e::~~Go:aa 6)uIO')~n 81GUgo;:> G~a:r:oo

(32) ·'"d tif ,0 co C 0 C C ') C I C

84OOro CD:U I en I ler £O')OO~OO84mll::)')OOGroOOlnUIII ++ anguage 840')00

Q -1- L ,. L tl .. --.It -L- J 0

Q C C C , C k d O"d tif § C • § 0 '"I

:).)::).)£:).)O')gO')(xy'):O') ++ eywor GO')OO I en I rer GO')84 0) 84:),): lCDgQUI::n:n

T. J. 0 L 0 L LO -L IL

C++ program O')Saln identifier name GO')84G£~ 84::D:~latggoJ standard reserved

L JoT To L L:J 0 0 '11 0

0.<; Keywords

doC k' d 0 '1" '"I C ceo C • 0 '"I C ()

wor ccoco ++ eywor GO')CDGal UIO')OJII £')g~ooooO')gO')QCGcm :)'):CDQUIO')OJII~: o, J

o L 0 L· T c:.~ 0 IL "t • L LO -1

In C++ keyword GO')d3G(P~(XY.):u10')oS I GCD(\)")~~u111

J 0 L VI t1 . ~~

C++ Basics

~(l)'): (0. j) Standard C+ + Keywords

Non- Identifiers

asm else operator throw
auto enum private true
bool explicit protected try
break extern public typedef
case false register typeid
catch float reinterpret_cast typename
char for return union
class friend short unsigned
const goto signed using
const_cast if sizeof virtual
continue inline static void
default int static_cast volatile
delete long struct wchar_t
do mutable switch while
double namespace template
dynamic_cast new this
--'.. _. < -,.. •• _ ........... Variables

variable ~OY) program rom data value Gm65 CO'):::B~9d::D:~lro storage G£Q")mS~o1011

L 0 L L LO L l::J • T -1- L

c-» Basics

. bloC ty COG 0 '1 C ty 0 • bl "& t -, d t 0 - Q

varia e O(c:<f> pe name cnQ)"tIrQ)~olcn()')1I pe Cl:(0Y.l varia e q. rorrna of. a a !Jd"tll:!Jt)w:OC

::D05(,l05Go:0Y.l0111 variable cnSOlQ cn~8:Gcnd5 program cO(,l") I::J<l05::Da3GC'",8:rua3QGo(,loS ::D~

J L -I.e T L 0 L J t:j L tjJ L.-t • IL T.

005::D05~ data type mG~(,lGIP8:01~:1I type declaration <f> G§lP(XY):~!Jt)d28: !Jt)§~G'i'<f>01ol1

Cs-+ <f>0108~ data type GC{?m bool I char I wchar_t I int I float ~ double d2.§S01cnoSll

. bl ty 0 C " G C 0 C • d I h rt I d bl 0 0 0 '"I C

varia e pe Gc{?OCOJo~2:(,l().)Cl:(~c unsiqne long ISO long ou e o?'Cl:(OY.>~OIG::D:cn()')1I

The bool Type

011 bool variable ~OY.> true ~(,lO(aS false ~~ value (2) ~l:o?!Jt)o.?:§l~ boolean (logical) type !Jt)~l:!Jt)w:0111 arithmetic expression cnSy<f> boo I variable o? !Jt)o.?:§l(,loS~~8 expression c» true §S~!Jt)0l1<f> integer value 1 o? return or6Go:o1a3~(,loSll false ~~8 zero o? return ro6(,l") 01 II cnSmoSa3 integer cnSOld5 bool ~SG!Jt)")8GC'''"'8:Go:(,loSa3Q8 integer 0 em false ~S~:

L J L· L L LJ tj-' L -[ t:j t1

integer nonzero m true §S<f>01ol1 ~ (0. ?) <f>G(j)T§(XY):~ Exl02.cpp program em~~8 bool

variable !Jt)o.?:§l'i'~:o?G~(XY):01cnoS I GC\?C\Y)§~oll1

II Listing 1.2: Using a bool variable

#include -clostream »

int main() {

bool flag; /I bool variable

flag = 5 < 100; II Set a logical value to flag if (fl ag)

cout« "5 < 100 is TRUE."« endl;

return 0;

II Quincy 99

• boo I flag; e1?o? statement an identifier flag d2 type boo I ~ G§IP(Y)')u111

• flag = 5 < 100; e1?o? statement d2 logical assignment statement ~G~T u1 000511 5 an 100 cod)c05(Y)')~ flag oo~~:an True §Su1000511

• if (flag) ~(Y)') if (True) c\y'):~G~:(Y)')u111 True §So?~o;?d) cout < < "5 < 100 is TRUE." eBci3 statement d5 execute ro8~: console (screen) 00 5 < 100 is

L. L Llj J

TRUE. e1?o? string constant d2 display C\(8§(Y)')u111 ooSm05~ flag = 5 > 100

eBQ8 False ~Sci3~ood) if (flag) G£')d)m statement d5~G~~8:0 Gm~::lY.):oou111

l -L [j. 0 T L lj J .,.- 0 J

• Gpd)~:'f'Gq:CO'):o? return 0; statement d2Go;?S[8 maine ) function q_~C\(8 ~:::lY.):~8 constant integer (0) value d5 operating system ~ return ro8Gu:u1

~ 0 ~~ L L

a3~~0511 [§:G~S[8 right brace ( } ) ~Gcf.,oomGt program [§:~:G~8:d2

G§§')u1 00 uS II

c++ Basics

The char Type

011

char variable ~cm 8-bit bytes ASCII character set cOm character value GoodS

L 0 L

o 0 '1 c h 0 '·d tif C 0 ty h 'd ICC 0 C h hoe

~CYOIOOQ)II 20~ c ~at I en I rer OO0?or pe c ar -f. ec are cyo~Q)~E>1c c ar c ; ~GE>1:E>1c

E>101oooSlI ~ (0. J) ,[,GtoT§CXY:l:o? Exl03.cpp program '[' char variable 8d~:§I1'~:o?GE>1:CXY:l:01

C E 103 0 0 C 'C C Co, ~ C 'T' '1'

OOQ)II X .cpp program or run cymcm-f. o;?i'QJllcm0mE>1c,[, ++ ~atO)')G~JC:GOI (U'),[,OIOIl

~ (0. J) o?§~o111

/ / Li sti ng 1 .3: Usi ng a character vari abl e

#include <iostream> int main()

{

char ch;

/ / char variable

ch = 'C'; cout« ch;

/ / assign 'c' to ch II display 'c:

:

I -I

I

._I

8

[>].:

ch = '+'; II assign '+' to ch

cout « ch «ch « endl; II display '++'



return 0;

<J

- - ·1

• 00aJ8:,[, identifier ch o? type char ~G§IP[§: ch o? character 'C' ~ assign cy8Go:o1oooSu [§:GO?1E>18 ch q. value §So? C O)')a?:o? screen '[' display cy8§o1

o C C

(\)';l~Q)1I

C++ Basics

JO

• CC'lhOh ct tant t+t s assi C 'l CfR C G<ji')mool!)~1 C err c ara er cons an + il. assign C\(UGU:UIOO().)1I lj:GO?1~C

cout « ch « ch; ~oo statement mG£ C ooro:G£')05oo '+' ~Gif>oo (2) ~

l. T L T J L

o CfR d· I cr:_ 'l o c C 'l ~co C Co' ~c -r-

errmulj: ISP ay C\(UljUICD';l'=l()')U G'Gt:1J9'f.'"'6<jiuJIl0)')'(' ++ ~O?OOGt:1JC:GUI C\)')

O)')ulull ~ (~. G) d2[§~ull1

BlQuincy99

~ (~. G)

The wchar _t Type

c++ compiler '(' wide character class library ~G'i"'=luS~~8 wout object d2 Sd~:Bl[9: : 6-bits wide char data type mG£ character Goo().)fR: stream output CD6Gu:g8uloouSll

T 0 ILlj L L

The int Type

:)1 int type specifier 1006'(' plain signed integer 2uOO int counter; ~O)')~~l:~~a? signed int I unsigned int I long int I short int 1b~~§9 Sd~l:~l:~G'i"[§uloouSll int d2 Sd~:Bl'=luS~~8 range m -32768 to 32767 r;;:SuloouSll short int ~Sdoooouloll unsigned int ~Q8 range: 0 to

Cj Te ILIL t t

65535 §SuloooSu signed long int q. range ()J) -2147483648 to 2147483647 §S[9: unsigned

long int q. range m 0 to 4294967295 ull1 ~ (~. ~) '('GtPT§CXY.):o? Ex104.cpp program '(' int

. bl • C ° ::rr: 'l C

vana e ~:'l'~:err GtP'ljcxy')WIOO()')1I

J~

c++ Basics

r' _j l:XIUq,CPP .. -\a&1J fa
II Listing 1.4: Using an int variable. ;..
......
#include <iostream> ~
int main() ,
{ ,
,
int num; II int variable;
-
num = 12345; II assign 12345 to num
II di spl ay the num ber ,
(out « "Number equals" « num « endl; ,
return 0; "
1.....0.
} -- ~
:, I ." lUI .. , .-.1 [E.:: JII Ex104.cpp program d? run d205gu5a?~8 0'6~qjII0)')~m~8'P Number equals 12345 ~

GoT C\Y.)olcS~gu511 ~ (0. Gl) d?§~oll1

IDQuincy99

~ (0. Gl)

• Q)Q)~8:'P identifier num d? type int ~G§fPoloou511 G,p05l§: num d? 12345

c co, . c IR 'lOt' ta t c, 'IR

OC1l')i':ooi'<f:<f. assign ,,?OG0:tj: num ~ va ue 0( s ring cons n ooQ)Y<f.D6tj:GO':>1

display (\)8h~8:O)')olulI

L tj L

c- ... Basics

JJ

Floating-Point Numbers

c++ 'fJ 8::m~orn~:oo~l:ooO)'): (floating-point number) (3) ~l:d2°O~:§l~8010)oSll 003 '"") float I double ~ long double o?,o1011 float ~ range CJY.) 3.4E-38 to 3.4E1038 I double ...-.ge co 1.7E-308 to 1.7E308 ~ long double ~ range CJY.) 3.4E-4932 to 1.1E4932 o?, §S 3:D05~05al05GO)m OG:D~(]J0501:n:1I compiler oo~:ooO)'):GoT ~0)~o10)oSll 0 (0. r;l) 00

J (J 0 L L IL iJL ILC L I.;.J

.:.c::n:a; Exl05.cpp program CJY.) float oo~:§l,,~:d2G~T§CX)'):o10)oS I GO?(xr:{~3t§o1u

:::J Ex 105.cpp

)" ,i'e LC JC!t. 1 •. ' &4 i 1#;:".4=0 :tt::::1fmii

:'!'" ,IO....L

II Listing 1.5: Using a float variable #include <iostream>

int .mainO

{

float fnum; II fl oat vari abl e

fnum = 1.234567; II assign a value to fnum

II display the number

(out « "fnum equals" « fnum « endl;

return 0;

:......

8

> .••

program d2 run ~0598 OJ~~llO)')([)m98'fJ fnum equals 1.23457 o? GoT C\Y.)o163~~oSu : (0.00) d2§t§o1u default OOG,,~ 3::m~ (5) o?:O)')oG~T§o10)oSll

< I

III Quincy 99

J?

~ (0.00)

c++ Basics

Character Constants

o.G Constants

C c co r,'V"\c" o c r,;:c , I 0 0 t t 0 ++ program rolDy,[> roof<f:~Gt:1 .... cecoo mof:Go.:>l:jlDGofO? va ue "lll:Go;sO( cons an s C\(.

GQT 01 o: oS II constant ~oS~S~Jl:~ro~GOY{ (5) ~Jl:oll1 (0) Character constants (j) Integer constants (~) Floating-point constants t- (J) Address constant ~§S§olrooSll

Character constants ~OY) single code (' ') Go;st-8oSa.n:o? char value Go;sa?~o?ol roo5lI roSmo5G~ character CJY) letter §S§S digit §S§S I blank a?G0Y)8 character ~GQT ~S[rooS G(\)Il character Grog) numeric value Gro~~olrooSll ~ro~8:Grod3 ASCII (American Standard

OJ OJe,j TL 0 L

Code for Intermation Interchange) value Go;sroGft-o.:>oS'toS'[>oll1 20g)

chi = 'A'

/ / ASCII char constant

/ / char constant expressed as hex value / / char constant expressed as octal value

ch2 = '\x2f ch3 = '\013'

~20g)g) backslash \ o.:>G~roGrod3 escape sequences cS GQT 01 o» .S II ~o.:>G~roolc\y)Q8

J 0 L L· -L

character constant '[> ~:g.,:o? S[~as~:QJa5roSy ~Gofol@1I \a ~()1C\Y)S[8 audible bell character

§So.:>~ \n ~S[8 output data roo;sa5 newline character §SolrooSll ~().)'): (0. ~) '[> constant escape sequence G"da?G(J)T[9a.n:olrooS I GO?C\Y)§~oll1

~().)'): (0. ~) Constant Escape Sequences

Escape Sequence Description

\' Single quote

\" Double quote

\ \ Backslash

\0 Null (zero) character

C++ Basics

J9

-

- Octal number (nnn)
\Onnn
\a Audible bell character
\b Backspace
\f Formfeed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\x Hexadecimal number (nnn)
\? question mark teger Constants

Integer constants a?0'X) type name Go;?§So? long ~goraS short I signed ~goraS r.sjgned fixed value Go;?o? ~a?O'X)o111 integer constant '['0 (3) ~l: oo8~CXY):o1G~:O)oSll (0) Jedmal constants (base 10) (j) Octal constants (base 8) ~ (~) Hexadecimal constants .ese 16) ~01011 decimal constant O)SyOJ.)~9.t :xc~mG;'> (9) mm OC1f)~:Go;?~orGo1t:§SG;,>O'X)o111 constant m OC1f)~: (2) ru: ::BgmaS (2) ru:oodJ 801GsgoS;;8Qt 038a:):oC1f)~:0J.) ~~r,;:Sc3gQo1OJ:1I

J T L La L L l T L -L l T L c:.t:J La -L IL

XJ5~: constant value OJ.) ~aS"iaSCXY):o? lower bound ~ upper bound &:m 0)~~:Go;?0

- 901goSil C++ program m rudJ~9ao? decimal constant Go;?m 20m 0 I 1234 I 32700 .)1011 GandJo1 constant GO)mGO'X) decimal constant GO) gmaS~o1OJ:1I

, o· 0 L~ It

23,456 54.68 32 591 0987 956705

constant '[' comma ( I ) o1~g9.o1~:11 Go.:Dgru:-0: o1c3gQo1OJ:1I

c:. LO -L IL

c ceo "l

space mmruoalsrugQOIOJ:1I

o ~T ~ -l IL

1D3:G'dmQ')0J.) ~~r,;:Sc3gQo1OJ:1I

C Q -L- L c:.lj La -L Il

constant value OJ.) upper bound limit o?GmpG;,>o10)oSl

G1;;8Qt decimal constant gr,;:So1OJ:1I

L -L lj It

JJ

c++ Basics

Octal constant GOJm ::l(~~ (7) romo(1T)t:GOJt. O(Go18:§SG;;OJ')oll1 octal constant 'it:

_ Q coo c. C 0 C'\ '1 C 0775 ~ C '1 C

::lJG8d'JcOG coo~:O(1T);;:O( ::l(~~l::lCX)'):Go:E>(O(g()')1I 20g') ij00()')().)11

Hexadecimal constant GOJ9GO':l1 ::l(~mG;; (9) rom O(1T)~:GOJ~~o;r (a) mG;; (f) ro 00 letter G(),)~ 0Go18:~SG£OJ')oll1 hexadecimal g~:=fjG8d'J8~ c88a:):~mQ') (2) ~d5 Ox =fjgm05

o To L L1 T J T La L Q -L- L L LO L

OX ~~C\(8Go:E>(olguSll 20g') Ox54fa §Sol()')uSll

Floating-Point Constants

Floating-point constants ~OJ') base 10 d5 ~G~~ro real number G()')d5 ~~o1()')uSll

L L L:1 0 0 L L L

g t toe (fl t· . t) ,~c 0 eeoc ( t) .. ,~c~c

8 cons an GOJO( 8::mgO(1T)<j>: oa Ing POIn ~G;;~ij0G0 ~g0«)') room;;: exponen y0~ij0ij0

::lJ05'i05d?,qo1()')uSll 20en 1234.56 I 2E-8 I 2.55E+38 ~ §So1()')uSll G8d'JoSol constant GOJa?GO':l1 C++ 00 floating-point constants G(),)~ g::lJ05g0501::),):1I

o L· J IL

"Hello C++"

"MyanMar"

"25/10/03"

1234 15E+2.5 12e 5

String Constants

String constants ~OJ') double quotes (" ") roen GQ:CX)'):ro~mQ')G()')d5 ~~OJ')o111 ~

L J "I • C) -L- 0 L L L

, bl k '1 C '1 C C C C '1 C 0 C C '1

~m soccococo an 0 ICD:-D: QO tcoco II ~m Q') ~ GQ~()')m :J')()')GCD')mo (Qg().)CD gm£ cocoo I:J'): II

;> -L- 0 J c.::. -L C) -L- -L 0 -L L· T. IL

G8d'JoSG(J)T§ol string constant GOJa? C++ program 00 CDoS~o1()')uSll

c-- Basics

Js

':JExl06.cpp , ;\;;;J\W1 ft.t
II Listing 1.6: Concatenated string constants ,.
I-
#include «lostream»
,
int mainO I
{ =>:
cout « "This is the beginning of a very long mess aqevn" = ,
.'
"that spans several lines of C++ programming code.vn" !
"This format allows a program to build lnnqvn" !
"strl ng constants without gOi ng past the\ n"
"program editor's right marcln.vn''; i
I
return 0; ~
} ~
<' [>J.:: ~ (0.00)

• Exl06.cpp program ci3 run c8oS~uScSQ8 m~OlIlQ'Y.)~ ad~c8GoT C\)')Q'Y.)ci3GOO Qo1c8S~uSll

J L L L -L oT-"'" J L L L o·-l •

~ (0. oj) o?§t§o111

IDQuincy99

~ (0. oj)

• string constant ad~~~:o? newline escape sequence \n ad~:§tB: ~Gq:§8:

r;;_c 0<;' c~ c 0 c C C d" I C~OC 0 "I C

GPJ:ij9 oo<{Gad~~e:I:ooQ):rO( GO'Y.)c~GmpGGPJc ISP ay ,,?0tl:rc:aaqolooOJIl

J?

c-« Basics

Enumerated Constants

011 program OO?):;)(1) o:)Cf)~oScm=ci) data set OO?)Qd5 type OO?)QG'dGs~ O)oS~oSG():QI8Q8

L J J. L L L TTo J !J -L

enumerated constant d5G'd::D:~lc{3Q()loooSll :)()(:Y.) COLOR d5 enumeration OO?)Qc{3G~~G0:~:

L L L:1 LO -L eLL L. ~tl J t1

(RED, BLUE, GREEN,WHITE, BLACK) a?a?G'dGEf>8 (5) ~l:~O)oS'joSGmQJ89_8 enum COLOR

{RED, BLUE, GREEN,WHITE, BLACK}; a?a? statement a?G9_=9_89_()loooSll COLOR a?cm(T) enumeration type name ()111 RED G'dooch symbolic constant d5 0 c{3O)oS~oS()loooSll (J)I~cmGO')

o L L· J IJT a

d5 1, 2, 3, 4 c{3 G'd~G'dQ)8c{3ch O)oS~a5G():O)'):(:Y.)()ll1 Gl~~ma5 enum COLOR {RED=50, BLUE,

L L· C L J 0 J J L

GREEN=500,WHITE, BLACK}; ~G§§,)G():~oSa?9_8 BLUE = 511 WHITE = 501 ~ BLACK =

502 d? enumeration type c» G§-:>8:roO)oS'joSG():06-':'j':l()111 ~ (0. 0,,) 'j':lG<PT§cm:a? Ex107.cpp program a?GC\?C\Y.l§~()ll1

'=:JExl07.cpp

II Li sti ng 1 .7: Usi ng an enum erated constant #include «Iostream»

int main() {

enum days {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; int choice;

cout « "Enter a day (0-6): "; cin » choice;

if (choice == Sun II choice == Sat)

cout « "vnlt's a weekend dav.vn":

else

cout « "vnlt's a weekday.\n"; return 0;

_<J __

J

~:

, ~ (0. 0,,)

I i ,

, ,

!

[VJ I~ ..

J11 G'dyG'l' program a? run a?ch~: Enter a day (0-6) : d? prompt OO?)yG()T C\Y.la?G'dQl'j':l G

00 c ('~ ENTER 0(' 0 c "It' k d d 0 rr- '1 0(' c • ( ) o~ c

O(~(),)CD~tj: ~()C\«()')cmof. s a wee en ay. ~G()I C\Y.l()Ic\)~~OJIl « o, 09 O(t::1~o

C++ Basics

J(f)

III Quincy 99

• Q)Q)aJ8: identifier days d? type enum ~G[§lPB: {Sun, Mon,Tue,Wed,Thu, Fri, Sat} a?~ assign orcSGo:olmoSu identifier choice d? type int ~G[§lPoloooSu

• cout « "Enter a day (0-6) : "; ~d? statement mG'l' choice oo06ch data ClJ~)Go:g prompt rocSGo:oloooSll cin > > choice; mGS chice ooooch data d3 0

C!. L· L T 0 l

00 C ceo ')0

rol':'\mClJ~GO:b)U)d:)OIQ)1I

L°'L' CJ., L L·

• 81~98 if (choice == Sun II choice == Sat) statement mG'l' choice em Sunday (=0) ~b)O(aS Saturday (=6) c\y'):~O'YJd?~Q)SolmoSu 0 §Sd?oo0605 if ( ) Gsnchoo~oo~m cout « "\nIt's a weekend day.\n"; ~d? statement d? execute orcS'P§SoloooSu 3G~ "6~oJllO'YJ It's a weekend day. ~GoT C\Y.)BGolll ooSmoS~ choice 000605 data d? 3 ClJ~GO:98 It's a weekday. ~ display orcS B'Po1u y (0. o~) d?[§~oll1

III Quincy 99

c++ Basics

CounterPtr = 8tCounteri FuncPtr = 8tDoFunctioni

/ / address of a variable 1/ address of a function

Address Constants

c++ program GOOg') pointer GoocE!n::D:~l~uSaSQ8 Address constant GOOci> !n::D:~l

-0 J 0 L L (j L -I 0 L L (j

QGang')ulll variables I function GOOg') memory address GOO 2.uloouSll 3 address GOOcE C++

"t • J 0 J 0 '}I -0 L

program g') GGn05ul!nci.,8: reference C\)8c8QuloouSll

J L L L·-L

0.7 Expressions

expression aSan ooS~:ooSh-.:~gGso? constant GOO I variable GOO I array element

L ~J 'jl Teo 0

GOO I function call GOOcE operator Goo£~0508(X)'):anuloll expression ooSO)cEG~1':I8:c8oSQ8

o 0 L 010 L L tjjl L -I

oo~a:ooSO)ci> return C\)8Gu:g')ulll C++ expression Good5 £~s,)G<.D'Tt':Q~uSa3Q8 count * 10 £

T L L L L J 0 L TILT ~, tf "I L -L T·

1.8*( degC+ 32) ~an~Jt:Gulll

Arithmetic Operators

G0Y.>8:j9 I !3l~~t operator GOJ ::nuS,S~Jl:~C:\)1I arithmetic operators I unary operators relational and conditional operators !no~::D~§~ !n~l:!nO'):GOJ ooS~§3:~anGulll ~!31GOJ~:~8 expression ~an§SC\)')anuloll C++ 'f>ulota} arithmetic operator GOJo? (!lQ)'): (0. 9) 'f>G<.D'f§ (X)'):uloo05u 3 operator Good5!n::D:r,',,(R: oooSan O)loSanGood5r,'"C\)O Qg')ull1

o L L (jlt1 0 ~ 0 Lt1I. L -IJ

(!lQ)'): (0. 9) Arithmetic Operators

I

Symbol Description

+

Unary plus

C++ Basics

Unary minus
* Multiplication
/ Division
% Modulus
+ Addition
Subtraction 0.6> Assignments

A· t t t teo C • cor,;, C 0 C _0 0 '- t

:)11 ssrqnrnen s a emen O)(!)Y(J.)')arqc expression O)(!)yO(Gl:j~c:C\(mC\(, q~(\)')O? re urn

value d2 variable O)Sy~ assign C\(8Go:'{>oll1 ~ (:). :)(5) '{>G~T§cm:o? Exl08.cpp program (J.)') Celsius degree O)SacB 1.8*C+32; ~oo expression cB 8'i):).):~,IR: degree Fahrenheit cBGr;'",.,8:

L L L • L L L:11.l::::f L L:f..l

'- '- r,;,c "I C

(\)GO:O? program l:j(!)Olo)o)lI

.. ¢ i." a~ _

II Listing 1.8: Assigning an expression

#include <iostream> int main()

{

float cel, fah;

cout « "Enter a degree Celsius: "; cin » cel;

fah = 1.81fcel + 32;

cout « "Degree Fahrenheit = " « fah « endl;

return 0;

I

-'

" '

~ (:). :)(5)

C++ Basics

mQuincy99

JI Ex108.epp program ~ run d?a5~oS~~8 OJ~<-{Ill0')')0m~8'fl Enter a degree Celsius: c\?, prompt ooSyG()T C\Y)()1c8~~oSll 99.9995 ~~a5oot2@: ENTER ~8d?a50')')~ Degree Fahrenheit = 211.999 c\?,G()T C\Y)()1@1I ~ (:::>. :::>?) ~§t2()111

C++ Basics

?J

• 00~8: identifier eel ~ fah ~~ type float c\?,G§[p@: Enter a degree Celsius: ~o?ooG[§:>8: screen 'flG()T C\Y)Gan8 eout < < "Enter a degree Celsius" ;

C 'I C

mG'¥'C\«)G<.>:() 100Wil

• ein > > eel; -;;Sci) statement dSGQ:cx:r:nO')')Gr;::;:::,....8 eel fTtJooa5 data dS user 0')

L 0 L -L ~J. 0 L

keyboard mG£ga5oo:-tSG():Q~()111 eel fTtJooa5 datadS 99.9995 dSga5ood;G():()1~J)

Ttl Cl. -LJ 0 L Ltl t:.i.

• eel = 99.9995 c\?, program m :::>3qp:@ci?Goy'! fah =1.8*eel+32 = 1.8*99.9995 + 32 = 211. 999 -;;Sci)fTtJG~dS OG::D£d;:::D:~:00d)w()100oSll

L· ~ L L TC L t1 0 It

• fTtJG~dSood3G<.>:afTtJood) eout > > "Degree Fahrenheit = " > > fah > > endl;

tJLL L· 0

ci?o} statement mG,¥, OJ~<-{IllO')')'fl Degree Fahrenheit = 211.999 ci?o}OOG[§:>&

G()T c\y)Gan8C\)8G():~()111 < < endl expression ())') next statement line dSm:28: ~

L J LILl

C C ~'

fTtJ0;5m oot2G~:o::r:>:O')')() ()II

_ogical and Relational Operators

c++ language 1fJ olo8o? relational and logical operator GOJ02 (!>.OY.): (0. ~) 1fJG<.DT[9()Y'):ol ..s. ~ operator GOJo?~o.?:§lB: expression (2) yo? ~8:Oj'e~8:QoSll G'l"xf)[9: true (or false)

o t c o c 0 ') C

e or re urn <.\(Oyc:~qolm()J1I

(!>.OY.): (o.~) Logical and Relational Operators

Symbol Description .

&& Logical AND
I I Logical OR
Unary NOT
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
-- Equal to
!= Not equal to c++ Basics

~~~.cpp I_lrri~

II Li sti ng 1 .9: Usi ng the rei ati onal and I ogi cal operators ¢

#include <iostream> int main()

{

double a,b,c,s,area;

cout « "Enter three sides oftriangle\n"; cln » a» b » c;

if «a+b>c) && (b+c>a) && (c+a>b)) {

s = (a+b+c)/2;

area = sqrt(s1r(s-a)1r(s-b)1r(s-c));

cout « "\nArea of triangle = " « area « endl;

}

else

cout « "\nTriangle can't be formed";

return 0;

~ m ...

~ .. u~

_ J

<.1

~ (0.04))

JII atlyG<j> program d? run a?a5'=loS~E>}8 <"'6~<-lIllO')')lOmE>}81fJ Enter three sides of triangle ~ prompt rof>yGoT C\)'Jo1c3~'=loSlI 3 <space> 4 <space> 5 a?%a5co~[§: ENTER ~8a?a50')')\ Area of triangle = 6 ~ro atlG~~roa5Go:o1cS~'=loSll 0 (0. 0(,») ~C:;:~o111

L· ~ L 0 • L c, Lr:.Ju..

c++ Basics

?9

• 00~lt: program OOOO:D:r,:lIdJS a I b I CIS I area ci3m identifier Goooooor:h

IJ J Lr:1 0 l. 0 0

data type d? double ~G§[pGo:o1ooJSn

• Enter three sides of a triangle ci2c? prompt d? display ~GoT?t:[9: a i b I C oo~~:GOJd? ( space [p:[9: ) keyboard mG1'~r:h<x)~Go:Eqo1IdJSII a I b I C ~~ oo~~:Good3 a=3 I b=4 ~ c=5 03 gr:hax{~ldoSc801SI1

TL OL To Letl Ci.. L L·

• 31ci2Eqt GO:cm!o? data GOJ~§o§SId§Sci2O)')d? relational operator(» ~ logical operator(&&) ~Syd?oo~:§l[9: 0SG:;n:01ooJSn ci2~O)')m (a = 3) + (b= 4) <:fY) (c ~ 5) OOr:hO!IdJSII (b = 4) +(c = 5) m (a=3) oor:hO:ldoSn (c = 5) + (a = 3) m ,(b=4) oor:ho:IdJSci2Eqt s ~ area ~d?:;nr:hOJr:h[9: Area of triangle = 6 ~ display ~GoT Go!o1c3~IdJSII sqrt( ) function <:fY)ci2Eqt OOGo1t:C\)qsC1!'Y)d3~:ooSy

" c c 0 c c 0 0 c:" th f cti c ~ c "'I c

9.~000om1':Eqc:ac§PGo:~cO? rna un Ion 000Y['j00fO)()')1I

raQuincy99

c++ Basics

Increment and Decrement Operators

c++ 'P o108d? Unary operator G06~ <-"OJ'): (0. (5) 'PG<PT§an:01cnoSll C7J1~GroS~ 8 operator Gcnd5m::D:~~: variable Gcn~ cn~a:Gcnd5 m65:mGroy')(\)tiGo:cSQo1cnoSll

- 0 L L L:1lC::1 0 -L· T L 0 L L ".. L L· -L

Symbol Description

<-"OJ'): (0. (5) Unary Operators

++

Increment operator Decrement operator

~Exlo10.cpp A¢ 44 P .aa j.l > 41 "I( Pi 2 U44 ,. 4

P4 GJlhlti

011 <">6J~G~~ ~ (0. JO) 'PG<PT§an:o} ExlOlO.cpp program ~ run c?d3QoS~q8 Unary

operator G06mG§:>8:o?d5qo1cS~QoS I GC\?C\YJ6~o111

II Listing 1.10: Using increment and decrement operators

#include -clostream» int mainO

{

int k ounter, 01 dCtr, newCtr;

oldCtr= 1234; newCtr = + + 01 dCtr; kounter = newCtr--;

1/ oldCtr = 1234

II newCtr = 1235, oldCtr = 1235 II kounter = 1235, newCtr = 1234

c++ Basics

.,

...

cout «"oldCtr ="« oldCtr« endl; cout «"newCtr =" « newCtr « endl; cout « "kounter = " « kounter« endl: return 0;

• I!) I!);;lJ t: program 'f-'84~:§l~<\i kounter I oldCtr ~ newCtr ~e? identifier (3) y d5 type int 03G,;:;:::c::..,olmoSll G£')oSmSG~t:g) oldCtr d5 1234 03 assign ru8Go:

L L· ~l:l..l T U.J J L L. L

olmoS II

• oldCtr m~~:o? increment 84qtnc8GO:~: newCtr ~~Go:olmoSll ~G~ newCtr = 1235 ~ oldCtr = 1235 §Sqp:ol~1I

• ~mS;;ll kounter mf.8:65 newCtr = 1235 ~84Qt assign ru8~: newCtr mf.8:65

T l L T· -L L L::1 T L L

decrement nc801moSil 3G~ newCtr = 1234 §~§Sqp:ol~1I



G£,)oS-;/): statement (3) ;;lO')G£ oldCtr I newCtr ~ kounter mf.8:Gm65 mS;;l;;llt:

T 'L L T To TL 0 L L iJ

II Quincy 99

Compound Assignment Operators

c++ 'f-' olate? += I -= I /= I %= I «= 841!)~e? Compound assignment operator GOJo? ~UYJ: (0. '2) 'f-'G 0T§ cox 0100 oS II 3 operatorGOJ84~:§l~: statement GOJo? short form

~ c c r,'", co,) C' tOt 0 0 ') C

(jI!)G84.)CGtl.Jc:Gq:~qolmu)1I 20g) sum= sum + coun s; or sum += coun s; ~Gq:~qolmu)1I

C++ Basics

~().)'): (0. 2) Compound Assignment Operators

Symbol Description

+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
°/0= Modulus assignment
«= Shift left assignment
»= Shift right assignment
&= Bitwise AND assignment
1= Bitwise OR assignment
A= Bitwise exdusive OR assignment 011 ~ (0. J\,) ,?G{9T@CXY):o} program 0')')et?~8 multiplication assignment operator 6?rn

Bl[9: Go:CXY):o}d5~:OJSyq. factorial 6?§PGO:o} program 010 I GO?C\Y.)6~0111

• Q)Q)~8: program ,?G'd~:Bl~K\> identifiers i ~ num ~6? type int a:>G;IO":lII~ fac 6? long int ~G61P01OJoSll i m counter 0111 num co O6l~G~~ t::U+f" ...... §PGo:~8o}d5~:0111 fac m num! d? store Cl(8~~ identifier §S01OJoSll

c-« Basics

'_....JexIDI!.Cpp l-.llt:l.ll EI
II Listing 1.11: Using a compound operator ""I
r-
..
#inelude <iostream> .7
.'
int main( )
{ \
<
int i, num;
long int fae; ..
eout « "\nEnter a number: "; 3
ein» num;
fae = 1;
for (i=2; i <= num; i++)
fae"lt= i;
eout « ''\nFaetorial of" « num « " is " « fae « endl; !
,
;
i
return 0; ,__;
} ~
_~J_ .. 1111· .. -. I [!] .:: • cout < < "\nEnter a number: "; a?o? statement mG'l' prompt mStGuT COOGu:E18 keyboard mG'l' 10 o?~oSCDt&o1gu)1I 81a?E18 num = 10 ~ cin » num; mG'l' assign 0?8Gu:o?oSu1~1I

c++ Basics

-

fac * = i... fac = fac * i

2! = 1 * 2 = 2 3! = 2 * 3 = 6 4! = 6 * 4 = 24

5! = 24 * 5 = 120

6! = 120 * 6 = 720 7! = 720 * 7 = 5040

8! = 5040 * 8 = 40320

9! = 40320 * 9 = 362880

10! = 362880 *10 = 3628800

Conditional Operators

i = 2 i = 3 i = 4 i = 5

i = 6

i = 7

i = 8 i = 9 i = 10

I

..... - ,.~

variable = <test> ? exprl : expr2i

JII ~ (0. JJ) ~GlOT§CD'):o? program <.J)')~q8 conditional operator a?8'do.?:§l~: GO:CD'):o?~f

(3) yrom 8'd~:~:~~:a?~Go:o? program 010 I G~C\Y.)6~0111

"II 8 program a? run o?a5goS~q8 "6~~1l0Y:l~ Enter three numbers : ~ prompt O')S~ GoT C\Y.)~0111 keyboard mGt 150.56 I -500 ~ 2500 ~a?~a5ro~Go:~: ENTER key ~8o?a50Y:l~ Largest number is 2500 a? "6~~llOY:l~ display C\(8§Go:01cS~goSll ~ (0. }5) a?6~0111

c-» Basics

_ _jEx1912.cpp

.. ~ ..

II Listing 1.12: Using the conditional operator

#inciude <iostream> int mainO

{

float num1, num2, num3, largst;

cout « "\nEnter three numbersvn"; cin »num1 »num2» num3;

largst = num1 > num2? num1 : num2; largst = largst > num3 ? largst : nums:

cout « "vnl.arqest number is" « largst « endl; return 0;

1111

._ J

'--

8

m·:

~ (0. js)

• Q)Q)alt: program '=l?~o):~l'dJj identifiers (4) adS type float c8Gr;::;:.~~: 0:>0'5

iJ J L t1 • L L L. L.jt:J..Il:j IL l·

c++ Basics

• largst = num1 > num2 ? num1 : num2 ; ~o? statement mG;; largst = 150.56 > -500 ? 150.56 : -500 = <true> ? 150.56 : -500 = 150.56 c{3

..

assign rooG0:g:,0111

L J

• 8'dyO')S~1'f'GOJ1 largst = largst > num3 ? largst : num3 ; ~o? statement mG;; largst = 150.56 > 2500 ? 150.56 : 2500 = <false> ? 150.56 : 2500 = 2500 c{3 assign rooGo:g:,0111 81G~8a m~olltQ'Y.)g:, Largest number is 2500

LO L J ~J. L. 0 T iJ J

~ display oro§Q'Y.)01ol1

~.".J_ r;x .l~!~.~_ ~~ "
II Li sti ng 1.13: Usi ng the com m a operator ;0.1
H
#include <iostream>
int mainO
{ 'I
float a, b, c,num; ,
a = 255.78; ,
i
b = -100; = ,
c = 18; I
num = (a+ «, b- s. --c+3);
cout « "vnv alue returned is " « num « endl; I
cout « "a = " « a « endl; ,
cout « "b = " « b « endl; il
cout « "c = " « c « endl;
return 0; __ ,
} LV]
< ) i.::
- Comma Operators

011 C ~ c++ program GCYJ'f' expression GCYJ~ comma ( , ) GCYJ~.§:>:Go:~E1010')oSll 2000 var1 = (exprl, expr2, expr3); c{3GQ:Go:~oS;;8@8 expression O')S~~18:~ O')~g:GO')d3O')oSG0::xn:rR:

.. T L -I L \I -~ T L 0 L 0 0 ij

c • ." co 0 1 " . c r;;:c '1 c. ( ) ~ ,

~8'd8;;~:m expression q_O');;<fOC var f. assign orOGO:qp:'f'1:j00IO')OJIl « o, J2 'f'G<9, tlCO'):O?

c++ Basics

9J

E 1013 0 0 ceo C C • ( ) ~ , o c 'T'

X .cpp program 0( run arO?~U)ar9c OJ"oJIlCJY.)<[-> y o, JI!) <[->tjCXY:>:O?a4OCC:GOI C\Y.)

n-, Q 0 ~ ceo C

<[->01011 !3 program O(GO?C\Y.)e:J~~U)ar9c

• ~~~8: program <[->a4~:§l~u? identifiers (4) 'r6? type float ~G§IP[9: ~~ a4cnd> data Gcnd3 a = 255.781 b = -100 ~ c = 18 a3 assign ro8Go:o1cnoSil

o 0 L To LO L

• num = (a++, b+3, --c+3); a?o? statement O?G" a = 255.78+ 1= 256.781 b = -100 1 c = --c = 18-1 = 17 £ --c + 3= 17+ 3= 20 ~d3cnd>Go:cn0111

T· L. L -0 j

3GCJY.) num = 20 Q;o:n:01fRll b cn~8:0?~Gr,,,,8:01:)):1I

• tj 0 l:j TL l:j.J IL

• !31G§P9~ cout « n\nValue returned is n « num « endl; O?Gf Value returned is 20 ~ display ar8§CJY.)01ol1

• a:2f~:o;r a = 256.781 b = 1001 C = 17 ~6?ro~: display ar8§<[->0111 ~ (0. JI!)) 6?§~0111

_Quincy 99

c++ Basics

Initializers

ml~ GroSdS GI:'I8t:<:noo~:m program <:n()la:, variable Gmd3 type declare ro8~:~ 0:>

'"OJT L·)1. L J L T J. -0 L L t1 J IL

initial value GoodS assign ro8G():~()loooSll Q)tQ)S type declaration ~G;)OO data initialization ~

o L L· T· IL L

ro~:C\(8~E>1()loooSll i2 (0. J?) 'f-'G~T§~~ ExlOl1.cpp program a? i2 (0. Je) G;)o?t:E>1G8(f)t§tG~~

_Q C' C' 0 C' • ( ) ~ 0 , '1 '1 0 C' C ,_~. C', r:::' 0 C'

run C\[m~().)atE>1c « o, J9 mG;)GCj~l:UE>1'f-'()11I GlatE>1c ++ 'f.,()ooo:>mO?G;)Gt:laGOJO? Q)')~OO~G;)G'l'

Q)Q)rotrotGro: 03g::m:~ci5cot()loooSll

LL jIOt:1LO

'~::J Exl014.cpp

$ .il! I

II Listing 1.14: Using the initializers

#inelude <iostream> int main()

{

int

long int

num = 10; fae = 1;

for (int i=2; i <= num; i++) fae 1(= i;

eout « ''\nFaetorial of" « num « " is " « fae « endl;

return 0;

- ---'------tr·" :1--;

... _ •... "_, I.:.) 1 .::

_~_.I

uu

c++ Basics

99

c++ function GD6OY.> c++ program mSya?m~Ga:Y)oSsp'P 94GE¥U1~:94G§~ "Y-") subprogram Gmu1011 function mS;;);;)18:0Y.> executable program code Gmd3(\)oSaan:u1

• 0 L IJ 0 L

..s. c++ program mS;;)'=Y.> 94£~::i>: function mS;;)GO'Y.) u1Qu1~oSll ~o10Y.> program 94moS

l J TC. l L • "I 0

:mo8Gu1oS~ qsoSGu1oSG<{Su108a} maine ) function u1011 maine ) function mGtmS[p: lower-

evel function Gmd3 cal dT'rR: ~3 function ccococo code Gmd3 execute (\)b'=Y.>u111 ~3~1~'=Y.>

o L .. tI 0 0 l L J ur J

:c ling function OY.>94C\(b9ban:~: call G;;)T~9a} function m return §tc\y')~o? value mSya?Gro~

-tOOoSG(\)1I maine ) function mGt call G;;)T :l:la?0 lower-level function mSymGt Gt')oSmSya? ta I G;;)T 0'Y.)(\)~:gu1moSlI maine ) function d3GO'Y.) call ~~G;;)T c8~Qu1:J):11 function mS;;)OY.> call

c:. jl L • t1T L· -IlL L

9J

Functions

!nOJ8GOOdS calling function 0000 §)8Ga;n8GQ!0)Q'J~c8GOY.>o1::D:1I new function ooS~ ~8~C.GE>l::Kd

L 0 L J JI2 "T -t- L • IL L.

," 0 0 C'BC' 0 C' C'0C' 0 [g C' '1 0 C' II' f ct' d

!n8m~:OJm £OJm OJO~C:OJQG£ ~())OO(\),):II 81COQC ca Ing un Ion GOOOO co e Ga:>SiC::CX.ctl

L 0 L T L L L Lo-l T L L -l 0 J

~:~d2 C++ programming technique tmOJt§: !n~~:coaS(\)')'f'0lol1

011 function ooS:r'P !nSm0108o?!n~8: (2) :rtm function header ~ statement body

§SoloooSll function header a?co8g~O)S6~E»8 !n~8: (3) y0108Gf'0Y.>a?G06.E>)'f'0111 (0) retu type (j) function name ~ (\» parameter list d?'§S60100oSll return value srr» C++ type ccococo ooS~~~S~8~c8 data type GOOdS point OJ8G£m pointer ooS~OJ~:~S~80

o L LLJ L L 0 L LT· L c:.. LJ L

') C' t ct 0 • t C' " • t 0 C' ~C' 0 '1 C' f ct'

81'i~0?00 s ru ure I array G06o( POIn ,,(OGf'O? POIn er ~l:OJ~:IjO)C\(,E»OIOO(l)1I un Ion

mGOY.> identifier GOOdS £,)~~Go:£~:£!n000001ol1 parameter list tm blank ~S~8~c8 va

tI 0 LTc:. TC ,. IL Il eJ L L

~ 0 0 C' " C''' • bl ,0 II' f cti t

G06!n~p:u:~Gf'C\(,OJ~:E»OIOO(l)1I 8 vana e G06COO( ca Ing un Ion c» argumen ,...,...,/'Y">,...,.......,,,,.,.

co~'f'0ll1 statement body a? program OOSyGE»!o?!nd?8:GE»:E>t01~oSll local variable decl GOO I executable code Goo010801c8~~oSll ml~GroSd3 function ooS~dS call ~G~T ~8 function

o 0" OJT L- L L

parameter type G06~ return value !n~l:!nO)'):G06tm :),),)G0601~ compiler a? !nE»8!n~Go:E»0

~3c8 function declaration dS prototype c8G~T 01000511 G0)')8:1R I OJoSmm function ooS

L L L· t:1 OIL-

define ,,(8lY: maine ) function mGf' call G~T§~E>tGa;n811 ~ (J. 0) c» Ex201.cpp program

GO?(\)')§~oll1

J.O Create a Simple Function

• maine ) function OO'f' !nE»8~:"(80Y.>m STEP I: Inside the maine ) ~o?O)')G~8:a? display ,,(80Y.>01011 81tm ~ (J. j) c» oco~O)')G~8:Golll

E 201 0 0 C' C' 0 C' C' • ( ) ~ , 0 C' 'T'

JII X .cpp program 0( run "(m~(l)~E»c "6f'~llOY.>'P Cf J. J 'Pt:1CO'J:O?!nO(C:GOI ~

", " 0 ~ C' C' _9 C'

'P0101I 8 program O(GO?(\)')U~~(l)crrE»C

• C' • () f cti ,OC'OC' f C', f ct' t ty

O)O)~C:'P main un Ion 9_.cooCfc:'P unc f'')~~'f. un ionpro 0 pe

[p0100oSll return type m void §SlY: parameter list 'P variable :)')')'i~§o

prototype declaration Gf'')aS~:'P semicolon ( ; ) ~8d3Go:E»01~oSll

Functions

_Jt:XLUl.Cpp_

/ / Listing 2.1: Create a simple function

#include -etostraam»

void func(); / / decl are the functi on prototype

int main() {

cout « ''\nSTEP I: Inside the main() functrornn";

=

/ / call to the functi on

func( );

cout « "\nSTEP III: Back in the mainO function again\n\n";

return 0;

void func(). {

/ / function body

cout « n\nSTEP II: Now inside the func() functionvn"; '--

~ I

Il1I -.' _ .' .:', .• ,. •• .;;2.;. _I

9?

8 ffi ...

Functions

Functions



(

func( ); mG'l' function call c{}05a}rno;?05 void func() ooo?08C\Y)u1[gn calling function If.) argument (x)~Gu:g(X)'):u1:n:n gGOY.> func( ) function 00d5 ci305gdS

J u. IL· LLLI

Gbp05~:[g: STEP II: Now inside the func( ) function ~a}ooG[§:>8:o? display

C\(8§'f'u1n 81c..m ~ (Jo j) m tci3()')ooG[§:>8:Guln function body 00'f'C\(80bpo?~ ~:q8 maine ) function O?§~C\Y)'f'u111

• rnaooSa1 maine ) function oom func( ); G::rn05lf.)gci) code statement 65a)051&

L J JI • L ~

G§~8:u1n3~guSll 3GOJ1 STEP III: Back in the maine ) function ~a}ooG§:>8:~

display C\(8§e:'f'u111 81c..m ~ (Jo J) m ooci3()')ooG[§:>8:Guln 81~q8 Ex201.cpp program c..m [g:~:u1[g1l

• ooSmuSc3 func( ) function ooSaro:d5 maine ) function rnGuT If.)~'GQ:(X)'):~

L· L L L J ~ 'T -l-

function prototype declaration gu1o~ program run ~qu1oouSll ~ (Jo ?) mlC:)':l::i:>o.

/I Listing 2.1A: Create a simple function

#include <iostream> void func()

{

/ / functi on body

cout « "\nSTEP II: Now inside the func() functlonvn":

int main() {

cout « "\nSTEP I: Inside the main() functlonvn", /I call to the functi on

func( );

cout « "\nSTEP III: Back in the main() function again\n\n";

return 0;

[Vi

[>] ::

IiII

Pri nti ng aline of Asterisks

8mSa1m8§'{>m starline( ) ~o? function (void) mS~o? call Ga1]: program output asterisk(*) G06GoT (\)'JG~8C\(8~8:'{>o111 ~ (Jo 9) '{>Gb[:CXYJ:o? Ex202.cpp program a: code =6d2GC\l(\)')§~o111

II Listing 2.2: This program demonstrates a simple function II that prints a line of 40 asterisks.

# include <iostream>

void starline();

int main()

{

cout « "Data Type Range" « endl;

starline();

cout « "char -1 28 to 1 27" « endl

. « "lnt -32,768 to 32,767" « endl

«"double -2,147,483,648 to 2,147,483,647" « endl; starline( );

return 0;

void starline() {

for (int i=O; i<=40; i++) cout« " ..... "; cout « endl;

lUI

"

. _! [II.::

_<_1

9@

Functions

II Quincy 99

• Q)Q)~8: maine) function ~roGuT r.p starline cj>')~~~ function prototype cnS G~r,::,..u1cnoSn return type m void u1n parameter list 00 :J)')~~gul)'):n

~tlJ J J)I IL

Data Type <2 Tabs> Range ~o? heading o?G9=~8:@: starline( ) function

call G~T u1cnoSn

• starline( ) function cOoo for loop d5ro::D:~'~: ~oSu8ro~ (40) d5 print co

J L L L:11£:1 r:.:1 0 • L L L

u1cnoSn counter i o? for loop cOr.p0 data type t~@:G§~CO'):u1cnoSn asteris

(40) yo? print UC6@:q8 main( ) d2§fO)')u1@n roycnS~1 char <2 Tabs> -1 to 127 d2~05@: G~o05cnSG~8:d2o;r:u1cnoSn endl G:p05r.p semicolon(;) ~GSf

'i' o c C C t 0 c~ 0 ~ co, "I'

roGUI mroorc:aJmGq:qc cou or aJmt:1:ro::l?:t:1l~O)CI(O?::DG:J)')ulun

<2 Tabs> -32,768 to 32,767 d5aJ05~05oou1n 3roc88:0 cnc8O)<Y"'>r'I"""A.

L ~I J L

print ro6::D'):oou1u

L 0 J

• Gc8O)ro~G starline( ) function d5 call G~w,:GO)') print ro6~8:~oSa3Q8 0

L t:1 L"II' L:1. L L L -L

r.p asterisk (40) Y(JY.) ro6GuT 0)')r.pu10n ~ (Jo J) o?[§~u1n

J. J Pass the Variables by Value

on calling program cnS~mG£ function cnS~d5 call G~T d305oJro~100 argument cnS~1 c?::

L T L L L 0 J IJL· L

called function cOm variable GcncOd5 pass ro6Gu:u1cnoSn data pass ro6sd;:Gcnro~t'):~:g()1

o L L L TC 0 u e.:1 JI

Functions

:"Xl5n 8d8OOf~: (2) yoo Passing by value ~ Passing by reference f~:GCYJ§So1oooSn ~ (J. G) ..I)GQ:()),,):oo Ex203.cpp program <n constant value GOO pass co6s~:d5 oo8C':())"):o1oooSn

-r • J 0 L Tc.:, L t1

~Ex203.cpp

·l.-.I1.oJI3

)- ...

jll Ex203.cpp program d? run ~a5~oS~9.8 C16~oJllOY)<f' ~ (J. ?) <f'B()),,):o?8dq8:GoT C\Y) • <f'o1on ~ program o?GC\'C\Y.)§~~oS~9.8

II Listing 2.3: Calculate the area of a triangle

#include -ciostream» float caIArea(float, float);

int mainO {

float area = calArea(l 0,20); cout «"\nBase ="« 1 0; cout « "\nHeight = " « 20;

cout « "\nArea of the triangle = " « area « endl; . return 0;

float calArea(float b, float h) {

float area = O.S ..... b ..... h; return area;

< I

• program 1!)1!)~8: main() function q,8dGoT <f' calArea f')~~~ prototype o?G§& o1oooSn return type 00 float §S~: parameter list <f' float data(2) yo? pass co6~8:<no1n

L L J

• maine ) function ro<n 8dQ8;;o:co60Y)oo identifier area d5 float 0'3 declare

J -LLL L L·

co6~: calArea( ) function d5 call G~T o1oo oS II pass co6Go:~oS argument GOOOO

L r:1 L L· 0

constant value Gooo1on 10 00 r;::goooS~~ base r,;:S~: 20 00 height a301Sn

o e,j L-Lo (jtj L t.e

Functions

Functions

JJ

• pass C\)6Q)0J"):00 constant argument (2) ~cf:, function calArea( ) 0000 b .l

L ILO • L L 10

h ;;800 variable GO')ooG') ad~:~: copy (x)~G0:0305010')d)1I 3GO')') b = 10 ~

L· 0 J l:...!.. L ..,.

h = 20 §S~:01~1I 3G'l'E>P'P ::D~(X)'):q'Pm prototype declaration ~ functi

header o?OY.lo;r~q01~d)1I ady~ data pass o:r60')')~ passing by value ~G~ 01 0') d) II

• adYa?q8 function body OOGE>P05G'l'01~1I local variable §So? area q. data ~ area ~adq8G§[P~: §3oc;:~O)')~ (base * height)/2 a?o?«G::D'l';..u;'!PlT)OJc 010')d)1I float area = 0.5 * b * h; ~oo statement 0Y.l ~3adO')05 GQ:(X)'):0')')0

L • 0 -L

area ~o;?05~:~:q8 return area; mG'l' function return value ad§S area

return o:r6G0:0103~~d)1I 3GOJ? area q. data type ~ return value data type ~0Y.lC\)~: O')QG')G0111

L· C. IL -lJ 0

• maine ) function ~§~GE>P05C\)')o?ad~1'P area= caIArea(10,20)= return val ~ assign o:r6GO:'P§S010')d)1I main( ) function 0000 local variable: area §3oc;:~O)')O')~~:m GE>P05G'l'01~1I G'l'')05~:adG'l'~ cout « expression ~ado.):I()IIIU: base I height ~ area o?q.adG§ ~O;?~'-lIIlO')')'P display o:r6G0:~05~§S010')d)1I « (J. r;?) ~§~0111

_Quincv 99

JII Ex204.cpp 0Y.la?q8 Ex203.cpp ~ ad::DS§8Gq:(X)'):0')')0111 variable Go;?~ pass o:r6'l'~ ~ program ~§8Gq:(X)'):010')oSli « (J. G») ~§~0111 3 program ~GotC\)')§~~oSa?q8

!3dGoT <;6: statement ())'J base I height I area cBciS global variable Goo03 declare C\)8~:

L LeL OLO Llj

prototype (3) ~CiS define C\)8Go:an:0100o5,, maine ) cO~oro'=la:): getData( ) function

L L L J L

ciS call G~T 010005" getData( ) function cO~ base ~ height !3d00d) 00f.8:GoociSgd)rod;

L J T· 0 T L 0 L tl U.

II Listing 2.4: Passing variables by value #include <iostream>

float base, hei ght, area; void getData();

void caIArea();

void printArea();

int maine ) {

getData( ); calArea( );

p ri ntAre a( );

return 0;

void getData() {

cout « "\nEnter base and helqhtvn"; cin » base » height;

void caIArea() {

area = O.5"rbase1rheight;

void printArea() {

cout « n\nArea of the triangle is " « area« endl;

Functions

~:qt maine ) o?§~GE>po5C\Y)~: calArea( ) function o? call G~T 'Po111 calArea( ) function

" C " "l C ~. 0 o. c" C "l C b " h . ht C 0

o)GE>pmc\y)0?04~19qc e;jOgqo.nO( '(G::Di"~:<f. O6mo,tol(,l(l)1I ase <f. elg O')i"<f:G06m

:BGf'I9~ function OO'PG§!Pq)E>p(,ld2Go:>?ol~:1I area O605l9:qt maine ) o?§~GE>po5C\Y)B: printArea( ) d3 call a::>o5G~T 010')0511 printArea() function m area O')~a:d3 print rot)

L T L L L

JII Ex204.cpp program o? run d205(,lo5a?qt qs~'-llIIO')')'P ~ (J. @) 'P§(X)'):o?04o?t:GoT C\Y.) 'Pol II 04G§m Ex203.cpp program ~04o;to;tolUIl

rIIQuincy99

Creating a Self-defined Square Root Function

01

~-,JoS program <JY)~Qt sqroot( ) ~a) 10 d3 self-defined function O')S~d3

_ • L -L L • L L L

~" ceo ceo "l f f C C • II' f t'

.-,c~Q C§q)O)om£:Qc:ml':nG0:g)olll unc Ion 04roorooom ca mg unc Ion mG£

L P J T -L L jl- J L L L T

consta

o?C\)e?-

0')9::01- program

I d f tion cs C 0 c~ "G> C C c~ " §

CG e unc Ion 0) pass coocoeox» : 04Gg)O')mO')')~lmO')')roo :0')')£ 04G

L L JO ij L ,.

.;:~olO')o5lI 04r,:~(,l') return value (,l(l)U main( ) d3r,:~C\Y)0')')0111 3::DG~

• t1T J IL Lt1T

cop program o?Gq:(X)'):O')')§SolO')o5lI ~ (J. 00) 'PGq:(X)'):o? Ex205.cpp

GC\lC\Y)6~0111

Functions

II Listing 2.5: This program displays the square root of II a number passed from a program to the function.

........ 4' ... ~

~~x$.cpp &4 0." e; i HI •

# include <iostream>

void sqroot (float ,float L

int main() {

sqroot (625,10000);

return 0;

void sqroot (float xn, float xr) {

,for (int i=l; i<=50; ++i) xr = (xr+xn/xr)/2;

cout « "Root of" « xn « " is " « xr« endl;

<J

1111

._-_ -- -~-

.J

• program 4)4)~t: main() function ~ooGoT "P sqroot 1o~~~ prototype o?G§1P olrooS" return type en void q;lR: parameter list g) float data(2) deB pass

tlt1 J LL

rob~t:g)ol" G()')')t:1R I main( ) function g) sqroot (625, 10000 ) d3 call Gdw,:

L L J t1 J L:I" lj

625 ~ 10000 d? sqroot( ) function cD pass "(bd2~olrooS" passing by value

c.... '1

1'~:OGO!"

• sqroot( ) function header "p xn = 625 ~ xr = 1 0000 ~~: constant GOJ

Pass robotO)'):ollR" function body cDg) xn ~ square root ro~a:d3lY)olrooSll

L 0 tt J -Lo T L L JI-

ceo C .... t co '1 t .... C (/

xr en OJji'GOY.>O? assume "(OO? roo roi'<e:OIiJ roo ~O?i'~:en xr = xr+xn

xr)/2 ~o? statement d?(X)bdlroSro§~OJ~?t:OY.>olol1 for loop o?oo0G (50) o05~:~:9.tooG§9.o1B" output result o? ~ (J. 00) "PG~T§(X)'):olrooS"

Functions

"" 3 program "p ~t<-1lll()')')m~G§o? §~:§~::;>J8: ~tGcrn8:;>t~t:CY605:;>J05C\)')()')')o? §8~8(Y)oS

a?E>'t8 ~ (Jo o j) "P§aY.):o?~o?8:§8Gq:I§: run 6~()111

Functions

III Quincy 99

.'_j EX:.-'U!"lA·CPP

II Listing 2.5A: This program displays the square root of II a number passed from a program to the function.

# include -clostream» void sqroot (float, float);

int main() {

sqroot (625,10000); return 0;

void sqroot (float xn, float xr) , {

for (int i=l; i<=50; i++) {

xr = (xr+xn/xr)/2; if « % 5 == 0)

cout « "Root of" « xn « " is " « xr « endl;

.'-J

<1.

1111

lit Quincy 99

:lll ~ program r,p root ~~86?oC1D~:~ assumed value 9o? keyboard mG~ OO~8rot§G0: 28'=luS~Qt ~ program m8Gont:C\Y){,l')01n xn ~ xr dSQ oo~a:Good5 variable GOOOOG.5~ pass o:,[)

~ l -L L J T· La -I.- T L 0 LOT To L

,"0:§~~G8'n611 ~ (J. 09) r,pG<f(l)'):6? program code GC1Jo? 0')u)a?§8G<f(l)'):ro~0??a? ~d3§1

6t§GG:lQJt01oou)1I

• sqroot( ) function ~ return type o? float ~.§8Gq:(l)'):01oouSll maine ) ror,p

.... co 0 k b d 2._C' C o c C r,'",C ., C

xn i xr oo~<f:G"3CY? ey oar mG~ 't,mro2tG<J:,?CG8'nCGljJC:Gq:CO'J:0100()')1I

OOG§o? cout < < ~ sqroot(xn xr) 9o?~Gq:~: print cxr05~t:(xy'):01oouSll

• t( ) f tion cc t"" C C C _o.... ., C CrR C sqroo unc Ion ror,pGOO? roo ~0?~~:~m~mcy?0Gq:(xy'):Uloo()')1I C1Jmlj:qc

OOG§o? xr = sqroot(xn, xr) OOG~~ return ~8G0:r,p0111

Gil ~ program d5 run a3cb'=luS~Qt u (J. 0""') {,l')~(xy'):oJoodSt: oocb:::m:a3Q01oouSll

L L L -L L ..J J t1 • L ~o 0 t_e-L

Functions

Functions

1'l::::J 1-\1-..11 ~.cpp

.....

II Listing 2.5B: This program displays the square root of II a number passed from a program to the function.

# include -clostreamcfloat -sqroot (float, float);

int main() {

float xn, xr;

cout « "Enter a positive real numbervn": cin» xn;

cout « "Assume its rootvn": cin » xr;

cout « "Root of" « xn « " is " « sqroot(xn,xr) « endl; return 0;

float sqroot(float xn, float xr) {

for (int i=l; i<=50; i++) xr = (xr+xn/xr)/2; return xr;

lIll

J

II Quincy 99

Pass Variables by Reference

c++ program ooS:;>oo calling function rom argument OOS~I d5 called function ~d5

L J \,Il. L L

C, ') t t t CQ c o c 0 c-, II" t!pc ,

pass CDOOOGl):;>loo argumen - o-argumen G(])')OCDO:;>C:OY.>blll:bl(J')OOO ca rng argumen ooG C:CD

L 0 J L L iJ[ L J

o dd 0 co cBc C t dd C cOp " b

O')')Goom a ress 00 oom~m C~:GG'i)')C argumen- o-a ress pass CDOS~:m assrng y

o l J L L 0 l TC L

Reference ~G:;>T 01000511 Ex203.cpp program o? 3f~:~G!p8:Gbl:6~blGG'i)')811 ~ (J. oG) '_f)Gq:

:m:o} Ex206.cpp program o?GC\'C\Y)6~0111

~ ;ao:a .,~._J EXLUO.Cpp

I [ ~ Ii .1 GIJlliIU

II Listing 2.6: Passing variables by reference

#include -ciostream»

void .caIArea(float, float, float& );

void pri ntAre a(flo at);

int main() {

float base, height, area;

cout « "\nEnter base and helqhtvn"; cin » base » height;

caIArea(base, height, area);

p ri ntAre a( are a);

return 0;

void calArea(float b, float h, float &x) {

x = O.5"'b"'h;

void pri ntArea(float a) {

cout « ''\nArea of the triangle is " « a« endl;

) '"

Functions

OOGr;:;:r,::,...£~:s gmGOY.)olO?:1I called function m return type Gm6S void GmCiI~:

J t:1tJ..ITC T. IL • IL 0 L 0 \.Ie.:.

• 00 GoT <i>: statement (2) Ci<.m function prototype declaration Gm0111 Ex203.cpp

L L 0

C' 'I C' Q _C 0 C' 0 , r,;: 0 f cti t I '

a.r0CXY.): OlmOJIl 8GOJ? o;?m"?~mo('9.O?ooG[jGo;?O( un Ion re urn va ue OOGi'~

return ~a.r80y')GOJ?G::DCi.r01~1I calArea( ) function romGi'')rhex2: argument d? ::Dd3~,r;:;:~)0111 3eI!Y)2!2: variable ~(J)05010?:1I calling function m argument d3

l:f1t:jC!, e 1"'11 L IL L

C' ~C' 0 C' C' 0 C' ,Q dd ' OC', • bl ' C'O , C'

mI!)YYt1corm~OJCX(9.c 008 a ress t.CX(cO? varia e q,mi'<f=<.m program q,O?OJG~

E>p'{'0~~ §8~:::D'):§Sqp:01~1I

• . f cti O~C' C' , 'I C'O 0 C' 0 [l'!.r,;:C' 0 main un Ion O(t1i'GE>pmC\Y.)O?ooCiI'{' area mi'<£:O( o;?i'tlIllOY.)m::DGi't1[jI!)OY.)~

assign or8Go:'{'§SolmuSll Gi'')rhcx2:00Gi'~ printArea( ) function o? call GCiT@:

function cDoo area m~8:dS print c.u8Go:0001011

J TL L L J

Lowercase to Uppercase Character Conversion Program

~ (J. 0'2) '{'§CXY.):o} Ex207.cpp program o? GcvC\Y.)§~~uS~~§9.8 function o? call GCiT mm~:m data <1(~:OY.)o? GO;?9.01muSll data m lowercase letter 'e' '0111 lower_to_upper a2o? function cD,,? passing by reference i'~:~ uppercase ~ address ,{,letter 'E' §SG~8§8GO: ~rh01muSll G~8:o}i'~:mGOJ? c2 = (c1 >='a' && c1 <= 'z') ? ('A'+c1-'a') : c1; statement d?

• h. 'I C' C' 0 1 ", C' 0 C', 'I (1 "&& 1 ")

OO::l(:tjloy')OIIl o;sJi'GOY.)~m C = e OOGi't. pass oroGo:a.rmO?OOCiI'{' C >= a c <= z

expression ~ test or8~rho}ooCi199.8 TRUE §So}ooo;?a5 c2 o? 'A' + c1 - 'a' ~ assign or6 Go:01c8~guSll char 'A' ~ ASCII hex value m 41 0111 c1 = 'e' oomo5m 65 0111 'a' oomo5m 61

• -P 0 0

0111 3GOJ? c2 = 'A' + c1 - 'a' = 41 + 65 - 61 = 45 o?9.01muSll ASCII hex value = 45 ex» 'E'

§So}ooo;?a5 character variable (upper) co: 'E' §S~:ol~11 mSmuS~ c1 = 'E' ~CD~GO:~uS~E>f c2 = (c1 >='a' && c1 <= 'z') ? ('A'+c1-'a') : c1; statement 00 c2 = c1 c8 assign c.u8Go:00010

J L· L J

Functions

Go

~Ex207.cpp

-. at P AC .a; .up) J ~FI

~-- 1--'101131

II Listing 2.7: This program reads a lowercase character, II converts it to uppercase and then writes out

1/ the uppercase equivalent.

# include <iostream>

void lower .to.upper (char ci, char& (2) {

c2 = (cl >='a' && c1 <= 'z') ? CA'+cl-'a') : c l ;

int main() {

char lower, upper;

cout « "Enter a lowercase charactervn": cln » lower;

I ower _to_upper(l ower, upper);

cout « "vn'Ihe uppercase equivalent is " « upper « endl; return 0;

... " '_ .... " r.: .. _ ....

un

BlQuincy99

Go

Functions

Swap Variables by Reference

011 ~ (J. O@) 'f'B(XY):o} Ex208.cpp program (J)')~~8 passing by reference 'f~:a?~,,~"".'''.r.

variable a ~ b ~~ value GOJa?G;E>p~8:cUGo:o1oooS I GC\?C\Y.)§~o111

II Listing 2.8: This program swap

II two arguments passed by reference.

# include -elostream»

void swap(int&, int&);

int mainO {

int a, b;

cout « "Enter a and bvn"; cin» a» b;

cout « "\nBEFORE: a = " « a« "\t\tb = " « b;

swap(a,b);

cout «"\n\nAFTER: a = " « a « "\t\tb = " « b « endl; return 0;

void swap(int & x, int &y) {

II swap x and y int temp = x;

x =y;

y = temp;

-.---------- _-- .

<

[}] .:

UII

- .. ~~.-- ... -- -----" .... ~- ....... -----.- ... _- _. ~.-

_._",:_ .:... .. , w _:_

Ex208.cpp program a? ~ (J. JO) 'f' run B(XY):o1oooSu

11 Quincy 99

Defa-..lt Function Arguments

function prototype Cf)S~cB declare C\)80')00~100 parameter list 00 uloto') argument

LL L· J J.

axn ~ldJo')OOGQOOCf)dJcB default value GCf)OO~Sc(y):Gu:03QulCf)oSll function call G~T o3dJo3

~ • "t 0 L 0 t:j L· "I L L·

'<m:o') argument GCf)cBGCf) Qt compiler mG£ default value GCf)cBoow:OJ~GU:'=l')ulll 0

• 0 L o- "t T 0 L U J L

o JO) ooG(D~C(Y):o') program oo~Qt function prototype moo argument GCf)OOCf)dJ default

J III tf. J L "t 0 0

o d I c[9 0 § 0 0 c§ '1 C

e eax» ec are coo : 000): lO)'):um Cf)C coxoicocoa

OL L LOLL

g 0 r.:;:: C C ~Q C G program or GO?C\)')e:1~'=lO)Cl(E>tC



G)G)~lt: function prototype volume( ) cB declare C\)80')00~100 argument GCf)

iJ L L· J 0

OOCf)dJ default value GCf)cB 2 I 3 I 4 03 0003:03: o)~'=l~Gu:ulCf)oSll UOJ'=l:;O: call

o 0 L L· J L

G~T 0') volume( ) function 00 argument ro:o'=lulo')ooCf)dJ default value (3) ~

• J L· 0 L

ro:d3 ooo.):r,:,(R: volume cB l*w*h=2*3*4=24 03 Cf)dJGu:ulo3~'=loSll

LL Ltfl.rj L LeO.

• GdSO)oo~~ call G~T 0')00~100 parameter list 00 argument Cf)Sro:o ulo')ooCf)dJ

L ~ • J J L· 0

UOJ'=l:;O: default value cB new argument .5 oow:GC''''t:Gu:ooulll 3GCf)') volume

L L T. C:::1J J •

= 5*3*4= 60 §S'_Pu111 3,,~:ooo?t:mJ~o? function Go;?o? call G~Tf9:E>tt volume (JY) 5*7*4 = 140 ~ 5*7*9 = 315 ~ §Sulo3~'=loSll ~ (Jo JJ ) '_P EX209.cpp o? run §C(Y):ulCf)oS I GO?C\)')§~ulll

Functions

Functions

1/ Listing 2.9: Using functions with default arguments

#i ncl ude <i ostream >

void vol um e(float=2, float=3, float=4);

int mainO {

volume( );

II all three arguments default

volume(5);

II provide the first argument

/I provi de the f rst and second argum ents volume(5,7);

volume(5,7,9); II provide all three arguments return 0;

void vol um e(float I, float w, float h) {

float vol = I"'w"'h;

cout « ''\nVolume = II «vol « endl;

(

IDQuincy99

Inline Functions

C C 0 f t" cOd fi C 0 C '0 C 0 C "I ,Q f ct"

O')I£GO')')m unc Ion m0~0') e me (\)0(\)0')0')')£ Oc:)£aJQC cornpi er 0')10£ 800 un Ion

OlT L· L L L L To L J T L -L T

t C 0 C" t cti . COt C Il( 0 C 0 C '"IIJ\

: execu e Cl:(0<e80060') ms ru Ion 800(0)0yO( crea e Cl:(OGo:lj: memory r.p :))C:):ClY.l:CI:(O')Ollj"

• function d2 call G~T d2t: calling function O')G<j> called function ~~d2 y~GO')f->~:B= 06d)0')')~d)0')') ~6r.p0111 [§:9.t calling function a?§~(\)')C:)oSGolll function a? (10) ~~ call G~T 9.t (10) §~d3d3

'"I C C '"I C h C '"I' II rr, f ctl 0 C C C 0 C t" t" C

.. ;;Jl()')o('l!G~IO')lj<j> ~:G<j>r.pOIOIl ca G~I O? un Ion 0') :))oco)G<j>O)O)ar9.c execu Ion irne coer:

:ra t" 0 '"I 0 C C f t" C 0 C CIl( II rr, ~ C C C 0 C " I"

verse irne O')<;_JG<j>ol(\)C;lc:)o)lI unc Ion O')(\)~::))ocO)lj: ca G~I 0?8Oe:1C:)0')<j>~:C:)O)ar9.c In me

'unction a?G§[p~: call G~T 0')')()'Y.)~§~r.p0111 inline function mSYa? create Cl:(6~t9.t keyword 1line 03 function declaration 101:'1 a): C:)')CO "'GO: Q01C:) oS II inline function c8G~~ClY.l:Qt compiler

L Jla L J ei -L L. utJ..I -L

"'") mO')~ function ~ create Cl:(6c:)G<J:GOJ?O function call G~T o?8O~1~'i inline function r.pG9.: :rn:m code statement Gmo3 calling function C:)') d3d)8d)0'):coaSGo:ll(: 8O(\)6r;;:SG8'"nt(\)6St:

• OL J LLI IL Ci. I,j Llj LL

lmoSll 3100')') inline function C:)') code statement mS~&S~G(\)')d)O 010')')JI:c:) 80 aJt Gh C:)')G 01 II

• J LJL iJLJ L:1J 0

OQ OC § C C "I" f cti 0 C f t" 0 II rr 0 'I'

xoqrarn coecoce :-DQC In me un Ion Gm()'Y.) OC:)£ unc Ion GmO') ca G~I :))(\)01010(\)11

L L C!. -L 0 L J T 0 L L

joG Local and Global Variables

local variables ~O')') maine ) function ~ mS§:>: function G06q_ body cDr.p declare Cl:(6 :::n:m variable name 100)01011 :))d3()'Y.) 88GQ'")d)8G£m function O)S~~lt:£0;;8t010)oSll function

a 0 IL L· "T JI T 0 L iJ To L

C, labl C C f ctl , iable s C C C

"'")vycoO') varra e 0)0Y()'Y.) G<j>')O') un Ion ax» varra e 'l!<j>,)c:)~~c:~G<j>GO')')c program r.p

:nG&')t800)d)C:)80ln:1I :))d3Gm~ scope ()'Y.) 88GQ'")d)8G£m function £0;;8tO')')o3:11 G£')d)O)S~O')

J. J JilL IL L· 0 -I,- -L- JI T • T· L L T L

\Indion header GmooO') parameter list Go)o3 ~3 function 8Omd) local variable GmcS:))chC:)ch

o 0 L 0 0 L· J

3Q01moSil 3 variable Gmo3 function body ooC:)')co61l(: declare (\)60Q'")C:)cSo1::n:1I global variable

~ "I 0 L J t1 L "T L IL

';"6a? maine ) function 8O§t~d) program q_d36a?:<j>'):r.p declare Cl:(69.01C:)oSll variable scope

~GOJ? program mSyo?:~~t(10)oSll G()')')t:~ I ~ (Jo J~) r.pG<.OT§ClY.l:o? EX2010.cpp program -? GC\?(\)')§ ~ 9.10 8O')tll

Functions



Ex2010.cpp

-.

II Li sti ng 2.10: Thi s program creates a functi on power( ) II to com pute the val ue of integer rai sed to the yth power.

#include <iostream> #include «cmath»

long int power(int, int);

int main( ) {

long int x.v.tsmp:

cout « "Enter x and y\n"; cin » x »y;

cout.preci si on(l 0);

tem p = power(x,y); II functi on call cout « x « " to the power of "

« y« " = " « temp;

cout « endl « "\nUsing math function pow() : " « pow(x,y) « endl;

cout « endl;

return 0;

long int power(int a, int b) II functi on header {

long int temp = 1; for t b > 0; b--) temp l'r= a;

return tem p;

< J =-::_ --_. - -

[>l ..

• temp ~o? variable name O')SyO)') main function ~GE>P I power( )

ooGQJ (2) &,:ro:oo o1G~o10')oSn G1GogoS::>.:>d!>~,8:0)') :r.r:>gg£801::n:n ::>.:>cP;GQJ,§

J "T ijL L J TaiL L· ij J L IL IL I,!I -1-

function O')Sy~8:~~u~8010')oSn main( ) function ro~ local variable (3

long int ~G§lPoIO')oSn 3ro~ temp ~o? variable C\)~:oIO'Y)m~''''ri~''

Functions

• x ~ y ~C1Jd) data GC1Jo7ro~Go:l9:q8 power( ) function 07 call GaT o10?oSil calling argument GC1Jm x ~ y §So10?oSll power( ) function ro G~d)C\Y)0~a1 X ~ Y cf5~ O?~a:GO?d3 function header 00 local variable GO?~So) a ~ b In~ro:

To L.-I.o T L 0 L ol.'j • To J

r,,,,C C 'I C

Gtj Jc:ro~GO:O IO?WII

• power( ) function body rom temp ox: main( ) function rom temp ~p~~aJ8:

O?GO~oS ~~~:Dd)088ol:n:1I function roInO?d)ald)fR:cS temp d3 return robGo:

IL • J L IL JO I.ItlLG L L

C1Y)lfY) power( ) function ~ O?~a:d3 return robGo:C1Y)~~0?0?o1011 main( ) d3

-L.TLL L T.ILIL L

B~G~d)o}~a1 local variable §So} temp roo? power( ) function ~ value o?

~1?~ temp ~ power(x,y ) ~ tempG!p8:ro~Go:o10?oSll

• C • ~ (2) o o c cr,: 'I C C C C 0

G<j>')m01:(:'f> ~Gr:J 1?or*c:U?2tjO)')W'O?WII oro~0?0ym OJlfGC1Y)O?, program

Gq:I9: C1Jd)~q0~G§o111 G<j>')d)~G§mGO?? math library function §S0 pow( )

function d3~:D:r,:,fR: 0?d)cSQC1Y)o111 G1GC\Y)d)08Q8 local variable GO?~ ~801oSd3

L lt1ltf 0 LO-l l-L 0-"" 0 L

<j>'):ro~~:I9~ro8010?oSll ~ (J. J9) '{> Ex2010.cpp 07 run BO)'):o10?oSll

Ci1Quincy99

• Ex2010.cpp 07G<j>')d)O?S~l:Gq:§~o1~oSll ~ (J. J~) 'f>BO)'):0 Ex2010A.cpp proqram o» global variable 07 ~~:BlI9:B8Gq:0)'):o10?oSll Ex2010A.cpp cooocoe

, 0 C C • C C C h,., 'I C t 0

program <f.o;f:DC\(rocqGO~O;> Gq:«Gq:<j>~: ~<j>~:cwOJ'='~J:~Wlo?WII emp or

global variable ~G<j>~G6§:>O)'):o}~C1Jcf., main( ) rom temp ~ power( ) rom

to C C • bl ~ C 'lrR f t· b d" C co" emp 0?,lfY) 0?0yO?~:G:D') vana e t'j0G<j>Oltjll unc Ion 0 y ro,{>C1JmaJm~qO?

Functions

Functions

temp value d? return C\(8Q)sp(J~o~ main( ) d?§~Gsp05~:G9d')8C\(8Go:o1c{3~ (JuSll 81d?§t2§8:9d'):§~ global variable GOJOY) function GOJ§':>: rY\o,f'nr,Y'oI, data transfer C\)8Go:~8oJ ooQ)~:~oJ::nG:J'Y.)Go111 Q)')(Kh::nd5uSd58 ~ program (2

L L· 0 J • 0 IL L L

o 0 C C r.:;: C C "\ C _Q. c 0 C ~ 0 '- "I

yO( *c:or2GO;>C\Y.)ue.:GQ)~CO'0)Q)1I program 0( run (JQ)d:(b)c oco(JOOGtj"lll:0b),?ol

• •

-- - .Mao .••••• tJrwii



II Listing 2.1 OA: This program demonstrates /I the use of global variables.

# include <iostream> void power (int, int);

long int temp;

/I define global variable

int main() {

long int x, y;

cout « "Enter x and y\n"; cin» x» y;

cout.preci si on(l 0);

power (x,y);

cout« x«" to the power of"« y«" =" «temp « endl;

return 0;

void power (int a, int b) {

temp =1;

for t b > 0; b--)

temp "'= a;

. 1111

.. _-_ .. _-,.

.<l .. -

7

Overloaded Functions

C++ program mSag) function atl~I'):~:dS function name mSamd;:Go:~: create CD6

L J i,J- L..j L L c:. t1 L

00100 oS II ~GldS function overloading 03GaT olmoS II function name mGo~oS parameter list

.1- L L· IL •

':')~mGa:rx]):Golll argument type I argument number GmCDd;:mC'~:g)olll 20g) C library g)

-~ Il • IL • 0 c.:. ot:1.J J J

'of absolute value ~o? function ~:~l:G(\)')05~olmoSll integer atlOJ05~q8 abs( ) I long

eger atlOJ05~q8 labs( ) I floating-point value atlOJ05~q8 fabs( ) ~~:~cm:olmoSll 32f='

c C' 0 C' '1 C' e C', 0 C f t· I di C' •

:JQO')')~am:J):(\)'): I atlg):~n:1S>COlm()')1I Gatlamatlam ++ g) unc Ion over oa Ing £:"1): atl:::D:

"I IL J iJ - L L J T c:. L

~:G§~8:~8olmoSll function overloading d2 function polymorphism <i?CD~:GaT olmoS II poly

~ ~ - h f '1 '1 r;:;::.... C' 0 •• 0 0 0 'f tl C' 0 I hl

~m many I morp m orm 0111 GIGe.:lJ<:~ «~atl"lJl:"lJl:~O? unc Ion m~yO( po ymorp IC

..

ti 0 -r- '§C' '1 C'

.nc Ion CDGal 0')')0 ~Olm()')11

LO

• program ~~~8:'f' PI = 3.141593 ~ radius I height I volume ~d2 global float variable Gm03G~r;::,._olmoSll caIVol() dS overloaded function GmCD6Go:cm:ol

o L· t:1tl"' L 0 L

moSll main( ) function 0008(\)')(\)')aI8: radius ~ height dSatlm05 data GoodS

iJ T. L· 0 0 L

keyboard mG~~05CX)~q'f'0ll1 ~:GO'J1q8 oCX)~ caIVol(radius) d2 call Ga~: void

calVol(float r) function oo'f' volume = 4*PI*r*r*r/3 ~o? formula atl~:§l~: sphere volume dSm05().)olmoSll volume dS global CD6cm:0')')8 return CD6Go:

LOlL L L L· L

o '1 . ( ) I C' 0 0 0 0 0 "'l~

~Q')~CDOI:J):II main g) vo ume m£Ul:m atlCDCD:::DG£OI II

"T L IL J T L L L L T

• G~')05mSal call GaT o? calVol( ) function 'f' argument (2) yololmoSll radius ~ height d2 argument atlG~~ pass "26Go:~05q8 calVol(float r, float h) 0008~:~: volume= PI*r*r*h ci5a") formula atl::D:~l~: cylinder volume dSm05().)olmoSll

L· Lr:1t:1 LO IL

• e 0 0 C' C' 0 C' • ( ) ~ , 0<;' ~C' '1 di

G program 0( run "2m~().)arqc « Jo J? 'f'tlcm:O?atlO(c:I:::ICq'f'011l ra IUS =

5.5 ~ height = 7.5 d2cx)~Go:§~olll sphere ~ cylinder volume GOJd2OJ05Go:

o?05ol~1I

Functions

Functions

-

.. 'tJtEJli

:.::] Ex~I I.cpp

II Li sti ng 2.11 : Usi ng overloaded functi ons #include <iostream>

const float PI = 3.141593; float radius, height, volume; void caIVol(float);

void calVol (float, float);

int main()

{

cout « "\nEnter radius: n; cin » radius;

cout « "Enter height: "; cin » height;

cslvol (radi us);

cout « "vnvclume of sphere is " «volume « endl;

calVol (radi us, hei ght);

cout « "\nVolume of cylinder is" «volume « endl; return 0;

void calVol(float r) {

volume = 4"'PI"'r"r"r/3;

void calVol(float r, float h) {

volume = PI"'r"r"h;

c

II Quincy 99

Overloading Function myDate( )

:1 ~ (Ja J~) 'f'BCXY.l:o} Ex2012.cpp program OY.)~b)8 string type date t integer type date b)05~ (2) ~l:02 overloaded myDate( ) function GOJ02ooo.?:Bl~: display ~8~8:0Y.)§S()10')oSll call G~T~G~T i'~:02 GC\'C\Y.)§~()111

~Ex2012.cpp

II Li sti ng 2.1 2: Thi s program shows functi on 1/ myDateO overl oadi ng

# include «Iostreem»

void myDate (char =str): void. myDate(int, int, int);

/ / date as stri ng

/ / date as num bers

int main() {

myDate("20th Apr 2003 "); myDate(4,20,2003); return 0;

void myDate (char =str)

{

(out « "Date: " « str« endl;

void myDate (int month, int day, int year) {

cout « "Date: " « month « "l" « day « "l" « year « endl;

<]--

IIU

JII 3 program ~ run o?oS~oSa?b)8 ~ (Ja J@) 'f'BCXY.l:o}ooo?8: Date: 20th Apr 2003 ~ Date: 4/20/2003) a?o}b)05~ (2) ~l:O? display ~8BGi'()1~1I

Functions

Overloading with Default Arguments

:)11 Ex2013.cpp program o?GC\?C\Y)§~(JoS~q8 repeat_ ch( ) function prototype '

default argument GOJGq:@: overloading ~8o?~:;l1 function name roSy I function defin roS:;ld3O~::D:~lO)')~ cOGC\Y)d)O)')d3Gro o1c8~(JoSll 6 (J. ~o) d3~d;o111

L L L t1 T. L L 0·· L "\ Ll::.:jU.

CJEx2013.cpp

4 . $4 ,t

.0 t Q@Jti

$4 ; 4.

5' 4

/I Listing 2.13: This program demonstrates function II overloading with default arguments.

# include <iostream>

void repeaLch(char = '=', int = 40);

int maine ) {

repeat_ch( ); repeat_chC ..... '); repeaLchCS', 30); return 0;

void repeat.chrchar ch, int n)

{

for (int i=O; l-en; i++) cout« ch; cout « endl;

}

r<r ..

Functions

[>J .::

lUI

'2J

3 program o? run ~05~oSa7E>!8 ~ (J. ?o) ~§an:o?ooo?8: character line (3) Jl:d2 display ~8§0'Y.) G06.E>!~u111

III Quincy 99

Recursion

:)11 recursion ~O'Y.) function ooS:rmGej> same funtion cOo? co8~1ooSa) call §~G~TB:GOO? :n05Ifch.an:o? condition ooS:r ~GGf'05G~:~~8: looping u05Gej>O'Y.)u1ol1 recursive program ooS:ro? run oooo~1g') function call Goo()')'J~I05~18: execute C\)8~:ooGG':co05~Gmu1:J):1I OOGG':Good5 (0'38

o J 0 " iJ L tj lj L IL tj 0 L L

O')Sd38g') ooGu105u1oo:{)C'''':oo88:Gmd5 co~SID8an:Gu:~~JJI:) GC'",8:~~co8~::lY.):u1oooSll ~05~05

L J 0 L::1.J L -0 L ~o L ItIl L::1J tiT 0 J

cm:oo condition ooS~03GQ")05ro')('8 recursion Q8::lY.):GOY.l~ OOGG':Goo03 (d38mG£ :{)C'",:88:GOO

• l L -l- L. -L 0 .J lj 0 L L T tfJ l 0

C ceo) C''''c~c c;I c-, c c .... ' '.... . c ....

O')ID:r~C:~OOGU:~~ GljJc:lj<j>ooIDOOID2i <"'6<j>t{lllO'Y.)m~ooGu:~:~UIUIi 0081()')'J recursion <j>~:U1II

Gcrn8:B I ()m~:ooS:r~ factorial d2 recursive ej>~:~§p§~E>!GOO')811 ~ (J. ? j) ~GE>!:an:o? code statement Goo03r;::;::~u111

o LLJu.

n ! = n x (n - 1) !

(n - 1) ! = (n - 1) x (n - 2) ! (n - 2) ! = (n - 2) x (n - 3) !

Functions

"'=:1I:x2O 14. cpp - ..

. .....

II Listing 2.14: This program calculates the factorial of II a positive integer usi ng recursive method.

# include <iostream> long double facto(int);

int mainO {

int n;

cout « "Enter a number: "; cin» n;

cout « "Factorial of" « n « " is " « facto(n) « endl;

return 0;

long double facto(int l) {

if (i <= 1)

return 1;

else

return (j*facto(i -1 ));

J.--------

<

-

iJ!l

l

4!=4x3! 3!=3x2! 2 ! = 2 xl!

01 0) oS II 3(J)")d38Q GG'd')d3~:lf.) ~G£lf.)olol1 ~:GO')') 8d3Q)8dr;::Q~ function call d3 G~T aJ8d~l

L -1,0 L J J T J t1 0 L U L 0

argument m (n-1) §Sqp:ol~1I 3GO':>1 (n-1)! a?CD~: (n-1) x (n-2)! ~~a5'ia5[§:Ga:>? exe

c "oc" c c~c .... eG>o c" . 0 c c

gC\(OG~:O o(C'i,)OC:OO~Ott~OIO)Q)1I 8C\(~~:~. recursion Of;;omC\(o~'):O)')(J)') arqurnerr

c co r,;:c" c ~ t I I 0 d " c

8d~O)O)~<f:CjlOqp:O')')'f. process (J)')E10qp:tt:Ga:>? ac ua va ue GOJOf reverse or er 'f.O;?~~ll

OJd3ora5GO:[§GCDIl ~ (J. ~~) ~ program run §(X)'):O')')a?§~oll1

Functions

?9

raQuincy99

The Tower of Hanoi

II Quincy 99

Functions

Functions

; .;00

tJ EX2015.cpp' e II III

QUid at

/ / Li sti ng 2.1 5: Thi s program is a gam e used to trans fer / / the di sk s from the I eftm ost pol e to the ri ghtm ost pol e, / / without ever pi aci ng a larger di sk on top of a sm all er

/ / disk. Only one disk may be moved at a time.

# include <iostream>

void transfer (int, char, char, char);

int main() {

int nDisk;

cout « "Welcome to the TOWERS OF HANOI\n\n"; cout « "How many disks? ";

cin » nDisk;

cout « endl;

transfer (nDisk, 'L',' R', 'C'); return 0;

void trans fer(int n, char from, char to, char tem p) {

if (n > 0) {

transfer (n-l, from, temp, to);

cout « "Move disk" « n « " from" « from; cout « .. to " « to « endl;

trans fer (n-1 , tem p,to, from);

~~ L· __ .

1111

.. ..J!.

v

.(3 Passing Structure Variables

function cO~ constant GO) I variable GO)d5O)S~~lt: pass C\)8a3Q::))a3 data type m8~

J 0 0 L L tJ L L·-l L L L

.byo1oto? structure d2~:~C\)~: pass ,,?6Go:d?qo10)o)rr ~ (Jo ,,(5) ~§an:o? Ex2016.cpp

OCt teo f t· "' c!: C o c '1 C § C '1

::rogram OY.)~QC s rue ure coecco unc Ion <DGQ')o)GG'nc pass C\)OGO:&COlo)o)l GC\)C\Y.) coon

L -L L L -L- L L • C!.

II Listing 2.16: This program demonstrates II passing structure as argum ent.

'::::J Ex20 16.cpp

# include <iostream>

struct height
r
int feet;
float inches;
}; void convr(height h) {

cout « h.feet « "\'-"

« h.inches « '",''''« endl;

int main() {

height myH ei ght;

cout « "Enter feet . n . cin » myHeight.feet; cout « "Enter inches: "; cin » myHeight.inches; cout « "My height is "; c onvr(myH ei ght);

return 0;

Functions



• Q)Q)~8: struct d?o} keyword a?ad~:§l@: height d?o} structure name ~o} type

C' 0 C' C' '1 C' "Q" "t t b (2) ~ t"· h

OOQ)yO(::xJOO'fOOGU:UIOO()')1I ad8ror.p~ S ruc ure mem er ym lee <f. me es

u111 main( ) ro<:r:> myHeight eBci) type structure height ad:::DSooS~dS create cu6

J L • L L l



u100uSil

H . ht" f t ,..S. 0 C'" C' k b d 6 00 C' C' C'

my elg q. ee ad~t::::O(GO'Y.)c:~adOJm ey oar mG'i" O(~mroi3:Gu:~Q)

_0 '10 . h C' 0 C'" '1 5 0 C' '1 C' ~ H . ht "

acUI~1I Inc es ad~~O(GO'Y.)C:~adad~1 O(roi3:GU:UI~()')1I OGCJ:>1 my elg q.

member value GooooS~~18:dS m~ulltO'Y.)m::i3:::D?:u1~1I myHeight value GoodS

o L u L oT ~ 0 t1 0 L

convr( ) function ro pass 0.(8GU:E>[Gon811

void convr(height h) function header <:r:> myHight dS h ro G~Bm:ro""GO:

J L IL et

d5a5 u1 0) uS II h mcua5: type structure height G:Sd5 m:roa5Gu:d5QO'Y.)u111 o1eBQt

L c:. ~ L· IL C!. L·-L L -L

main( ) rom structure ooS~ function rodS pass o8:::D?:~Gcull structure value

L L 0 t1

Oft· "" . t C' 0 C' '1 C' "'1 ~ C' . () f t· 0 h C' ()l~

0( unc Ion ror.pu pnn O(OO0.(muIOO()')11 adOI t1:E>[c main unc Ion 0( t1'i"C\Y)(j'

program cu~: @:qp:@§Su100uSu ~ (J. ,,?) a?§~u1u

IDQuincy99

Returning Structure Variables

011 Ex2017.cpp program <..md?98 structure variable GOJa?ad~:§l@: length (2) ya?GU

'1 Q 0 ~C' C'OC'

GU:r.pUIIi 0 program O(GO?C\Y)e:1i3:~().)acE>[c

Functions

II Listing 2.17: This program demonstrates returning a structure

#include <iostream>

struct Length {

int feet;

float inches;

};

void convr(Length);

Length add (Length, Length);

int main() {

Length piece1,piece2,total;

cout « "For piecel\n\tEnter feet cin » piece1.feet;

cout « "\tEnter inches: "; cin > > piecel.inches;

• 11. · ,

cout « endl;

cout < < "For piece2\n\tEnter feet cout « "\tEnter inches: ";

• II. · ,

cin > > piece2.feet; cin » piece2.inches;

total = add(piece1, piece2); cout < < endl;

cout « "Adding piece1 and piece2 gives" « endl; convr(piece1);

cout « " + ";

convr(piece2);

cout « " = ";

convr(total);

cout < < endl;

return 0;

}

Functions

z.inches -= 12.0; z.feet++:

Length add(Length x, Length y) {

Length z;

z.inches = x.inches + y.inches; z.feet = 0;

if (x.inches >= 12.0) {

}

z.feet += x.feet + y.feet;

Functions

G)O

return z;

}

void convr(Length x) {

cout « x.feet « "\'-" « x.inches « "\"";

}

• main( ) ror.p piece1 I piece2 I total ~o? structure type Length §SGnn8 create (\)6 0100 oS II Length Q declaration d5 program d56~:s'):g)GQ:(lY.):01moS

L -to L L T J -L

piece1 ~ piece2 07,q. member value GOJo?~a)ro~Go:~: add() function ~

call G~TolmoSll argument Gm('J) piece1 £ piece2 dSoo structure Gmolol1

o T· L· 0

• add( ) function roo? Gq:>a)C\)')o?!)'d~lr.p piece1 o? x I piece2 o? y ~ro6 assign

(\)6Go:oo!)'dma) x.inches an piece1.inches £!)'dmmolol1 3GO')') z.inches =

l • 0 .,. IL IL 0

x. inches + y.inches = 7+ 11 = 18 ~Solc8GbloSll z.feet d5 0 c8 initialize (\)6ClY.l:

tl· L L· l

0100 oS II z.inches=18 an 12 roa)~:C\)'): I ~C\)'):b?,Gbl:olmoSll 3 <test> ssr:

True ~Soo!)'dma) if block roo8~: z.inches -= 12 :Bblmd3 z.inches = z.inches

Lj·o tJ l·L

-12 = 18-12 = 6 c8ma)molmoSll 1 GO 8roa)C\)')oo!)'dma) z. feet rog)Go18:ro~)GU!

l· 0 IL L 0 • 0 J u.

Qg) Gol II !31G~88 z.feet ++ c8GQ:c8a)O')')oll1 !)'d~dSQ8 z.feet = z.feet + 1 =

-L J. Lj J 0 LO l_e "I L L L-L

0+1 = 1 §S~:~II

• G~'JoSooS~1 z.feet = z.feet + x.feet + y.feet ~o? expression (,),)G~ 1 +25+55 = 81 d3oooSwO')'JC::S()1oooSll G'd~a:3Q8 structure z rog) z.feet =81 ~ z.inches=6

LOlL lj L L "I J Ta

o ~ C' 0 t C' 0 C' " C' dd( ) §C' 0

(')')QGS ~(»OO(\),):II Z c» re urn CU()G0:CU(,),)OOG'dOO(,),) z = a 0::D'J::J.)CU

L -l T L L L L· 0 0 L

main( ) o?GEf'oSo?G'd~1'P total = add(piece1, piece2 ) a:JoS§Sqp:()1~1I ~Go:>?

total member Go;?'P totalJeet = 81 ~ totaLinches = 6 G'd:i5::i5:§SG~§'P()111 convr(total) (,),)G~ G'dG§~oSO(oSG():u1c3~~oSll ~ (Jo ~(f)) o?§~()111

GlQuincy99

Functions

\>.0 The if Statement

c++ programming 00 program ooS~~ program flow ~ control robGo:g80Y..

J L-lo L L L

()J.)~L~8 C++ control statement Gmo1011 C++ OOG<l::D:~tJ::i:>: statement GOOo)Goy)

-L -0 J l tJ- L o·

break case continue default

do else for goto

if return switch

011

if statement :;SOY) conditional statement ooS~r,;:So1oooSll if statement ~::D:ooG<l~1cn

L LIj' L L 0 J

Of ~C: c" 0" t t C ~Q 0 CQ C "c §c t st

I G~omO)O)c:roOO<:\OO < es expr> ~£C\)'):OO:C\)'):;;OOY)O) G<l~CQ)Q)Q)~OIOO(')')1I G<l~tJ:G';l'): C < e

T 0 J 11 0 J T J L L "I -L iJ - •

Program Flow Control

I!)J

if «test expr» <statementl>i

~<C0'f' <test expr> o?G§~8:6?a5o? nonzero stst8 TRUE §SolmoSu 81~st8 program }) <statement1> ~ execute (\)801a3~(,)oSu IR:Q8G£')a5mSG~8:~ :;08: o.n:(,)')ol u mSmoSa3

L L· t1 -t T ~J L 0 J La

<test expr> St.8dG§m zero (FALSE) ~st8 <statement1> o? execute (,)C\(8G~010;(:u next

ine ~ m~::;o8:o.n:(,)')01ou if G£')a5m statement ccocoo mS:;l(X)a58(\)')(,)oS~a3gQ8 brace{ }

L T 0 J T 0 L L L L· jl-L

;;m~ 805Go:a(')G(,)01~u ~~a38aSGo:a3a5Q8 if statement block d5 single statement mS:;lm~:8dG£~

010 La - To L L -L L L c:. T 10

execute C\(8~:'f'§SolmoSu if statement ~oaSO)a5o? Ex301.cpp program o? <c (? o 'f'

;;(9T§(X)')w1moS I GC\'(\)')§t&olu

.~ Ex301:cpp 44 h

hI t (

,JR •• ,ag a: :-'4 4 $

II Listing 3.1 :This program illustrates the use of if statement. #' include <iostream>

int mainO {

short int num;

(out « "Enter a nurnbervn"; (in » num;

if (num < 0) cout « "The number is -ive.\n"; if (num > 0) cout « "The number is - tve.vn": if (num == 0) (out « "The number is zero.vn": return 0;

- .-----.- 1-

1lI1, I

-

• program 0)0)~8:'f' num o? short integer variable o?G§l9(X)'):olmoSu num

Program Flow Control

9.0')~~:(J)') -32,768 mG'l' 32,767 8'4068:'fl~G'l'S[()1~oSll Enter a number ~o?

Prompt G()T C\Y.)0)8'40l1Q') num 8'4O')rh data dS 12 grhcoC).~f5'l-: ENTER key g8

• J 0 L 11 ut1 J

~S[8 num = 12 §S~:()l~1I

• ()CO~:i>: if statement ~GO') ()lO')oSll num a: ~C).)corhcoSC\Y.):m I

L T. o- LC • ~J'~~~"~"'"

zero (FALSE) dScooSGo:cSrhm8'4O')rh m~OIllCfY)m G ~~)a::IO')I[)GI'a:r:)C:(T,>01DC:,';),!:):01ll:

L L L· 0 0 T-I.,I

8d3().) if statement Q') num m ~~corh~:C\Y.): G~:()lO')oSll num = 12 m

L J Lc.:. ~

c~ C '1 C 9 C t t . C 0 'Th

comu:CfY)'j'l'() 10') co II 8G~O;S'l'qjllCfY)m < es expression> G'l'')m'fl~O? e

number is +ive. ~mQ)')G~8:dS m~()'ltCfY)Q')G()T C\Y.)G8'4')8 ro8G0:()10')oS"

L· ~..1 LoT \J J L

C C ~C 0 C C '1

G 'l'') m 0') 4) Gu J C: 0( soco a:) C: C\Y.) 'fl o I"

• G£')rh:i>: if statement mGCfY) num dS ~C).)~~C\Y.):cSG~:()lO')oS" ~C).~()l::n:1I

T L a L LC Toe..:. L. C. IL

§Sa}8'406rh O;S~qjllCfY)m next line o? a:)rha:)8:~:()10')oS" closing brace ( } )

G06.a}8'4011 program [§:~:()1[§1I ~ (\>. j) 'fl program o? run BCO'):()lO')oSll

III Quincy 99

J

~301.cpp program o?BlB8[§: G'l'')rhO')SJjl:GS[:ci?S[CfY)m num (J)') positive

• C 0 C Cf5'l- r.: 0 d· I cr,; '1 0 C C .c C Yi h

-::-Q)()m'l':O')c~: 8'4GtJO( ISP ay ~()~()Iro~~().)" ~or(])S[c ou C ose not

-essage dS display ro&r,;~8:CO'):()10')oSll

L L lj L

Ily Excuting a Program Block

II Listing 3.2:This program cubes a number if it is II not a zero or negative value.

~Ex302.cpp;"; S4" ",,&LU!U. u;; HusPS.z;4 p,,.. • LiJiliJii'

# include <iostream> # include -ccmath»

int main() {

int num;

cout « "Enter a numbervn": cin» num;

if (num)

{

cout « num « " cubed is " « pow(num,3) « end!; return 0;

}

cout :« "You chose not to cornputevn": return 0;

}

W.::

<..I

lilt

II Quincy 99

Program Flow Control

~.J The qoto Statement

to c .... • c ,c: ETC: c:~ 0 c c c e

go 0 ;;00)') program o)lDClQ Og£:xn:G£O)(\)g:G c:mG£ 0)1D :G£rom (\)O)(\)O)(\)OC\)L

L L -10 L J ToT • T T "T L 0 0

c c c c 0 c • ~ c t t t '1' t' • • e 0 '1

YfGmJ?~:ClJCO)Q)ar9c ad~:[jl9gO? 5 a emen 01011 go 0 ~«lDm !3O(OIIi

<label> : target statement;

goto <label>;

~~Ex303.cpp : '*" I. ........

I ; t ,wus A .....

/ / Usting 3.3: This program computes the sum of / I odd numbers from Start through Last.

It include <iostream> int main()

{

unsigned short int start,l ast,odds,sum =0;

cout « "Enter start and lastvn": cin » start » last;

if (start % 2 ! = 0) odds = start;

if (start % 2 == 0) odds = start + 1; AGAIN: if (odds <= last)

{

sum += odds; odds += 2; goto AGAIN;

cout « "Sum of odd numbers" « start « "through" « last;

cout « "vnaquals " « sum « endl;

return 0;

}

<1

iii:

Program Flow Control

name 0111 target statement r.p label o? colon(:) ~~B:G9_:Go:9_01bloSll goto statement o? ~:§l<2O? <2 (". ~) m Ex303.cpp r.pG<.011laYJw10')oS I GC\?C\)')6t&0111

Q t rt 0, 2 eel t _0 , e. c c c

:3 program (J)') s a soco Q) :OClDs:O')Q)QmGS as aJO') GS')m;;n:OClDS:O')Q)Q94O')c:m

L. T L T LO T L T L 0

• program r.p94~:§lbl~ variable (4) yo? unsigned short integer G06~ declare (\)6Go:010')oSll ~GO')') variable GO')~ 0')~8,:GO')(J)') 0 mGS 65,535 94O')t:b)')o2Q01

L • 0 -1.0 T LoT 0 J jl -L

c c c 0 c c c ., nc eo, r;.: c

ccou OJJ1'GO')')o?'06m~cO')')m blOClD1':G069d'):C\(:9_.GO'C:(\):3O( sum enr.p 94Glj06m

enoSb)')0111 :::JY)blO')~O')')QI~O')')blQ)G::D:Qt sum = 0 c8 initialize (\)60J'):010')oSll

L J JO iJ LO L

• Enter start and last ~o? prompt o?GoT~t:010')oSll cin > > start> > last ~o?

statement G~9 start ~ last ~9406~ data G06o? keyboard mG1'~~ent2GO:

Q01bloSil 2 <m~(\)6> 9 d3blmoS 2 <ENTERr> 9 d32~en~rR: ENTER ooSc8~

-L 0 LO L L tl u..t:f L L

bloS~9_t start= 2 I last= 9 §S~:01B"

• ~. Q c t rt· 0 0 c e c '1 c c c

94G9_:e1:~:m Q)e:OClD1': s a (J)')O(C\)'): I blC\)'):~O')')O( 949_CQ)Q)Q)9_OlblOJIl Q)Q)1'~:m

t rt 0 2' r::;: c c h c 0 c t rt !> h c c 0 c • r;.:e '1

saO( t.Q)'):e12?blOJ I blljO')~:~9_c S a mbloClD'j':1I ljO')O')OJ~9_c O(ljQ)r.p011l

start % 2 (start o? 2 ~Q)'):9_t 9~o?94§t:) m ~~~~O')')Golll ~G<J:l1 start % 2 != 0 ~o? <test expression> (J)') FALSE §S~:01B" ~ expression ~G1'')~m odds = start ~o? statement O?O;?~qjllO')')m blG§~t:G<J:l101~:1I G1'')~O')SG~t: d3;;n~ ;;nt: ::D,): bl')01 II

L 0 J

• t650J if mJG<J:l1 <test expression> m TRUE §S~:010')oSll :31G~9 odds =

start+ 1 = 2+ 1 = 3 c80')~OJc8~010')oSll ~c8m94801oSm Q)!5:0ClD~:(J)') 2 r;.:S

LO 0 It L. L L 0 0 C T Lj

GObloS 3 d30 Q)!5:oClD~:c8 m~0'ltO')')mGI,''''t:OJc8~0')')0111 odds £ last d3OJ8c8~c8

• LeT La 0 T iJ t::::1.J It L To L J C L LO

c c 0 c Q c 0 c if c bl k t t tOt c '1 0 c

COJO')OJ O(,blO(O') ~O')OJ~9_c I Gpmm oc s a emen ere execu e C\(001(\)~

bloSll 94y(\)~:O odds = 3 m last = 9 en~coSO')')~ <test expr> m TRUE Goll1 if block cad3otC\)')01rRll sum += odds ~0')')d3 sum = 0+3 = 3 c8 m~olltO')')m

L tf L L LooT iJ

0')~c8~010')oSll 948010Sm sum cad3 oenbl:i>:bloClD~:O')Sro: en:lSc8~0')')0111 3

o L 0 L L T L ~L

rR:Qt :365OJblOClD~:(J)') 5 blmoSO)'):1I ~~:)Q)')Q8,940')~ odds += 2 d394::D:h,rR:

tf -L L T L C Q) -L LO 0 L L tfJlj

odds = odds+2 = 3+2 = 5 ~m :365OJblOClD~:d30')~OJ010')oSll

LOL TLO It

Program Flow Control

• goto statement (JY) AGAIN ~o? label name ~o?G1'9a? §~~:?8:Gl'O')')o1.

° C C bl k t t t C C '1 c, C r;;:c

~y~~co;?l''-lIllO')')(JY) oc s a emen ~06c:CP coo~IO')Q)CI.)oO')Gl'CP[jQ)OIa:)<.UI.

O')S~~cp odds = 11 §S~:o163~QoSll G1~~8 odds = 11 m last = 9 coa5@3:

O')')G§':>S: <test expression> (JY) TRUE §S~:o1B" if block roa?co8Qr.r-,~,""",,·

c 0 c rn

G ~')mO( ;;DC: Cl.)')tj GCI.) II

• Gl'')a5~:cp Sum of odd numbers 2 through 9 equals 24 ~o? output "",,..,,,,,,,,,....,_ a? (2) G§':>8:~B: ~G§CX(a5Go:o163~QOSIl G1~~8 Ex303.cpp program mB:~ o1~11 0 (8. (5) Q')r;:CO'):o)~d38: start =2 ~ last = 10000 63 data :::D8:~Q8 G)

t:1 L"\ J [j 0 L T. L. a D-L

o o§c '1

m ~~CI.) C QQ')O III

L L L -tJ

tit Quincy 99

Reversing an Integer Number

011 Ex304.cpp program St.~E§§oS~a5m d3~:§~om~:O')Sa?:07 input data ~Gl'~

° c c 0 c ,Q cOr,'..,.., c r;: C Q C 'cr;;: C C C C '1' ( )

O(mQo)~~c ~8oml':0( Gtj_.c:tjl'~Q)~Q)21'.[jQ)G~C o;?l''-lIllO')')mO(oGo:cpOIIi c.r ~.? cp

statement G0607G~:§co'):o10')oSll

• Q)Q)~J8:cp unsigned long int num, rev, q, r ~G~:CO'):o?~06a5 3

Program Flow Control

Ifllfl

.• 'SQ+. ,. F.

/ / Listing 3.4: This program reads an integer number

/ / and pri nts out the sam e num ber with di gits reversed.

#i ncl ude <i ostream >

int main() {

unsigned long int

num, rev, q, r;

cout « "Enter a numbsrvn"; cin» num;

q = num flO;

rev = num % 10;

START: if (q != 0)

{

num = q;

q = num flO; r = num % 10;

rev = rev "I< 1 0 + r; goto START;

cout « "The number reversed isvn" « rev« endl; return 0;

1111

L~J .,'



GOJ~O)~~:o? 0 mG;'> 4,264,967,295 adOJ8:'P Bla5o}()m~:~ assign <.\(8~901[911 Enter a number ~o} prompt GoT (\)')[9: cin > > num G§P9 num adOJa5 data o?G(J")')8:G;'> 01[9 II keyboard mG;'> 123456789 o?~a5co~Go:o?a5~oS~98 num = 123456789 r;.:S:xn:g:,oll1

L:l 0 J

q O)~g:d3 q = nLim/lO =123456789/10 = 12345678 ~O)a5().)olO)oSl/ rev =

T L L L.t' 0 IL

num % 10 = 123456789 % 10 = 9 Goll1 if ( q ! = 0 ) ~o} <test expr> o?

o;5~oJll(J")')m TRUE ~adG§ard)olO)oSl/ q co ~~'f~O(d)(J")')o?:1/ ~Goy? if block

'c ~ cor;.: c ') c

CO oc (\)')tj: o;5;'>0JllO)')mady<.\(GL:l~c:o 10)()')1I

Program Flow Control

II Quincy 99

num = q = 12345678

q = num / 10 = 12345678 / 10 = 1234567 r = num % 10 = 12345678 % 10 = 8

rev = rev*10 + r = 9*10 + 8 = 98

• goto START G§':>9 o;5~()Jllanm START label ~o}G'i'~d? §~qs:>:()1moSll q m

c , C Of bl k ,0 C C Cr,::;Q.C~C C IJl. of

~~(:larmO?Gdo;sm I oc mac o;5'i'<-iJllanm G'i''JmmQ)e_j(:ltj'i'0CC\Y.)tjGC\)II I

block OO(:l') Gd~c8G~o::'\8:()1moSll

J LLt:JJI

num = q = 1234567

q = num / 10 = 1234567 / 10 = 123456 r = num % 10 = 1234567 % 10 = 7

rev = rev*10 + r = 98*10 + 7 = 987 goto START d?§~qs:>:u111

• mS~hr) q = 0 §Sqs:>:l9: if block oomq:05C\Y.)'['()111 G'i''J05a?:,[, The number reversed is : 987654321 c8 mSGr,:;:,.,8:~~IJl.: GdG~9.05m05G()w1c8~(:loSll :31~Q8

L· L_:1..J 0 r:1 t:J't1 L • L -L

program [9:::l6-'w1[911 GdG§d? ~ (". 4)) '[' program run §CO'Jw1moSll

Program Flow Control

A Payroll Program

_" 4

II Listing 3.5: This program calculates the payroll for II different workers giving overtime if the hours

II worked are greater than 40 hours.

#include <iostream>

int main() {

int category;

float wage, hours, pay;

START: cout < < "\ nEnter category (any of 1 to 4)\ n": cin » category;

if (category < 1 II category> 4)

goto START;

if (category == 1) wage = 12.5; if (category == 2) wage = 15.5; if (category == 3) wage = 20.5; if (category == 4) wage = 25.5; cout « "Enter hours worksdvn": cin » hours;

if (hours <= 40)

pay = waqe=hours: if (hours> 40)

pay = wage"'40 + 1 .5"'wage"'(hours-40); cout « "Pay = " « pay « endl ;

return 0;

1111

_, _ ._'0 .. , ."M. __ ". __ , .•.•

r>J .. :

Program Flow Control

Program Flow Control

@J

rIIQuincy99

The if-else Statement

811 program o:>SyGq:o?8<l~l~ G§=Q)~roG:G[g:>8: (2) Y§C\Y.lq8 if-else statement o?~:~9 010:> oS II if G<j'>'JoSm <test expr> 0'Y.l'i~o:>oSa?q8 <staternentt > o?G§~8:[9: if-else 8<l§tO?q?05 :J.Y):lf.)~Solo:>oSll <test expr> If.):GSQt <statement2> cf.> execute roolf.)oll1 statement GO:>CJY.)

o J L:1 J T -L L L J 0

o:>SG[g:>t:cooSyC\Y.lqt brace { } G06~8a5Go:qo1bloSll if-else statement q.~Q)m 8<lyJ?oll1

if ( <test expr> ) <statement1>;

else

< statement2 > ;

II Li sti ng 3.6: Thi s program reads a lowercase character, II converts it to uppercase and then writes out

II the uppercase eqivalent.

#include <iostream>

int main() {

char lower, upper;

cout « "Enter a lowercase charactervn": cin » lower;

if (lower >= 'a' && lower <= 'z') upper = 'A' + lower - 'a';

else

upper = lower;

cout « "Uppercase equivalent is " « upper « endl; return 0;

E 306 0 r;::;::: ceo C

JI X .cpp program O(Ga;>(\)')e,jE2~<..Dd(~c

• program 00~8:1P lower ~ upper a2o? variable (2) yo? character GD6~G§1P olmoSu Enter a lowercase character ~o? prompt mSy 06~o~lOJ')~ GoT (\),)o?8dQl lower 8dmch data dS e a3~chco~ol~oSu Gl~Q8 lower = 'e' ~S~:ol~n

o L LO L Ci.. L -[ t::j 0 lj

• if (lower >= 'a' && lower <='z') a2~ relational expression G~:3~:~ lower 00

'a' cochE:3:[9: 't: cochcoSolmoSn 3GaJ?8dGBoo TRUE Golil upper = 'A'+lower'a' ~S~:ol~u upper ~ ASCII mf.8:dS upper = 65+ 101-97 =69 a3mcha3Q

Cj 0 r:1 -La T L L L. a LO -L

olmoSu ASCII mf,8: 69 00 uppercase letter E dSd3a3OJ')oln ~:Q8 else G8d')ch

'r t LLL lj-L

o c 0 C C '"l~

ooC\(c:O( Goo.r~C:~:OltjU

Program Flow Control

• cout « "Uppercase equivalent is :\n" « upper ~o? statement Gtp9 ~G§ E q?aScooO)')G()l11 ~ (? 8 j) "p program run Bro:>:O)')az6~()111 (J)l!)o:)().);~

kb d EOQC C coc C co CC, ''10

ey oar mGt 0( ~lmOJ~GO:~().)d(~c OJt~llO)') X>()')C\(~C\«)C\«)~c\)1I ~!310(

W~d:J~d2oSo?8 C\)aSGOJ.~G§~6t§()111

A Temperature Conversion Program

811 Ex307.cpp program CfY) degree Fahrenheit mG£ Celsius d3Gr,'yo,8:G():~8:»c8 degree

T L ljJ L L

C I . C h hett oCr,' yo, C Q C , C '1 , fI C d t ° 1 ° C C e SIUS mG<j> ,a ren el O(c\)~:Gt1Jc:G():~cO? program (J)Q)~()I()II ag ~OJm a a or l1mOJ2r

C ° cdC I . C h helt ° C r,'yo, C '1 ° C C 2 ° C C C

G():~()')~~c egree e SIUS mG~ ra ren el O(c\)~:Gt1JC:G():OIC\)'i~()')1I l1mOJ~G():qCGo:Y?

degree Fahrenheit mG<j> Celsius d2c\)~:G[p8:GO:"P()111 3~OJaS source code GOJd2 ~ (? 8?) "PG~:Bro:>:()l(J)oS I Ga;>coo6~()111

JI ~ (? 89) "p program run Bro:>:()l(J)oSll flag ~OJaS data d? 1 ~aSOJ~G():B: degree

Celsius = 100 d2~aSOJ~GO:O)')~ Fahrenheit = 212 ~ display C\(8BG~()lB"

Program Flow Control

"*~' ; •• ¥ $ "''''''='''. kt%.4gu. sq. >a;.li;:1.F· .. I~"t~." ~.-:.~ ..... l.t?! ... '9-1 .:ti:J(€iJii~

, Ex307.cpp " ·0"'", , ',., ., •. " "" • ~ -. '

1/ Li sti ng 3.7: A program that gives the user the opti on of 1/ converti ng Fahrenheit to Cel si us or Cel si us to Fahrenheit. #include <iostream>

int main() {

int flag;

double tempr;

cout « "\nType 1 to convert Fahrenheit to Celsius: " « "\nType 2 to convert Celsius to Fahrenheit: " « endl;

cin » flag;

if (flag == 1)

cout « "Enter temperature in deg Fahrenheit: "; cin »tempr;

cout « "Celsius = " « (tempr-32)/l.8 « endl;

else {

cout « "Enter temperature in deg Celsius: "; cin »tempr;

cout « "Fahrenheit = " « 1 .8Wtempr+32 « endl;

return 0;

- .. .J

, " .. 1111.

II QUincy 99

Program Flow Control



Program 00~18:oo num1 ~ num2 dSd5 integer variable GOJc8G~~olOJoSll

I.J J To t.- L 0 L. UI.jJ

Enter two numbers a?, prompt GoT c\y')o?8d~1~q8 num 1 OJ~~:J? 13 a?,~a5 OO:"l)Go:(,loSdSolSIl GldSQ8 num1 = 13 ~S~:ol~11 num2 OJ~g:d5G0'Y)8:OO8d~loo

Ci, L La L -L t:j 0 t1 T L L 0 J

Nested if Statement

011 nested if-else statement ()J) if statement GG7:>a5oou8dml[:o801OJoSll G~ 88:ooOJl,:m

J IJ jlo L J L T

ceo , , lf Itt t C (2) ,0 COr,',,",' 'l~"f C

o;sJ'I'GO'Y)~GC\lC\Y.)~O? I -e se s a emen GOJ'P G§!0&P(\)(,l: yO~OJU)nr,GljJ~Olljll I G'I''Jmm

<test expr> ()J) TRUE dSQt:x> G~oa5m <statement> d5G~~t:(,loS I FALSE dSQt else G~oa5m

l -l \LO T L l:j 11 L -L T

8d(\)0u(\)0000111 G1Gr,::;:,...88~:0Q')(\)~: (2) ~ugO'Y)c8Gr,',,",O'Y)olulI OJSmoSc8 ~:0Q')(\)~:GOJ 8d(,lr:l:~.

L L J ~J. ~ 0 -L- L jl ~ ljJ ~ 0 -L- 0 ij- t:t

d5 create (\)0~,8Q8 nested if-else statement GOJd58do.):~lQtQolOJoSll oo:ooS:Q8 brace GOJd5

L LiJ-L OL Ltj-L-L JJL-L OL

00 0 0 C '1. ( ) ~ 'E 308 0 C I ted if

««~~ OOe.:GOWIIi « ~. o~ 'PG(J)I ljOO'J:O? X .cpp program ()J)~qc camp ex nes I

statement GOJ 8d~:§l~§l'l'~:J? 'I'~'I''JGq:§OO'J:O'Y)§SolOJoSll

4 d5ga5oo:"l)Gowl(,loSu

L tl Ci.

• program m 8d§80')a58d~a?: if statement 'P num1= 13 m num2= 4 ooa5

P1.:C\Y.): I :"l'SC\Y.):c8G(,l:olOJoSll <test expr> ()J) TRUE ~SOO8dOJa5 co GG7:>a5m

~ c.:. L· lj • a IL-

if statement J?;;oa5[9: execute ~001OJoSll 8d(\)oS~8:~o? if statement 'P(\)~:

num1 = 13 m num2 = 4 ~ ~C\Y.):a?,oo0G(,l:olOJoSll ~ <test expr> en FALSE

~ C '1 C gee '"f I 0 c~ 0 "f I' C

tj0G'I'0IOJu)1I GGa:Y.?, 8dOJc:O')m8dmJ~: I -e se OCGmPlj: tOJu) I -e se q_G'I''Jmm

<statement> J? execute ~001[911 They are not evenly divisible" ~o?0')G&8:

C d" I C~ '1 0 C C

o;?'I'0JllO'Y)'P ISP ay ~OljOI(\)';l(,lu)1I

• 8dy~q8 8d§80')a58d~a?: if-else q.8d~0[9:~:ol[911 [9:q8 closing brace ( } ) a3J?G&pa5~:o?8dOJa5 program [9:~:ol[911

~II ~ (~. 0(5) 'P Ex308.cpp program J? run §OO'J:olOJoSll num1 = 13 I num2 = 4 §Sq8 They are not evenly divisible. -£00 message d5 display (\)0~oooll1 num1 = 16 I num2 = 4

L • L L L::1J

§Sq8 O')oS~ message J? display ~0§(,lc\) I ~~'i~:§~oll1 [9:q8 program run §~[9: 8dG§~a5

o '1 C nr,qOIOJu)1I

Program Flow Control

Ir'_j __ ·-...t:~ ....... ;...o;..I'...;.&;.CPP_"_·":_-_·_·· ···_'·_··_·· ~

II Listing 3.8: This program demonstrates a complex, /! nested if statem ent

#include <iostream>

int main() {

int num 1 , num 2;

cout « "Enter two numbersvnrtrst cin » numl;

cout « "Second: "; cin» num2;

if (num 1 >= num 2) {

if (numl % num2 == 0) {

jf (num 1 == num 2)

cout « "They are the same.vn":

else

cout « "They are evenly divi sible.vn";

else

cout « "They are not evenly dlvlstble.vn":

else

cout « "The second one is I aruer.vn": return 0;

}

~:----------------uu--.-. ------_- .. -~-~--~~

III Quincy 99

Program Flow Control

9" Ex308.cpp program r.p brace (;qsd2§Ia5~: ~ (? O?) r.p§CXY):a}ooa?8: §8(;6)=~J3~6)8

ox~: run cSQo10)J311 OO(;~ro~S:ooo)o)Q'=l?o111 w~a5o:)('J3J3d38rocfJ(;0) run ~a50111

c:. L· -1 L:l C. IL IL -lJ IL L L -0· L.:1C!..

'3M. lit &ltatk ... ,..... 4{ v AM ..• ;.eM .4 S .",CWt . Jlut;:P" '_'-F1r:;,~

..• s I.:Jl£Jw

31~~())a5 program logic dSoo~c8~8(;Q:IR: run Q8roa5: OO(;~ooo)O)Q'=l?o111 ~ program

J L L L Lt:::1 -rtf -l c:. L:l IL Il -lJ

m compact ~§SO)uSd?.ro8010)uSll ~ (? oG») o?§t§oll1

#include <iostream>

int main() {

int num 1 , num 2;

cout « "Enter two numbers\nFirst . ". cln » numl;

cout « "Second: "; cin» num2;

if (num 1 >= num 2)

if (numl % num2 == 0)

if (numl == num2)

cout « "They are the same.vn":

else

(out « "They are evenly dlvlslble.vn":

else

(out « "They are not evenly dlvlstble.in":

else

cout « "The second one is laruer.vn": return 0;

liJ

I

Ex308B.cpp program d2 run §t§6)8 ~ (?o o@) r.p§CXY):a}ooa?8:§86)r.po111 First = 15 ~ Second = 100 d? data rot§(;o:6)8 The second one is larger. ~a}OO(;§o? display

C'~ '1 DC' C'

C\(0t10lro~~u)1I

Gil

1111

Program Flow Control

~:::J Ex308B.cpp

'.(.. . ..

#include -clostream»

int mainO {

int num 1, num 2;

cout « "Enter two numbers\nFirst . u . cin» numl;

cout « "Second: "; cin» num2;

if (numl < num2)

cout « "The second one is l arqer.vn"; else if (numl % num2!= 0)

cout « "They are not evenly divisible.Yn"; else if (numl != num2)

cout « "They are evenly dlvlsible.vn":

else

cout « "They are the same.vn":

return 0;

<] -

III!

_I

rDQuincy99

Program Flow Control

Leap Year Test

}

-<_c~:~-~·~-- _-,--~~

"._"

·~Ex309.~-

a ,@

.. _.'

. Z4,' ... '. ,';

I

II Listing 3.9: This program reads in a number representing

/ / a year and then determines whether it is a leap year or not.

#include «rostraam» const int TRUE=l; const int F ALSE=O;

int main() {

int year, leap;

cout « "Enter a year ("''''''''I')\n''; cin »year;

if (year % 4 != 0)

else if (year % 100 ! = 0) else if (year % 400 == 0) else leap = FALSE;

leap = FALSE; leap = TRUE; leap = TRUE;

if (leap) else

cout «year « " is a LEAP vear.vn";

cout « year« " is NOT a LEAP vear.vn":

return 0;

IlII

- -_-, _--][}] .:

Program Flow Control

000

• 1998 QIiiS()')") ol~roo()lJ.):1I OY.lG":lc3c\)~GOYJ 1998 cf.J 4 sro:Q~~G":oSc3()loll 2000

L J IL t1 LO L· L T· "l t1 L·

Q&iSm 01roo()1rooS" OY.lG":lc3c\)~GOYJ 2000 cf.J 4 sro:OYJG":oSrooS" 100 ~roOro:

LJ l:::f LO L. L T. L:f T-

OYJG":oSG::D:rooSll 3GOYJ 400 sroOro:rooS" G":oSG::D:OYJo" !3l~Q~ 2000 Q&iS()')")

t1 • To L:f L-l lJ

G::DQPolrooOYJG()l11

• 5000 y,SmJGo:>? ol~rooGa:rpj(:1I OY.l§l~c\)d?Go:>? eeoc 4 ~ro:OYJ§oSGO":q 100 ~roOro:GOYJ.§oSrooS" !31G()~~ 400 ~ro:Ga:l1~§oSGa:l1~:1I !31G§:>~~ 5000 y,S()')") ol~roo~:c3Gr,''''OYJ()ll1 3q)S£~:Grold.> nested if-else statement Grocf.J G<I::D:G":lCOJ:

IL L· tj..l T C 0 J 0 L L L::1

()lrooS" Ex309.cpp program J2 run §~q~ ~ (~. JO) 'P§COJ:o)G<lo?8:§~9'P()111

year= 2003 d?,ro~Gm98 2003 is NOT a LEAP year. d?o)G<lG§J2 display orO

G":'lOC C 1::l()1(\)';l~u)1I

The while Statement

c++ I c 0 C "I c, C CQ 00 C hOI t t t 0

0" program 'P oop roQ)yO( ro()Q,roq)(\)()ro9Ga:l1~U)~~~qc W I e s a emen 0(

G<I:::D:G":lc3Q()lrooSll while statement ~ 00m G<lQc3()ln

L L:1 L·-l -LeL L L

000

Program Flow Control

while «test expr> )

<statementl> ;

e • • 0 C C C h'I' C c, t t exoro os t t c.... ..C" ~'(Q)(J)')a:r~c o;s'i'0JllO')')~ Q)Q)~c: W Ie 9,_G'i'':>mmo;sc:a::>m < es expr> 0( es O(00lcnWl

~.~cntr.m nonzero (TRUE) §S~~8 '"'6~'-lIllO')')m <statementl> d2 execute 0(8~o111 cnd)moS~ <test expr> ~ cn~g:m zero (FALSE) ~d):)J'):~oS~Q8 while loop d3 execute ~C\)8GO')')o10):a

-f!t T L (j' 0 L -l L L· Il

t t t [1 0 C b ,0 co .... '

sa emen Gcnm8d~I"): :a:)QC race GcnsocnGO:<.D~G~OI£1I

o I,J- L "I 0 To L. 0 T

JII 8drcn8§~~ Ex301O.cpp program (J)')a?~8 1 mG'i' 9 8da3om~: (9) ~:a? Q)')cnSG§-:>8:

C rr C h'l t t t • ~~ ~c.... C C c., c. ~

cn~:~GOI C\)')G8d')C W ne s a emen 8d~:t1It1:G~CX)'):O')')I:jQ)Olcno)lI om":O)Q)o(:<f.cnQ)O(:uJ:~

space cnd)y[p:GO:CX)'):01cnoSll ~ (? Jj) ~G~§CX)'):o? code statement G06a?GO?C\)')§~o111

~ Ex3010.cpp. 4 i i 4$ i4Ai? 'F*iII'+,! . =7"""" ..... '+' 9" kJLaliJ'

II Listing 3.10: This program displays the consecutive 1/ digits 0,1,2,3, ... ,9 with all digits in one line

II separated by one space between them.

#include -crostrearn»

int maine) {

int digit = 0;

while (di git <= 9) {

II Print a digit followed by a space cout « digit «" "

++ digit;

cout « endl; return 0;

} <1.

1111

- . - ~-- -_." -

Program Flow Control

OOJ

Вам также может понравиться