cs31-3

Upload: manuel-sosaeta

Post on 14-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 CS31-3

    1/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-1

    CS 31:

    Introduction toComputer Science I

    Topic 3

    Functions

  • 7/30/2019 CS31-3

    2/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-2

    Functions

    Function Definition

    A function is a single unit of computation

    Other words for function

    Procedure

    Method Subprogram (that returns a value)

  • 7/30/2019 CS31-3

    3/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-3

    Functions

    Function Characterization

    Accomplishes one thing

    May use other functions

    May produce a result

    Sequence of statements

  • 7/30/2019 CS31-3

    4/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-4

    Functions

    Function Inputs

    Called arguments or actual parameters

    Provides values for calculation

    Not needed by all functions

    Display text

    Generate random number

  • 7/30/2019 CS31-3

    5/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-5

    Functions

    Function Outputs

    Called the return value

    Reports the results of the processing

    Not produced by all functions

    Functions that perform an action only

  • 7/30/2019 CS31-3

    6/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-6

    Functions

    Function Processing

    Apply defined algorithm

    Use inputs

    Generate outputs

  • 7/30/2019 CS31-3

    7/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-7

    Functions

    Function Example

    Square Root

    Input: Value: 9

    Processing: Calculate square root

    Output: Square root of value: 3

  • 7/30/2019 CS31-3

    8/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-8

    Functions

    Two Function Dichotomies

    Function definition dichotomy

    Predefined functions

    Programmer-written functions

    Function return value dichotomy

    void

    Typed (int, float, double, char, bool, etc.)

  • 7/30/2019 CS31-3

    9/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-9

    Functions

    Function Definition Types

    Predefined functions

    Function library

    Commercial product

    Other programmers

    Programmer defined functions Written by programmer

  • 7/30/2019 CS31-3

    10/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-10

    Functions

    Function Return Value Types

    Functions that return a value (typed)

    Perform a calculation (e.g. Square root)

    Deliver (return) the result

    Functions that do not return a value (void)

    Perform an action (e.g. set an output format)

    Do not have a result to return

  • 7/30/2019 CS31-3

    11/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-11

    Functions

    C++ Predefined Functions

    Provided by the compiler

    Organized in libraries

    Referenced by #include statements

    Included in program using #include

  • 7/30/2019 CS31-3

    12/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-12

    Functions

    Some Predefined Libraries

    iostream Stream input and output

    cmath Mathematical functions

    cstdlib Some standard functions

    cctype Character operations

    string String capabilities

  • 7/30/2019 CS31-3

    13/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-13

    Functions

    Some Predefined Functions

    Library iostream (#include )

    cin Stream input

    cout Stream output

    precision Stream precision

    width Stream width setf Stream formatting

  • 7/30/2019 CS31-3

    14/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-14

    Functions

    Some Predefined Functions

    Library cmath (#include )

    double sqrt(double) Square root

    double exp(double) Exponential (ex)

    double sin(double) Trigonometric sine

    double log(double) Natural logarithm (ln) double floor(double) Floor

  • 7/30/2019 CS31-3

    15/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-15

    Functions

    Some Predefined Functions

    Library cstdlib (#include )

    int abs(int) Absolute value

    int rand() Random number

    void srand(unsigned int) Seed random number

    void exit(int) Exit program

  • 7/30/2019 CS31-3

    16/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-16

    Functions

    Some Predefined Functions

    Library cctype (#include )

    bool isdigit(char) Digit

    bool isupper(char) Upper case

    bool isspace (char) White space

    bool ispunct(char) Punctuation int toupper(char) To upper case

  • 7/30/2019 CS31-3

    17/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-17

    Functions

    Some Predefined Functions

    Library string (#include )

    String declaration (with/without initialization)

    String assignment

    String input and output

    String character selection Substring

  • 7/30/2019 CS31-3

    18/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-18

    Functions

    Function Call

    Invokes the use of a function

    Specifies input arguments

    Return result value, if any

    void function: No return value

    Typed function: Return value

    Exactly one value

    Value is function type

  • 7/30/2019 CS31-3

    19/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved

    JAR 3-19

    Functions

    Function Call Syntax

    name(arg1, arg2, arg3, . . . argn);

    variable = name(arg1, arg2, arg3, . . . argn);

    name: Function name

    argi: Argument i

    variable: Place to put function value

    (if any)

  • 7/30/2019 CS31-3

    20/97

    CS 31: Introduction To CS ITopic 3: Functions9/2010 John A. RohrAll Rights Reserved

    JAR 3-20

    Functions

    Function Calls

    void function: No value is returned

    typed function: One value is returned Cannot be no value

    Cannot be more than one value

    Must be exactly one value

  • 7/30/2019 CS31-3

    21/97

    CS 31: Introduction To CS ITopic 3: Functions9/2010 John A. RohrAll Rights Reserved

    JAR 3-21

    Functions

    Type Conversion

    Input arguments: For literals only

    Will be converted if necessary and possible

    Return values

    Always returned as function type

    May be converted by an assignmentstatement after return

  • 7/30/2019 CS31-3

    22/97

    CS 31: Introduction To CS ITopic 3: Functions9/2010 John A. RohrAll Rights Reserved

    JAR 3-22

    Functions

    Function Example

    root = sqrt(value);

    Function name: sqrt

    Library location: cmath

    Function action: Square root

    Argument: value (e.g. 25) Output: Square root of value (e.g.5)

  • 7/30/2019 CS31-3

    23/97

    CS 31: Introduction To CS ITopic 3: Functions9/2010 John A. RohrAll Rights Reserved JAR 3-23

    Functions

    Literal Argument

    root = sqrt(64);

    Argument is an integer

    Parameter is a double

    Automatic upconversion of literal value

    from integer to double

  • 7/30/2019 CS31-3

    24/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-24

    Functions

    Variable Argument

    double value = 64;

    root = sqrt(value);Argument is a double

    Argument must match type

    No conversion

  • 7/30/2019 CS31-3

    25/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-25

    Functions

    Function Use#include

    #include using namespace std;

    int main()

    {

    double value;

    double root;

  • 7/30/2019 CS31-3

    26/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-26

    Functions

    Function Usecout > value;root = sqrt(value);

    cout

  • 7/30/2019 CS31-3

    27/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-27

    Functions

    Function Execution

    Enter a value:5.76

    The square root of "5.76" is "2.4"

  • 7/30/2019 CS31-3

    28/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-28

    Functions

    Exit Function

    exit(integer);

    Useful for stopping program early on error Takes integer value for identification

    0 for special exit without error

    1 or other for error exit In library cstdlib

  • 7/30/2019 CS31-3

    29/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-29

    Functions

    Exit Use

    #include

    using namespace std;int main()

    {

    exit(0);}

  • 7/30/2019 CS31-3

    30/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-30

    Functions

    Time Function

    now = time(0);

    Returns current time Seconds since January 1, 1970

    Useful to obtain a random number

    In library ctime

  • 7/30/2019 CS31-3

    31/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-31

    Functions

    Time Use#include

    #include using namespace std;int main(){

    cout

  • 7/30/2019 CS31-3

    32/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-32

    Functions

    Random Number Generation

    Sequence of pseudorandom numbers

    Not completely random Generated by algorithm

    Initialized by an integer seed number

    Will repeat same sequence for same seed

    Use random seed for random sequence

  • 7/30/2019 CS31-3

    33/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-33

    Functions

    Random Number Function

    rand();

    Does not take any argument Generates a pseudorandom number

    Value is between 0 and RAND_MAX (>=32,767)

    Can be scaled for other ranges Function and RAND_MAX in library cstdlib

  • 7/30/2019 CS31-3

    34/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-34

    Functions

    Random Number Use#include

    #include using namespace std;int main(){

    cout

  • 7/30/2019 CS31-3

    35/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-35

    Functions

    Random Number Scaling

    rand() value is between 0 and RAND_MAX

    Value can be scaled to any range

    Select number of values using modulus

    Shift range by addition

    Scale by multiplication

  • 7/30/2019 CS31-3

    36/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-36

    Functions

    Scaling Example

    Find result of throwing two dice

    Minimum value is 2

    Maximum value is 12

    count = (rand() % 11) + 2;

  • 7/30/2019 CS31-3

    37/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-37

    Functions

    Another Scaling Example

    Find a probability

    Minimum value is 0

    Maximum value is 1.0

    count = (RAND_MAX - rand()) /

    (RAND_MAX * 1.0);

  • 7/30/2019 CS31-3

    38/97

    CS 31: Introduction To CS ITopic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-38

    Functions

    Seeded Random Numbers

    srand(seed);

    Initializes random number generator

    Used unsigned integer for seed

    Generate same sequence for same seed

    Generate different numbers

    with different seed

  • 7/30/2019 CS31-3

    39/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-39

    Functions

    Seeded Random Numbers

    #include

    #include #include using namespace std;int main(){

    srand(time(0));cout

  • 7/30/2019 CS31-3

    40/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-40

    C++ Strings

    string Library

    #include

    Provides C++ strings

    Not part of language itself

    Cannot be used without #include

    One of many extensions to the language

  • 7/30/2019 CS31-3

    41/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. RohrAll Rights Reserved JAR 3-41

    C++ Strings

    C++ String Declaration

    string st1;

    string st2 = "Initial string"; String is initialized to empty string by default

    String can be initialized with declaration

    Characters are numbered beginning with 0

  • 7/30/2019 CS31-3

    42/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-42

    C++ Strings

    C++ String Length

    string st = "Example text";

    st.length() or st.size() (Integer 12) Length of the string

    Function with no parameters

    Return value is integer

    Syntax uses string name followed by period

  • 7/30/2019 CS31-3

    43/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-43

    C++ Strings

    C++ String Access

    string st = "Example text";

    st[3] (Character m) One character of the string

    Position can be any integer expression

    Must not access past last character

    Syntax uses position in square brackets

  • 7/30/2019 CS31-3

    44/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-44

    C++ Strings

    Alternate C++ String Access

    string st = "Example text";

    st[3] (Character m) st.at(3) (Character m)

    Both access one character

    atchecks for beyond end of string

    atthrows an exception on error

  • 7/30/2019 CS31-3

    45/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-45

    C++ Strings

    C++ Substring

    string st = "Example text";

    st.substr(8) (String "text") Part of the string

    Position can be any integer expression

    Must not begin past last character

    Result is string from position specified

  • 7/30/2019 CS31-3

    46/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-46

    C++ Strings

    C++ Substring

    string st = "Example text";

    st.substr(2, 5) (String "ample") Part of the string

    Start can be any integer expression

    Length can be any integer expression Must not extend past last character

    Result string from position with length given

  • 7/30/2019 CS31-3

    47/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-47

    C++ Strings

    C++ String Comparison

    Strings can be compared like numbers

    Operators are ==, !=, >, =, and

  • 7/30/2019 CS31-3

    48/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-48

    C++ Strings

    C++ String Comparison

    Comparisons are character by character

    First differing character determines result Comparisons also depend on length

    Longer string is greater than shorter string

    if identical up to the end of the shorter

  • 7/30/2019 CS31-3

    49/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-49

    C++ Strings

    C++ String Comparison

    string st1 = "On";

    string st2 = "Once"; string st3 = "Once more";

    st1 == st2 is false

    st1 == st2.substr(0,2) is true

    st2 != st3 is true

  • 7/30/2019 CS31-3

    50/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-50

    C++ Strings

    C++ String Comparison

    string st1 = "On";

    string st2 = "Once"; string st3 = "Once more";

    st2 < st3 is true

    st2 >= st3.substr(0,4) is true

    st1 > st3 is false

  • 7/30/2019 CS31-3

    51/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-51

    C++ Strings

    C++ String Concatenation

    string st1 = "One string";

    string st2 = " extended"; st1 + st2 ("One string extended")

    First string followed by second

    No characters inserted between

    Plus sign (+) defined by #include

  • 7/30/2019 CS31-3

    52/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-52

    C++ Strings

    C++ String Insertion

    string st1 = "One string";

    string st2 = " more"; string st3, st4;

    st3 = st1.insert(3, st2); ("One more string")

    st4 = st1.insert(3, st2, 1, 2 ) ("Onemo string")

  • 7/30/2019 CS31-3

    53/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-53

    C++ Strings

    C++ String Removal

    string st1 = "One string";

    string st2 = "op"; string st3, st4, st5;

    st2 = st1.erase(3); ("One")

    st3 = st1.erase(0, 6); ("ring")

  • 7/30/2019 CS31-3

    54/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-54

    C++ Strings

    C++ String Replacement

    string st1 = "One string";

    string st2 = "person"; string st3 = "weather";

    string st4, st5;

    st4 = st1.replace(4, 6, st2); ("One person")

    st5 = st1.replace(0, 7, st3, 3, 2); ("thing")

  • 7/30/2019 CS31-3

    55/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-55

    C++ Strings

    C++ String Find

    string st = "One string";

    st.find("in", 0) is 7 st.find("in", 5) is 7

    st.find(' ', 0) is 3

    st.find(' ', 5) is string::npos Returns string::npos if no find

    (Constant defined in the string library)

  • 7/30/2019 CS31-3

    56/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-56

    C++ Strings

    Digit Value

    Characters are represented by integers

    The code is defined by the hardware Several code standards are used

    Each character has a different code

  • 7/30/2019 CS31-3

    57/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-57

    C++ Strings

    ASCII Digit Value

    ASCII: American Standard Code for

    Information Interchange Most common character code

    Uses first 32 values for control characters

    e.g. Tab, Backspace, Return Digits begin at 48, NOT 0

  • 7/30/2019 CS31-3

    58/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-58

    C++ Strings

    ASCII Digit Value Digit values range from 48 to 57

    Never need to use numeric values'0' = 48 '5' = 53

    '1' = 49 '6' = 54

    '2' = 50 '7' = 55

    '3' = 51 '8' = 56

    '4' = 52 '9' = 57

  • 7/30/2019 CS31-3

    59/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-59

    C++ Strings

    ASCII Digit Value

    Subtract digit 0 value from digit character

    char digit = '3'; int number;

    number = digit - '0';

    Numerical value ofdigit is 51

    Numerical value ofnumber is 3

  • 7/30/2019 CS31-3

    60/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-60

    Functions

    Programmer-Defined Functions

    Custom functions for specific uses

    Can be used to provide needed capability Can be used to modularize programs

    Limit size of each module

    Organize in hierarchy of modules

  • 7/30/2019 CS31-3

    61/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-61

    Functions

    Programmer-Defined Functions

    Three required items

    Function prototype (declaration) Function definition (code)

    Function call (use)

  • 7/30/2019 CS31-3

    62/97

    CS 31: Introduction To CS I

    Topic 3: Functions9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-62

    Functions

    Function Return Value None if void

    Any valid type if typed int float

    double

    bool char

    string

  • 7/30/2019 CS31-3

    63/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-63

    Functions

    Function Name

    Valid C++ identifier

    Uniquely identifies function Should indicate the action of the function

    Used to call the function

  • 7/30/2019 CS31-3

    64/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-64

    Functions

    Function Parameters

    Called parameters or formal parameters

    Are placeholders for arguments of calls Specify the type & number of parameters

    Specify the name of each parameter

    Name not required in prototype

    Should be included for completeness

    Are required in the function header

  • 7/30/2019 CS31-3

    65/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-65

    Functions

    Prototype Example

    void aFunction(int p1, float p2, char p3);

    Return type (None) Name (aFunction)

    Parameters p1 (Integer)

    p2 (Float) p3 (Character)

    Note required semicolon at end!

  • 7/30/2019 CS31-3

    66/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-66

    Functions

    Prototype Example

    int anotherFunction(double value);

    Return type (Integer) Name (anotherFunction)

    Parameter value (Double)

    Note required semicolon at end!

  • 7/30/2019 CS31-3

    67/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-67

    Functions

    Function Call

    Same as for predefined functions

    Function nameArguments

    Must match the number of prototype parameters

    Must match the types prototype parameters

    Must be in the correct order

    Exception: Automatic upconversion

  • 7/30/2019 CS31-3

    68/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-68

    Functions

    Function Call Examples aFunction (3, 80.24, 'J');

    int x;

    x = anotherFunction(816.42);

  • 7/30/2019 CS31-3

    69/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-69

    Functions

    Function Definition Not required for predefined functions

    Provided by #include statement Consists of two separate parts

    Function header

    Function body

  • 7/30/2019 CS31-3

    70/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-70

    Functions

    Function Header Same format as prototype

    Specifies type, name, and parameters Does not have terminating semicolon

    Must have names for parameters

  • 7/30/2019 CS31-3

    71/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-71

    Functions

    Function Body Defines the action of the function

    Can include declarations Must include statements

    No return statement if void

    Must return value if not void Value must match type of function Value is returned with a return statement

  • 7/30/2019 CS31-3

    72/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-72

    Functions

    Function Definition Example#include

    using namespace std;void aFunction(int p1, float p2, char p3){

    cout

  • 7/30/2019 CS31-3

    73/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-73

    Functions

    Function Definition Exampleint anotherFunction(double value){

    int result;if (value >= 0)

    result = 0;else

    result = 1;return result;

    }

  • 7/30/2019 CS31-3

    74/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-74

    Functions

    Function Return Void functions

    Return statement is optional

    If used, return cannot return any value

    Will return at final close brace if no return

    Typed functions

    Return statement is required

    Must return value of function type

  • 7/30/2019 CS31-3

    75/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-75

    Functions

    Functions Calling Functions Statements in function definitions can be

    any valid C++ statements A function call from within a function is valid

    Every C++ program is a function (main)

    Therefore all C++ function calls are actuallyinside other functions

  • 7/30/2019 CS31-3

    76/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-76

    Functions

    Preconditions Specify conditions which must be true

    when a function is called Guarantee correct results if all true

    Result not guaranteed if not all true

    Provide limits for arguments Use assert() to check (in cassert library)

  • 7/30/2019 CS31-3

    77/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-77

    Functions

    Postconditions Describes the value returned by a function

    Valid only if all preconditions are true

  • 7/30/2019 CS31-3

    78/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-78

    Functions

    Pre/postcondition Example For square root function

    PreconditionArgument is a real number >= 0

    Postcondition

    Result will be the square root of the argument

    F i

  • 7/30/2019 CS31-3

    79/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-79

    Functions

    Pre/postcondition Example For sin function (in cmath)

    PreconditionArgument is a real number in radians

    Postcondition

    Result will be the sine of the angle Result will be be in the range -1.0 to +1.0

    F ti

  • 7/30/2019 CS31-3

    80/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-80

    Functions

    Scope Rules Define the valid range of a variable

    Minimize variable name conflicts Provide for global variables

    Provide for local variables

    F ti

  • 7/30/2019 CS31-3

    81/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-81

    Functions

    Local Variables Define within a function

    Exist between opening and closing braces Do not exist outside the function except

    Static variables are preserved call to call

    Cannot conflict with local variables in otherfunctions, even if the name is the same

    F ti

  • 7/30/2019 CS31-3

    82/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-82

    Functions

    Global Variables Exist for an entire program

    Defined before the first function Good use is for global constants

    Use of global variables should be limited

    Use function parameters to pass data

    Use function returns to return data

    F ti

  • 7/30/2019 CS31-3

    83/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-83

    Functions

    Blocks Define scopes for variables

    Delimited by open and close brace Variables defined in block are local to the

    block in which they are defined

    Block may be an entire function

    F ti

  • 7/30/2019 CS31-3

    84/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-84

    Functions

    Nested Blocks Blocks defined inside other blocks

    Resolves variables names Based on static structure

    Variable name redefined

    New instance valid within new block

    Old instance revived when the new block ends

    F ti

  • 7/30/2019 CS31-3

    85/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-85

    Functions

    Nested Block Example{

    int var = 5;

    {

    float var = 2.4;

    cout

  • 7/30/2019 CS31-3

    86/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-86

    Functions

    For Loop Variables for (int index = 0; index < 10; index++)

    Variable can be declared in forstatement Better practice to declare at beginning

    Defined in scope offorstatement only

    Some older compilers may not follow rule May allow variable to exist after loop ends

    M th ti l I d ti

  • 7/30/2019 CS31-3

    87/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-87

    Mathematical Induction

    Concept Mathematical induction is a method that

    can be used to prove numerical formulas. A proof requires two parts:

    Show the formula is true for an initial value;

    Show that if the formula is true for somevalue, then it is also true for the next value.

    M th ti l I d ti

  • 7/30/2019 CS31-3

    88/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-88

    Mathematical Induction

    ExampleThe formula for the sum of the positive

    integers from 1 to n is as follows:

    Si= n * (n + 1) / 2i = 1

    n

    M th ti l I d ti

  • 7/30/2019 CS31-3

    89/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-89

    Mathematical Induction

    ProofStep 1: Show that the sum of the integers

    from 1 to 1 is 1: Si = 1.Proof: S i = 1 * (1 + 1) / 2

    = 1 * 2 / 2

    = 1 which is true.

    i = 1

    1

    i = 1

    1

    M th ti l I d ti

  • 7/30/2019 CS31-3

    90/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-90

    Mathematical Induction

    ProofStep 2: Show that if the sum of the integers from 1 to m

    is m * (m + 1) / 2 then the sum of the integers

    from m to m+1 is (m + 1) * (m + 2) / 2.

    Proof: Si= 1 * (1 + 1) / 2= S i + (m + 1)= m * (m + 1) / 2 + (m + 1)= (m2 + m) / 2 + 2m / 2 + 2 / 2

    = (m2 + 3m + 2)/2 = (m+1)*(m+2)

    i = 1

    m+1

    i = 1

    m

    Rec rsion

  • 7/30/2019 CS31-3

    91/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-91

    Recursion

    Concept Recursion is a method where an algorithm

    is defined in terms of itself. There must be two cases in the algorithm:

    A base case that does not use the algorithm;

    A recursive case that uses the algorithm.

    Recursion

  • 7/30/2019 CS31-3

    92/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-92

    Recursion

    ExampleThe formula for the product of the positive

    integers from 1 to n is as follows:

    pi = 1 for n = 0;= n *

    pfor n > 0

    i = 1

    n

    i = 1

    n-1

    Recursion

  • 7/30/2019 CS31-3

    93/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-93

    Recursion

    Recursive Factorial Functiondouble factor(double num)

    { if (num == 0)

    return 1;

    elsereturn factor (n 1);

    }

    Recursion

  • 7/30/2019 CS31-3

    94/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-94

    Recursion

    Recursion vs.Iteration Recursion

    Function calls itself Must have base case

    Must be supported by the language used

    Iteration

    Function does not call itself

    Computation is based on a loop

    Does not require any special language support

    Recursion

  • 7/30/2019 CS31-3

    95/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-95

    Recursion

    Recursion vs.Iteration Recursion

    More elegant Less efficient

    Not practical for production use

    Iteration

    More common

    More efficient

    Usually used instead of recursion

    Recursion

  • 7/30/2019 CS31-3

    96/97

    CS 31: Introduction To CS I

    Topic 3: Functions

    9/2010 John A. Rohr

    All Rights Reserved

    JAR 3-96

    Recursion

    Iterative Factorial Functiondouble factor(double num)

    { double fact;

    for (fact = 1.0; num > 0.0; num -= 1.0)

    fact *= num;return fact;

    }

    UPDATES

  • 7/30/2019 CS31-3

    97/97

    UPDATES

    More Examples