chapter 3 - functions.pptx

Upload: muhammad-abuzar-khan

Post on 26-Feb-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/25/2019 Chapter 3 - Functions.pptx

    1/73

    2000 Prentice Hall, Inc. All rights reserved.

    1

    Chapter 3 - Functions

    Outline

    3.1Introduction3.2Program Components in C++3.3Math Library Functions3.4Functions3.5Function Definitions3.6Function Prototypes

    3.7Header Files3.8Random Number Generation3.9Example: A Game of Chance and Introducingenum3.10Storage Classes3.11Scope Rules3.12Recursion3.13Example Using Recursion: The Fibonacci Series3.14Recursion vs. Iteration3.15Functions with Empty Parameter Lists

  • 7/25/2019 Chapter 3 - Functions.pptx

    2/73

    2000 Prentice Hall, Inc. All rights reserved.

    2

    Chapter 3 - Functions

    Outline

    3.16Inline Functions3.17References and Reference Parameters3.18Default Arguments3.19Unary Scope Resolution Operator3.20Function Overloading3.21Function Templates

  • 7/25/2019 Chapter 3 - Functions.pptx

    3/73

    2000 Prentice Hall, Inc. All rights reserved.

    3

    3.1 Introduction

    Divide and conuer Construct a progra! "ro! s!aller pieces or

    co!ponents

    #ach piece !ore !anagea$le than the original progra!

  • 7/25/2019 Chapter 3 - Functions.pptx

    4/73

    2000 Prentice Hall, Inc. All rights reserved.

    %

    3.2 Program Components in C++

    Progra!s &ritten $' co!$ining ne& "unctions &ith (prepac)aged*

    "unctions in the C++standard li$rar'.

    he standard li$rar' provides a rich collection

    o" "unctions. Inputoutput getline, read etc./

    Co!!on !athe!atical calculations po&, srt, ep,

    etc./

    tring !anipulationsstrcp', strcat, etc. an' !ore

  • 7/25/2019 Chapter 3 - Functions.pptx

    5/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.2 Program Components in C++

    Functions are invo)ed $' a "unction call

    A "unction call speci"ies the "unction na!e andprovides in"or!ation as argu!ents/ that the called

    "unction needs

    4oss to &or)er analog'5

    A boss (the calling function or caller) asks a worker(the called function) to perform a task and return

    (i.e., report back) the results when the task is done.

  • 7/25/2019 Chapter 3 - Functions.pptx

    6/73

    2000 Prentice Hall, Inc. All rights reserved.

    6

    3.2 Program Components in C++

    Function de"initions 7nl' &ritten once

    hese state!ents are hidden "ro! other "unctions.

    4oss to &or)er analog'5

    The boss does not know how the worker gets the jobdone; he just wants it done

  • 7/25/2019 Chapter 3 - Functions.pptx

    7/732000 Prentice Hall, Inc. All rights reserved.

    8

    3.3 Math Library Functions

    ath li$rar' "unctions Allo& the progra!!er to per"or! co!!on !athe!atical

    calculations

    Are used $' including the header "ile

    Functions called $' &ritingfunctionNameargument/

    #a!plecout

  • 7/25/2019 Chapter 3 - Functions.pptx

    8/732000 Prentice Hall, Inc. All rights reserved.

    9

    3.3 Math Library Functions

    Function argu!ents can $e Constants

    sqrt( 4 );

    :aria$les

    sqrt( x );

    #pressionssqrt( sqrt( x ) );

    sqrt( 3 - 6x );

  • 7/25/2019 Chapter 3 - Functions.pptx

    9/732000 Prentice Hall, Inc. All rights reserved.

    no&n onl' in the "unction in &hich the' are de"ined

    All varia$les declared in "unction de"initions are local

    varia$les

    Parameters ?ocal varia$les passed &hen the "unction is called that

    provide the "unction &ith outside in"or!ation

  • 7/25/2019 Chapter 3 - Functions.pptx

    10/732000 Prentice Hall, Inc. All rights reserved.

    10

    3.5 Function Definitions

    Create custo!i=ed "unctions to a)e in data

    Per"or! operations

    @eturn the result

    Format for function definition:

    return-value-type function-name parameter-list/

    declarations and statements

    B

    Example:int square( int y)

    return y ! y;

    "

  • 7/25/2019 Chapter 3 - Functions.pptx

    11/732000 Prentice Hall, Inc. All rights reserved.

    Outline11# $$ %i&. 3.3' i&0303.c**

    + $$ ,reatin& and usin& a *ro&rammer-deinedunction3 include4

    / intsquare( int); $$ unction *rototy*e9#0 intmain()## #+ or( intx #; x

  • 7/25/2019 Chapter 3 - Functions.pptx

    12/732000 Prentice Hall, Inc. All rights reserved.

    12

    3.6 Function Prototypes

    Function protot'pe Function name

    Parameters

    In"or!ation, the "unction ta)es in

    %eturntype

    'pe o" in"or!ation the "unction passes $ac) to caller de"ault int/ oidsigni"ies the "unction returns nothing

    7nl' needed i" "unction de"inition co!es a"ter the "unction

    call in the progra!

    #a!ple5int maximum( int5 int5 int );

    a)es in 3 ints

    @eturns an int

    Note that it is enou&h to mention

    'ust the data(typeof the input

    parameters in the function

    prototype

    int maximum( int x5 int y5 int );

    )owever! it is o* to mention the

    variable namesas well

  • 7/25/2019 Chapter 3 - Functions.pptx

    13/732000 Prentice Hall, Inc. All rights reserved.

    Outline13

    1. Function prototype(3 parameters)

    2. Input values

    2.1 Call function

    # $$ %i&. 3.4' i&0304.c**

    + $$ %indin& the maximum o three inte&ers

    3 include

    4 intmaximum( int5 int5 int); $$ unction*rototy*e

    6 intmain()

    / inta5 b5 c;

    9

    #0 cout

  • 7/25/2019 Chapter 3 - Functions.pptx

    14/732000 Prentice Hall, Inc. All rights reserved.

    Outline

    +/

    1%

    3.Function definition

    Program Output

    #9 $$ %unction maximum deinition

    +0 $$ x5 y and belo8 are *arameters to

    +# $$ the maximum unction deinition++ intmaximum( intx5 inty5 int )

    +3

    +4 intmax x;+

    +6 i( y > max )

    + max y;

    +9 i( > max )

    30 max ;3#

    3+ returnmax;

    33 "

    7nter three inte&ers' ++ / #

    aximum is' /

    7nter three inte&ers' 9+ 3 #4aximum is' 9+

    7nter three inte&ers' 4 #9 9/aximum is' 9/

    +nitially! maxis equal to x

    +f yis &reater than max!

    ybecomes the new maxnow

    Finally! if ,is &reater than max!

    ,becomes the new max

    1

  • 7/25/2019 Chapter 3 - Functions.pptx

    15/732000 Prentice Hall, Inc. All rights reserved.

    1

    3.7 Header Files

    Header "iles Contain "unction protot'pes "or li$rar' "unctions

    ?oad &ith include #a!ple5

    ,, etc.

    Custo! header "iles De"ined $' the progra!!er

    ave as ilename.h

    ?oaded into progra! using

    include 2ilename.h2

    16

  • 7/25/2019 Chapter 3 - Functions.pptx

    16/732000 Prentice Hall, Inc. All rights reserved.

    16

    3.8 Random Number Generation

    rand"unctioni rand();

    enerates a pseudorando! nu!$er $et&een0and :=usuall' 32868/

    A pseudorando! nu!$er is a preset seuence o" rando! nu!$ers

    he sa!e seuence is generated upon ever' progra! eecution

    ?oad srand"unction

    Eu!ps to a seeded location in a rando! seuence

    srand( seed );srand( time( 0 ) ); $$must include

    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 randto generate rando! nu!$ers

    18

  • 7/25/2019 Chapter 3 - Functions.pptx

    17/732000 Prentice Hall, Inc. All rights reserved.

    18

    3.8 Random Number Generation

    caling @educes rando! nu!$er to a certain range

    odulus ?/ operator @educes nu!$er $et&een 0 and:=to a nu!$er

    $et&een 0 and the scaling "actor

    #a!ple

    i rand() ? 6 1 #;

    enerates a nu!$er $et&een #and 6

    19# $$ %i 3 i 03 0

  • 7/25/2019 Chapter 3 - Functions.pptx

    18/732000 Prentice Hall, Inc. All rights reserved.

    Outline19

    1. Define loop

    2.Output randomnumber

    Program Output

    # $$ %i&. 3.' i&030.c**+ $$ @hited5 scaled inte&ers *roduced by # 1 rand()? 63 include

    4

    / include9

    #0 include

    ##

    #+ intmain()

    #3

    #4 or( inti #; i

  • 7/25/2019 Chapter 3 - Functions.pptx

    19/732000 Prentice Hall, Inc. All rights reserved.

    Outline10; i--) n n!i;

    returnn;

    "intmain()

    cout

  • 7/25/2019 Chapter 3 - Functions.pptx

    44/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.13Example Using Recursion: TheFibonacci Series

    Fi$onacci series5 0, 1, 1, 2, 3, , 9... #ach nu!$er su! o" t&o previous ones

    #a!ple o" a recursive "or!ula5

    ib(n) ib(n-#) 1 ib(n-+)

    C++ code "or ibonacci"unctionlon&ibonacci( lon&n )

    i( n 0 NN n # ) $$ base case

    returnn;

    elsereturnibonacci( n - # ) 1 ibonacci( n O + );

    "

    %

    313ExampleUsingRecursion:The

  • 7/25/2019 Chapter 3 - Functions.pptx

    45/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.13Example Using Recursion: TheFibonacci Series

    Diagra! o" Fi$onnaci "unction

    f( 3 )

    f( 1 )f( 2 )

    f( 1 ) f( 0 ) return 1

    return 1 return 0

    return +

    +return

    %6

    313ExampleUsingRecursion:The

  • 7/25/2019 Chapter 3 - Functions.pptx

    46/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.13Example Using Recursion: TheFibonacci Series

    Diagra! o" Fi$onnaci "unction

    f( 3 )

    f( 1 )f( 2 )

    f( 1 ) f( 0 ) return 1

    return 1 return 0

    return +

    +return

    Outline%8# $$ %i&. 3.#' i&03#.c**

    + $$ : i ib i ti

  • 7/25/2019 Chapter 3 - Functions.pptx

    47/73

    2000 Prentice Hall, Inc. All rights reserved.

    Outline+ $$ :ecursie ibonacci unction3 include

    4 unsi&ned lon& ibonacci( unsi&ned lon&); intmain()6

    unsi&ned lon&result5 number;/9 cout

  • 7/25/2019 Chapter 3 - Functions.pptx

    48/73

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    Program Output

    %ibonacci(0) 07nter an inte&er' #%ibonacci(#) #7nter an inte&er' +%ibonacci(+) #

    7nter an inte&er' 3%ibonacci(3) +

    7nter an inte&er' 4%ibonacci(4) 3

    7nter an inte&er' %ibonacci()

    7nter an inte&er' 6%ibonacci(6) /

    7nter an inte&er' #0%ibonacci(#0)

    7nter an inte&er' +0%ibonacci(+0) 667nter an inte&er' 30%ibonacci(30) /3+040

    7nter an inte&er' 3%ibonacci(3) 9++46

    %

  • 7/25/2019 Chapter 3 - Functions.pptx

    49/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.14Recursion vs. Iteration

    @epetition Iteration5 eplicit loop

    @ecursion5 repeated "unction calls

    er!ination Iteration5 loop condition "ails

    @ecursion5 $ase case recogni=ed

    4oth can have in"inite loops

    4alance $et&een per"or!ance iteration/ and good

    so"t&are engineering recursion/

    0

  • 7/25/2019 Chapter 3 - Functions.pptx

    50/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.15Functions with Empty Parameter Lists

    #!pt' para!eter lists #ither &riting oidor leaving a para!eter list e!pt'

    indicates that the "unction ta)es no argu!ents

    oid *rint();

    or

    oid *rint( oid ); Function*rintta)es no argu!ents and returns no value

    Outline1$$ %unctions that taPe no ar&uments

  • 7/25/2019 Chapter 3 - Functions.pptx

    51/73

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. Function prototypes(take noarguments)

    2. Call the functions

    3.Function definitions

    Program Output

    include

    oidunction#();

    oidunction+( oid);

    intmain()

    unction#();

    unction+();

    return0;

    "

    oidunction#()

    cout

  • 7/25/2019 Chapter 3 - Functions.pptx

    52/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.16Inline Functions

    inline"unctions @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 hould $e used &ith s!all, o"ten-used "unctions

    #a!ple 15inline double cube( const double s )

    return s ! s ! s; "

    #a!ple 2inline int max(int a5 int b)

    return (a > b) H a ' b;

    "

    3

  • 7/25/2019 Chapter 3 - Functions.pptx

    53/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.17References and Reference Parameters

    Call $' value

    Cop' o" data passed to "unction Changes to cop' do not change original

    sed to prevent un&anted side e""ects

    Call $' re"erence Function can directl' access data

    Changes a""ect original

    @e"erence para!eter alias "or argu!ent Qis used to signi"' a re"erence

    oid chan&e( int Qariable )

    ariable 1 3; " Adds 3 to the varia$le inputted

    int Qy x.

    A change to y&ill no& a""ect xas &ell

  • 7/25/2019 Chapter 3 - Functions.pptx

    54/73

    2000 Prentice Hall, Inc. All rights reserved.

    Using a Reference Parameter

    +s li*e &ivin& someone the *ey

    to your home

    The *ey can be used by the

    other person to chan&e the

    contents of your homeC

    Dain Pro&ram Demory

  • 7/25/2019 Chapter 3 - Functions.pptx

    55/73

    2000 Prentice Hall, Inc. All rights reserved.

    Dain Pro&ram Demory

    25

    4000

    age

    If you pass a copyof ageto a function, it is called

    pass-by-alue!and t"e function #ill not be able

    to c"ange t"e contents of age in t"e calling

    bloc$% it is still 25 #"en you &etu&n

    '(), if you pass 4000, t"e add&ess of age to a

    function, it is called pass-by-&efe&enceand t"efunction #ill be able to c"ange t"e contents of

    age in t"e calling bloc$% it could be 23 o& 90 #"en

    you &etu&n

  • 7/25/2019 Chapter 3 - Functions.pptx

    56/73

    2000 Prentice Hall, Inc. All rights reserved.

    Additional Terms

    Pass(by(reference

    is also called - - -pass-$'-address, or

    pass-$'-location

    +an you eplain why-

  • 7/25/2019 Chapter 3 - Functions.pptx

    57/73

    2000 Prentice Hall, Inc. All rights reserved.

    Pass-by-value

    *+I.'/*

    (*)I/

    *+

    incoing!

    alue of

    a&guent

  • 7/25/2019 Chapter 3 - Functions.pptx

    58/73

    2000 Prentice Hall, Inc. All rights reserved.

    Pass-by-reference

    *+I.'/* (*)I/

    *+

    incoing!

    o&iginal alue of

    a&guent

    outgoing!

    c"anged alue of

    a&guent/,

  • 7/25/2019 Chapter 3 - Functions.pptx

    59/73

    2000 Prentice Hall, Inc. All rights reserved.

    Pass-by-reference

    *+I.'/* (*)I/

    *+

    / a&guent

    "as no alue yet

    #"en call occu&s

    outgoing!

    ne# alue of

    a&guent

    Outline60$$ ,om*arin& call-by-alue and call-by-reerence

    $$ ith

    Lotice the use o" theQ operator

  • 7/25/2019 Chapter 3 - Functions.pptx

    60/73

    2000 Prentice Hall, Inc. All rights reserved.

    1. Function prototypes

    1.1 Initialize variables

    2. Printx

    2.1 Call function andprintx

    2.2 Print

    2.3 Call function andprint

    3. Function Definition of

    squareJyGalue

    $$ 8ith reerences.

    include

    intsquareJyGalue( int);

    oidsquareJy:eerence( intQ );

    intmain()

    intx +5 4;

    cout

  • 7/25/2019 Chapter 3 - Functions.pptx

    61/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.1 Function Definition ofsquareJy:eerence

    Program Outputx + beore squareJyGalueGalue returned by squareJyGalue' 4x + ater squareJyGalue 4 beore squareJy:eerence #6 ater squareJy:eerence

    c:e ! c:e; $$ callerSs ar&ument modiied"

    Outline

  • 7/25/2019 Chapter 3 - Functions.pptx

    62/73

    2000 Prentice Hall, Inc. All rights reserved.

    Example of Pass-by-Reference

    Ge want to find " real roots for aquadratic equation with coefficients

    a!b!c- Grite a prototype for a void

    function named Het%oots./ with parameters

    are type float- The last " are

    reference parameters of type float-

    Outline

  • 7/25/2019 Chapter 3 - Functions.pptx

    63/73

    2000 Prentice Hall, Inc. All rights reserved.

    void GetRoots(float, float, float,

    float&, float&);

    Now write the function definition usin& this information

    This function uses > incomin& values a! b! c from the

    callin& bloc*- +t calculates " out&oin& values root

    and root" for the callin& bloc*- They are the " real

    roots of the quadratic equation with coefficients a! b!

    c-

    &ototype

    Outline

  • 7/25/2019 Chapter 3 - Functions.pptx

    64/73

    2000 Prentice Hall, Inc. All rights reserved.

    void GetRoots(float a, float b, float c,

    float& root1, float& root2)

    {

    float temp; // Local variable

    temp = b * b - 4.0 * a * c;

    root1 =(-b + sqrt(temp)) /(2.0 * a);

    root2 =(-b - sqrt(temp)) /(2.0 * a);

    return;

    }

    Function Iefinition

    64

    6

    318DefaultArguments

  • 7/25/2019 Chapter 3 - Functions.pptx

    65/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.18Default Arguments

    I" "unction para!eter o!itted, gets de"ault

    value Can $e constants, glo$al varia$les, or "unction calls

    I" not enough para!eters speci"ied, right!ost go to

    their de"aults et de"aults in "unction protot'pe

    int deault%unction( int x #5

    int y +5 int 3 );

    Outline66$$ %i&. 3.+3' i&03+3.c**

    $$ Dsin& deault ar&uments

  • 7/25/2019 Chapter 3 - Functions.pptx

    66/73

    2000 Prentice Hall, Inc. All rights reserved.

    +0

    1. Function prototype

    2. Print default volume

    2.1 Print volume withone parameter

    2.2 Print with 2parameters

    2.3 Print with allparameters.

    3. Function definition

    include

    intboxGolume(intlen&th#5int8idth#5inthei&ht#);intmain()

    cout

  • 7/25/2019 Chapter 3 - Functions.pptx

    67/73

    2000 Prentice Hall, Inc. All rights reserved.

    Program Output

    Bhe deault box olume is' #Bhe olume o a box 8ith len&th #058idth # and hei&ht # is' #0Bhe olume o a box 8ith len&th #058idth and hei&ht # is' 0Bhe olume o a box 8ith len&th #058idth and hei&ht + is' #00

    Lotice ho& the right!ost

    values are de"aulted.

    69

    320FunctionOverloading

  • 7/25/2019 Chapter 3 - Functions.pptx

    68/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.20Function Overloading

    Function overloading

    Having "unctions &ith sa!e na!e and di""erent para!eters hould per"or! si!ilar tas)s i.e., a "unction to suare

    ints, and "unction to suare loats/.

    int square( int x) return x ! x;"

    loat square(loat x) return x ! x; " Progra! chooses "unction $' signature

    signature deter!ined $' "unction na!e and para!eter t'pes

    Can have the sa!e return t'pes

    Outline6

  • 7/25/2019 Chapter 3 - Functions.pptx

    69/73

    2000 Prentice Hall, Inc. All rights reserved.

    1. Define overloadedfunction

    2. Call function

    Program Output

    3 include

    4

    usin&std''cout;

    6 usin&std''endl;

    / intsquare( intx ) returnx ! x; "

    9

    #0 doublesquare( doubley ) returny ! y; "

    ##

    #+ intmain()

    #3

    #4 cout

  • 7/25/2019 Chapter 3 - Functions.pptx

    70/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.19Unary Scope Resolution Operator

    nar' scope resolution operator ''/ 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" ariableuse ''ariable

    Outline81

    $$ %i&. 3.+4' i&03+4.c**

  • 7/25/2019 Chapter 3 - Functions.pptx

    71/73

    2000 Prentice Hall, Inc. All rights reserved.

    1. Define variables

    2. Print variables

    Program Output

    $$ Dsin& the unary sco*e resolution o*erator

    include

    include

    const doubleKC 3.#4#9+63/99;

    intmain()

    const loatKC staticcast< loat>( ''KC );

    cout

  • 7/25/2019 Chapter 3 - Functions.pptx

    72/73

    2000 Prentice Hall, Inc. All rights reserved.

    3.21Function Templates

    Function te!plates

    Co!pact &a' to !a)e overloaded "unctions >e'&ord tem*late >e'&ord classor ty*ename$e"ore ever' "or!al t'pe

    para!eter $uilt in or user de"ined/

    tem*late < class B >

    $$ or tem*late< ty*ename B >B square( B alue# )

    return alue# ! alue#;

    " Breplaced $' t'pe para!eter in "unction call.

    int x;

    int y square(x); I" int, all BNs $eco!e ints

    Can use loat, double, lon&...

  • 7/25/2019 Chapter 3 - Functions.pptx

    73/73

    // function template

    #include templateclassT;

    T HetDax .T a! T b/ ?

    T result

    result = .a;b/J a : b

    return.result/

    A

    intmain ./ ?

    inti =

    n = HetDax long;.l ! m/

    cout * endl

    dl