Professional Documents
Culture Documents
Chapter 3 - Functions: 2000 Prentice Hall, Inc. All Rights Reserved
Chapter 3 - Functions: 2000 Prentice Hall, Inc. All Rights Reserved
Outline 3.1 3.2 3.3 3. 3.! 3.$ 3.% 3.' 3.+ 3.10 3.11 3.12 3.13 3.1 3.1! Introduction Program Components in C++ Math Library Functions Functions Function "e#initions Function Prototypes &eader Files (andom )umber *eneration ,-ample. / *ame o# Chance and Introducing enum 1torage Classes 1cope (ules (ecursion ,-ample 2sing (ecursion. 3he Fibonacci 1eries (ecursion 4s. Iteration Functions 5ith ,mpty Parameter Lists
Chapter 3 - Functions
Outline 3.1$ 3.1% 3.1' 3.1+ 3.20 3.21 Inline Functions (e#erences and (e#erence Parameters "e#ault /rguments 2nary 1cope (esolution Operator Function O4erloading Function 3emplates
Introduction
" Construct a progra# $ro# s#aller pieces or co#ponents " %ach piece #ore #anagea&le than the original progra#
'
3.2
Function de$initions
" 4nl) (ritten once " .hese state#ents are hidden $ro# other $unctions. " 1oss to (or+er analog)2
The boss does not know how the worker gets the job done; he just wants it done
3.3
%7a#ple
cout << sqrt( 900.0 );
" Calls the sqrt /s!uare root0 $unction. .he preceding state#ent (ould print 30 " .he sqrt $unction ta+es an argu#ent o$ t)pe double and returns a result o$ t)pe double, as do all $unctions in the #ath li&rar)
2000 Prentice Hall, Inc. All rights reserved.
3.3
" Constants
" 9aria&les
sqrt( x );
" %7pressions
sqrt( sqrt( x ) ) : sqrt( 3 - 6x );
3. Functions
Functions
=ocal varia&les
" >no(n onl) in the $unction in (hich the) are de$ined " All varia&les declared in $unction de$initions are local varia&les
Para#eters
" =ocal varia&les passed (hen the $unction is called that provide the $unction (ith outside in$or#ation
3.!
Function "e#initions
%7a#ple2
int square( int y) return y ! y; "
2000 Prentice Hall, Inc. All rights reserved.
# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3
$$ %i&. 3.3' (i&03)03.c** $$ ,reatin& and usin& a *ro&rammer-de(ined (unction -include <iostream> usin& std''cout; usin& std''endl; int square( int ); int main() (or ( int x 1 #; x <1 #0; x22 ) cout << square( x ) << 3 3; cout << endl; return 0; " $$ %unction de(inition int square( int y ) return y ! y; "
Outline
10
1. Function prototype Cotice ho( para#eters and return value are declared.
$$ (unction *rototy*e
#6
+.
36
49
64
0#
#00
Program Output
# + 3 4 . 6 / 0 9 #0
$$ %i&. 3.4' (i&03)04.c** $$ %indin& the maximum o( three inte&ers -include <iostream>
Outline
11
## int main() #+ #3 #4 #. #6 #/ #0 #9 $$ a4 b and c belo6 are ar&uments to $$ the maximum (unction call cout << 35nter three inte&ers' 3; cin >> a >> b >> c; int a4 b4 c;
+0 2000 cout << 37aximum is' 3 reserved. << maximum( a4 b4 c ) << endl; Prentice Hall, Inc. All rights
+# ++ +3 +4 +. +6 +/ +0 +9 30 3# 3+ 33 34 3. 36 3/ 30 39
return 0; " $$ %unction maximum de(inition $$ x4 y and 8 belo6 are *arameters to $$ the maximum (unction de(inition int maximum( int x4 int y4 int 8 ) int max 1 x; i( ( y > max ) max 1 y; i( ( 8 > max ) max 1 8; return max; "
Outline
12
3. Function de#inition
5nter three inte&ers' ++ 0. #/ 7aximum is' 0. 5nter three inte&ers' 9+ 3. #4 7aximum is' 9+ 5nter three inte&ers' 4. #9 90 7aximum is' 90
Program Output
3.$
" Function na#e " Para#eters
Function Prototypes
13
Function protot)pe
In$or#ation the $unction ta+es in
" 4nl) needed i$ $unction de$inition co#es a$ter the $unction call in the progra#
%7a#ple2
int maximum( int4 int4 int );
&eader Files
1'
" Contain $unction protot)pes $or li&rar) $unctions <cstdlib> , <cmath>, etc. " =oad (ith -include <(ilename>
%7a#ple2 -include <cmath>
3.'
13
rand $unction
i 1 rand();
" =oad <cstdlib> " Eenerates a pseudorando# nu#&er &et(een 0 and :;<=)7;> /usuall) 328580
A pseudorando# nu#&er is a preset se!uence o$ Frando#F nu#&ers .he sa#e se!uence is generated upon ever) progra# e7ecution
srand $unction
" Gu#ps to a seeded location in a Frando#F se!uence
srand( seed ); srand( time( 0 ) ); $$must include <ctime>
time( 0 )
.he ti#e at (hich the progra# (as co#piled
" Changes the seed ever) ti#e the progra# is co#piled, there&) allo(ing rand to generate rando# nu#&ers
2000 Prentice Hall, Inc. All rights reserved.
3.' Dcaling
15
" %7a#ple
i 1 rand() ? 6 2 #; Eenerates a nu#&er &et(een # and 6
# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4
$$ %i&. 3./' (i&03)0/.c** $$ @hi(ted4 scaled inte&ers *roduced by # 2 rand() ? 6 -include <iostream> usin& std''cout; usin& std''endl; -include <iomani*> usin& std''set6; -include <cstdlib> int main() (or ( int i 1 #; i <1 +0; i22 ) cout << set6( #0 ) << ( # 2 rand() ? 6 ); i( ( i ? . 11 0 ) cout << endl; " return 0; "
Outline
1. "e#ine loop 2. Output random number
18
Cotice rand() ? 6 . .his returns a nu#&er &et(een 0 and 5 /scaling0. Add 1 to get a nu#&er &et(een # and 6.
%7ecuting the progra# again gives the sa#e Frando#F dice rolls.
. 4 3 # 3 + + 4 . . + 6 . . # 4
. + . .
Program Output
# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4 +. +6 +/ +0 +9 30 3#
$$ %i&. 3.9' (i&03)09.c** $$ :andomi8in& die-rollin& *ro&ram -include <iostream> usin& std''cout; usin& std''cin; usin& std''endl; -include <iomani*> usin& std''set6; -include <cstdlib> int main() unsi&ned seed; cout << 35nter seed' 3; cin >> seed; srand( seed ); (or ( int i 1 #; i <1 #0; i22 ) cout << set6( #0 ) << # 2 rand() ? 6; i( ( i ? . 11 0 ) cout << endl; "
Outline
1. Initiali8e seed
1;
2. Input 4alue #or seed 2.1 2se srand to change random se9uence 2.2 "e#ine Loop 3. *enerate and output random numbers
return 0;
6 6
. 3
# #
4 +
Outline
Program Output
1?
+ . 6 6
6 # . 3
4 4 # #
3 4 4 +
3.+
# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4 +. +6 +/ +0 +9 30 3# 3+ 33 34
$$ %i&. 3.#0' (i&03)#0.c** $$ ,ra*s -include <iostream> usin& std''cout; usin& std''endl; -include <cstdlib> -include <ctime> usin& std''time; int roll=ice( 9oid ); int main() enum @tatus ,A<BC<D54 EA<4 FA@B "; int sum4 myJoint; @tatus &ame@tatus; srand( time( 0 ) ); sum 1 roll=ice(); $$ (unction *rototy*e
Outline
22
1. roll=ice prototype 1.1 Initiali8e 4ariables and enum 1.2 1eed srand 2. "e#ine s6itch statement #or 5in:loss:continue
s6itch ( sum ) case /' case ##' $$ 6in on (irst roll &ame@tatus 1 EA<; breaM; case +' case 3' case #+' $$ lose on (irst roll &ame@tatus 1 FA@B; breaM; 2000 Prentice Hall, Inc. All rights reserved.
$$ remember *oint
Outline
2.1 "e#ine loop to continue playing 2.2 Print 5in:loss
23
6hile ( &ame@tatus 11 ,A<BC<D5 ) sum 1 roll=ice(); i( ( sum 11 myJoint ) &ame@tatus 1 EA<; else i( ( sum 11 / ) &ame@tatus 1 FA@B;
$$ Mee* rollin&
$$ lose by rollin& /
i( ( &ame@tatus 11 EA< ) cout << 3Jlayer 6ins3 << endl; else cout << 3Jlayer loses3 << endl; return 0;
60 int roll=ice( 9oid ) 61 62 int die#4 die+4 6orM@um; 63 64 die# 1 # 2 rand() ? 6; 65 die+ 1 # 2 rand() ? 6; 66 6orM@um 1 die# 2 die+; 67 cout << 3Jlayer rolled 3 << die# << 3 2 3 << die+ 68 << 3 1 3 << 6orM@um << endl; 69 70 return 6orM@um; 71 " Jlayer rolled 6 2 . 1 ## Jlayer 6ins Jlayer rolled 6 2 . 1 ## Jlayer 6ins Jlayer rolled Joint is #0 Jlayer rolled Jlayer rolled Jlayer rolled Jlayer rolled Jlayer 6ins 4 2 6 1 #0 + 6 3 6 2 2 2 2 4 . 3 4 1 1 1 1 6 ## 6 #0
Outline
3. "e#ine roll=ice #unction
2'
Program Output
Jlayer rolled # 2 3 1 4 Joint is 4 Jlayer rolled # 2 4 1 . Jlayer rolled . 2 4 1 9 Jlayer rolled 4 2 6 1 #0 Jlayer rolled 6 2 3 1 9 Jlayer rolled # 2 + 1 3 Jlayer rolled . 2 + 1 / Jlayer loses 2000 Prentice Hall, Inc. All rights reserved.
23
" Dcope
Jhere o&Kect is re$erenced in progra#
" =in+age
Jhere an identi$ier is +no(n
Auto#atic storage
" 4&Kect created and destro)ed (ithin its &loc+ auto
e$ault $or local varia&les. %7a#ple2 auto (loat x4 y;
re&ister
Tries to put variables into high-speed registers
25
=ocal varia&les de$ined in $unctions >eep value a$ter $unction ends 4nl) +no(n in their o(n $unction
5xtern
e$ault $or glo&al varia&les and $unctions. >no(n in an) $unction
28
" e$ined outside a $unction, +no(n in all $unctions " %7a#ples include, glo&al varia&les, $unction de$initions and $unctions protot)pes
Function scope
" Can onl) &e re$erenced inside a $unction &od) " 4nl) la&els /start', case', etc.0
1loc+ scope
" eclared inside a &loc+. 1egins at declaration, ends at B " 9aria&les, $unction para#eters /local varia&les o$ $unction0 " 4uter &loc+s *hidden, $ro# inner &loc+s i$ sa#e varia&le na#e
# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4 +. +6 +/ +0 +9 30 3# 3+ 33 34
$$ %i&. 3.#+' (i&03)#+.c** $$ ; sco*in& exam*le -include <iostream> usin& std''cout; usin& std''endl; 9oid a( 9oid ); 9oid b( 9oid ); 9oid c( 9oid ); int x 1 #; int main() int x 1 .; $$ local 9ariable to main $$ (unction *rototy*e $$ (unction *rototy*e $$ (unction *rototy*e $$ &lobal
Outline
2;
1. Function prototypes 1.1 Initiali8e global 4ariable 1.2 Initiali8e local 4ariable 1.3 Initiali8e local 4ariable in bloc; 2. Call #unctions 3. Output results
cout << 3local x in outer sco*e o( main is 3 << x << endl; $$ start ne6 sco*e int x 1 /; cout << 3local x in inner sco*e o( main is 3 << x << endl; $$ end ne6 sco*e
"
cout << 3local x in outer sco*e o( main is 3 << x << endl; a(); $$ a has automatic local x b(); $$ b has static locallocal x x in outer sco*e o( main is . c(); $$ c uses &lobal x local x in inner sco*e o( main is / a(); $$ a reinitiali8es automatic local x sco*e o( main is . local x in outer b(); $$ static local x retains its *re9ious 9alue c(); $$ &lobal x also retains its 9alue 2000 Prentice Hall, Inc. All rights reserved.
3. 36 3/ 30 39 40 4# 4+ 43 44 4. 46 4/ 40 49 .0 .# .+ .3 .4 .. .6 ./ .0 .9 60 6# 6+ 63 64 6. 66 6/ 60
cout << 3local x in main is 3 << x << endl; return 0; " 9oid a( 9oid ) int x 1 +.; cout << << 22x; cout << << " 9oid b( 9oid ) static int x 1 .0; cout << << 22x; cout << << " 9oid c( 9oid )
Outline
2?
=ocal auto#atic varia&les are created and destro)ed each 3.1 "e#ine Functions ti#e a is called.
$$ initiali8ed each time a is called
endl << 3local x in a is 3 << x 3 a(ter enterin& a3 << endl; 3local x in a is 3 << x 3 be(ore exitin& a3 << endl;
$$ @tatic initiali8ation only destro)ed (hen the $unction $$ (irst time b is called. ends. endl << 3local static x is 3 << x 3 on enterin& b3 << endl; local static x is .0 on enterin& b 3local static x is 3 << x local static x is .# on exitin& b 3 on exitin& b3 << endl;
cout << endl << 3&lobal x is 3 << x << 3 on enterin& c3 << endl; x !1 #0; cout << 3&lobal x is 3 << x << 3 on exitin& c3 << endl; 2000 Prentice Hall, Inc. All rights reserved. "
local x in outer sco*e o( main is . local x in inner sco*e o( main is / local x in outer sco*e o( main is . local x in a is +. a(ter enterin& a local x in a is +6 be(ore exitin& a local static x is .0 on enterin& b local static x is .# on exitin& b &lobal x is # on enterin& c &lobal x is #0 on exitin& c local x in a is +. a(ter enterin& a local x in a is +6 be(ore exitin& a local static x is .# on enterin& b local static x is .+ on exitin& b &lobal x is #0 on enterin& c &lobal x is #00 on exitin& c local x in main is .
Outline
Program Output
30
31
" Are $unctions that calls the#selves " Can onl) solve a &ase case " I$ not &ase case, the $unction &rea+s the pro&le# into a slightl) s#aller, slightl) si#pler, pro&le# that rese#&les the original pro&le# and
=aunches a ne( cop) o$ itsel$ to (or+ on the s#aller pro&le#, slo(l) converging to(ards the &ase case 6a+es a call to itsel$ inside the return state#ent
" %ventuall) the &ase case gets solved and then that value (or+s its (a) &ac+ up to solve the (hole pro&le#
32
)" 0
return
f( 2 )
f( 1 )
return
f( 1 )
f( 0 )
return 1
return 1
return 0
# + 3 4 . 6 / 0 9 #0
$$ %i&. 3.#.' (i&03)#..c** $$ :ecursi9e (ibonacci (unction -include <iostream> usin& std''cout; usin& std''cin; usin& std''endl; unsi&ned lon& (ibonacci( unsi&ned lon& );
Outline
33
1. Function prototype 1.1 Initiali8e 4ariables 2. Input an integer 2.1 Call #unction (ibonacci 2.2 Output results. 3. "e#ine (ibonacci recursi4ely
## int main() #+ #3 #4 #. #6 #/ #0 #9 +0 " +# ++ $$ :ecursi9e de(inition o( (unction (ibonacci +3 unsi&ned lon& (ibonacci( unsi&ned lon& n ) +4 +. +6 +/ +0 i( ( n 11 0 NN n 11 # ) return n; else $$ recursi9e case $$ base case cout << 35nter an inte&er' 3; cin >> number; result 1 (ibonacci( number ); cout << 3%ibonacci(3 << number << 3) 1 3 << result << endl; return 0; unsi&ned lon& result4 number;
4nl) the &ase cases return values. All other cases call the (ibonacci $unction again.
return (ibonacci( n - # ) 2 (ibonacci( n - + ); +9 " 2000 Prentice Hall, Inc. All rights reserved.
5nter an inte&er' 0 %ibonacci(0) 1 0 5nter an inte&er' # %ibonacci(#) 1 # 5nter an inte&er' + %ibonacci(+) 1 # 5nter an inte&er' 3 %ibonacci(3) 1 + 5nter an inte&er' 4 %ibonacci(4) 1 3 5nter an inte&er' . %ibonacci(.) 1 . 5nter an inte&er' #0 %ibonacci(#0) 1 .. 5nter an inte&er' 6 %ibonacci(6) 1 0 5nter an inte&er' +0 %ibonacci(+0) 1 6/6. 5nter an inte&er' 30 %ibonacci(30) 1 03+040 5nter an inte&er' 3. %ibonacci(3.) 1 9++/46.
Outline
Program Output
35
3.1 @epetition
38
.er#ination
" Iteration2 loop condition $ails " @ecursion2 &ase case recogni<ed
1oth can have in$inite loops 1alance &et(een per$or#ance /iteration0 and good so$t(are engineering /recursion0
3;
# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4 +. +6 +/
$$ %i&. 3.#0' (i&03)#0.c** $$ %unctions that taMe no ar&uments -include <iostream> usin& std''cout; usin& std''endl; 9oid (unction#(); 9oid (unction+( 9oid ); int main() (unction#(); (unction+(); return 0; " 9oid (unction#() cout << 3(unction# taMes no ar&uments3 << endl; " 9oid (unction+( 9oid ) cout << 3(unction+ also taMes no ar&uments3 << endl; "
Outline
3?
Program Output
'0
" @educe $unction-call overhead " As+s the co#piler to cop) code into progra# instead o$ using a $unction call " Co#piler can ignore inline " Dhould &e used (ith s#all, o$ten-used $unctions
%7a#ple2
inline double cube( const double s ) return s ! s ! s; "
'1
# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4 +. +6 +/ +0 +9 30 3#
$$ %i&. 3.+0' (i&03)+0.c** $$ ,om*arin& call-by-9alue and call-by-re(erence $$ 6ith re(erences. -include <iostream> usin& std''cout; usin& std''endl; int squareIyGalue( int ); 9oid squareIy:e(erence( int P ); int main() int x 1 +4 8 1 4; cout << << << << 3x 1 3 << x << 3 be(ore squareIyGalueQn3 3Galue returned by squareIyGalue' 3 squareIyGalue( x ) << endl 3x 1 3 << x << 3 a(ter squareIyGalueQn3 << endl;
Outline
1. Function prototypes 1.1 Initiali8e 4ariables 2. Print x 2.1 Call #unction and print x 2.2 Print 8 2.3 Call #unction and print 8
'2
cout << 38 1 3 << 8 << 3 be(ore squareIy:e(erence3 << endl; squareIy:e(erence( 8 ); cout << 38 1 3 << 8 << 3 a(ter squareIy:e(erence3 << endl; return 0; " int squareIyGalue( int a )
return a !1 a;
32 33 9oid squareIy:e(erence( int Pc:e( ) 34 35 36 " x 1 + be(ore squareIyGalue Galue returned by squareIyGalue' 4 x 1 + a(ter squareIyGalue 8 1 4 be(ore squareIy:e(erence 8 1 #6 a(ter squareIy:e(erence c:e( !1 c:e(; $$ callerRs ar&ument modi(ied
Outline
'3
''
# + 3 4 . 6 / 0 9
$$ %i&. 3.+3' (i&03)+3.c** $$ Dsin& de(ault ar&uments -include <iostream> usin& std''cout; usin& std''endl; int boxGolume( int len&th 1 #4 int 6idth 1 #4 int hei&ht 1 # );
Outline
'3
1. Function prototype 2. Print de#ault 4olume 2.1 Print 4olume 5ith one parameter 2.2 Print 5ith 2 parameters 2.3 Print 5ith all parameters. 3. Function de#inition
#0 int main() ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ " +3 +4 $$ ,alculate the 9olume o( a box +. int boxGolume( int len&th4 int 6idth4 int hei&ht ) +6 +/ return len&th ! 6idth ! hei&ht; +0 " 2000 Prentice Hall, Inc. All rights reserved. return 0; cout << 3Bhe de(ault box 9olume is' 3 << boxGolume() << 3QnQnBhe 9olume o( a box 6ith len&th #04Qn3 << 36idth # and hei&ht # is' 3 << boxGolume( #0 ) << 3QnQnBhe 9olume o( a box 6ith len&th #04Qn3 << 36idth . and hei&ht # is' 3 << boxGolume( #04 . ) << 3QnQnBhe 9olume o( a box 6ith len&th #04Qn3 << 36idth . and hei&ht + is' 3 << boxGolume( #04 .4 + ) << endl;
Bhe de(ault box 9olume is' # Bhe 9olume o( a box 6ith len&th #04 6idth # and hei&ht # is' #0 Bhe 9olume o( a box 6ith len&th #04 6idth . and hei&ht # is' .0 Bhe 9olume o( a box 6ith len&th #04 6idth . and hei&ht + is' #00
Outline
Program Output
'5
3.1+ 2nary 1cope (esolution Operator Hnar) scope resolution operator /''0
" Access glo&al varia&les i$ a local varia&le has sa#e na#e " not needed i$ na#es are di$$erent " instead o$ 9ariable use ''9ariable
'8
# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3
$$ %i&. 3.+4' (i&03)+4.c** $$ Dsin& the unary sco*e resolution o*erator -include <iostream> usin& std''cout; usin& std''endl; -include <iomani*> usin& std''set*recision; const double JC 1 3.#4#.9+6.3.09/9; int main() const (loat JC 1 static)cast< (loat >( ''JC ); cout << set*recision( +0 ) << 3 Focal (loat 9alue o( JC 1 3 << JC << 3QnLlobal double 9alue o( JC 1 3 << ''JC << endl; return 0; "
Outline
1. "e#ine 4ariables 2. Print 4ariables
';
Program Output
'?
" Having $unctions (ith sa#e na#e and di$$erent para#eters " Dhould per$or# si#ilar tas+s / i.e., a $unction to s!uare ints, and $unction to s!uare (loats0.
int square( int x) return x ! x;" (loat square((loat x) return x ! x; "
# $$ %i&. 3.+.' (i&03)+..c** + $$ Dsin& o9erloaded (unctions 3 -include <iostream> 4 . usin& std''cout; 6 usin& std''endl; / 0 int square( int x ) 9 #0 double square( double y ) ## #+ int main() #3 #4 #. #6 #/ #0 #9 " return 0; cout << 3Bhe square o( inte&er / is 3 << square( / ) << 3QnBhe square o( double /.. is 3 << square( /.. ) << endl; return y ! y; " return x ! x; "
Outline
Functions have sa#e na#e &ut di$$erent para#eters 1. "e#ine o4erloaded #unction 2. Call #unction
30
Program Output
31
" Co#pact (a) to #a+e overloaded $unctions " >e)(ord tem*late " >e)(ord class or ty*ename &e$ore ever) $or#al t)pe para#eter /&uilt in or user de$ined0
tem*late < class B > $$ or tem*late< ty*ename B > B square( B 9alue# ) return 9alue# ! 9alue#; "