# Function

Document Sample

```					Function
Function

Introduction
Library function
New defined function
Random number generator
Scope
Inline function
Introduction

Why do we need function?
Reuse and simplify a large program.
Chapter 7 and Chapter 8 (p309-p436)
Library                function
1 // using library function.
2  #include <iostream>
3  #include <iomanip>
4
5  using namespace std;;
6
7 int main()
8 {
9    cout << setw(4) <<123 << endl;
10
11    return 0; // indicates successful termination
12
13 } // end main
14
123
 Functions called by writing
 setw (4);
 4 can be replaced by
 Constants:   setw( 5<<);
10  cout setw(5) <<123 << endl;
 Variables:
 X=4; x=4;
9    int
 setw(x); setw(x) <<123 << endl;
10     cout <<
 Expressions:
 X=2;
9   int x=2;
 setw( 6-x ); <<123 << endl;
10    cout << setw(6-x)
Math library function
Perform common mathematical calculations
Example
cout << sqrt( 900.0 );
sqrt (square root) function
The preceding statement would print 30
Method             Description                      Example
ceil( x )          rounds x to the smallest integer ceil( 9.2 ) is 10.0
not less than x                  ceil( -9.8 ) is -9.0
cos( x )           trigonometric cosine of x        cos( 0.0 ) is 1.0
exp( x )           exponential function ex          exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( x )          absolute value of x              fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( x )         rounds x to the largest integer  floor( 9.2 ) is 9.0
not greater than x               floor( -9.8 ) is -10.0
fmod( x, y )       remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992
point number
log( x )           natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( x )         logarithm of x (base 10)         log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
pow( x, y )        x raised to power y (xy)         pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( x )           trigonometric sine of x          sin( 0.0 ) is 0
sqrt( x )          square root of x                 sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x )           trigonometric tangent of x       tan( 0.0 ) is 0
Math library functions.
1   // using math library function.
2   #include <iostream>
3   #include <cmath>
4
5   using std::cout;
6   using std::endl;
7
8 int main()                                          Parentheses () cause function to    be
9 {                                                   called. When the call done, the
10     // loop 10 times and calculate and output      function result will be provided.
11     // square root of x each time
12     for ( int x = -5; x <= 5; x++ )
13        cout << abs (x) << “, "; // function call
14
15     cout << endl;
16
17     return 0; // indicates successful termination
18 } // end main

5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5,
1   // using math library function.
2   #include <iostream>
3   // do not need any other header file.
4
5   using std::cout;
6   using std::endl;
7
8 int main()                                   Without function call, the program needs
9 {                                            implementation of abs here.
10     // loop 10 times and calculate and output
11     // square root of x each time
12     for ( int x = -5; x <= 5; x++ ) {
13        If ( x <0) cout << -x << “, "; // if else, implementation of abs (x)
14        else cout << x << “, ";
15     }
16     cout << endl;
17
18     return 0; // indicates successful termination
19 } // end main

5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5,
Program 1                           Program 2

12    for ( int x = -5; x <= 5; x++ )   12   for ( int x = -5; x <= 5; x++ ) {
13      cout << abs (x) << “, ";        13     If ( x <0) cout << -x << “, ";
14     else cout << x << “, ";
15   }

Thinking?
In program 1:
Does the function know when it will be called? No
Is that function reused 11 times in the loop?
(Does the name abs appear 11 times?)              Yes
Do you care how to get absolute number in No
main?
Comparing with a main program providing a detailed
implementation of abs inside that loop, is this main
more simple and easier to develop?                   Yes
New   defined function
 3 aspects
Function prototype
Function call
Function definition
 Argument and parameter
 Pre-condition and post-condition
 Reference parameter
 Return value
 How to solve real problems by using
arguments and parameters.
3   aspects
Function prototype
Is used by compiler to check if the function
call matches the function definition.
A simple sample:
void function-name( );
Calling/invoking a function (function call)
A simple call:
function-name();
Parentheses are used to call function
(Control goes to function).
When the call done, the program will return
to the point from which the function was
called (Control goes back to caller).
3   aspects                    Function heading, without “;”.
Function definition
A simple function definition
void function-name()
{
statements
}
Simple sample
******************************
******************************
Welcome!
******************************
******************************
1    // using new defined function.              Function prototype.

3       aspects
2    #include <iostream>
3    using namespace std;
Parentheses () cause function to be
4    void print_star_one_line ( );
called in main(). When the function
5
6
Function definition done, the program will do the next
int main()
7    {        A simple function definition
statement.
8       print_star_one_line ( );  // print one line of stars.
9                void function-name()
print_star_one_line ( ); // another line
10               {
cout <<“Welcome!“<<endl;
11      print_star_one_line ( );  // print two lines of stars.
12
declarations and statements
print_star_one_line ( );
Function definition. Its statements
13               }                      inside will be executed when the
14       return 0; // indicates successful termination
function is called.
15    } // end main
16
17    void print_star_one_line ( )
18    {
19       cout << “******************************“<< endl;
20     } // end of function
A function cannot be defined in other
function such like:
17   void print_star_one_line ( )
18   {
19         void print_one_star ( )
20         {
21                    cout << ”*” << end;
22         } // end of function print_one_star

......
.. } // end of function print_star_one_line
******************************
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Welcome!
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
******************************

Thinking?
Do we need two different functions?
Argument and parameter
 Make function more general by input parameter.
 With parameter in the function definition, function
call with different value of argument can fulfill
 Argument:
A variable or expression listed in a function call;
Also called actual argument or actual parameter.
 Parameter:
A variable declared in a function heading;
Also called formal argument or formal parameter.
Argument         and parameter
 Example.
Express the following procedure:
Two numbers; add them together; divide by 2.
Try 9 and 8
Try 7 and 4
Did you use (x+y)/2 when you want to express
the procedure?
Did you use (a+b)/2 when you want to express
the procedure?
1    // using list of arguments and parameters, argument promotion.
2    #include <iostream>
3    using namespace std;
We tried 9 and 8.
4    void showavg ( int, int );
5
We tried 7 and 4
6    int main()
7    {
8         showavg (9, 8);
9         showavg (7, 4);                            Instead of x and y (or a and b), I
10        return 0; //successful termination         used num1 and num2.
11     } // end main
12
13    void showavg (int num1, int num2)
14    {
15        cout << float(num1 + num2)/2 <<endl;
16     } // end of function
Argument              and parameter
General format (Prototype, Call, and Definition)
Function prototype
Tells compiler argument type.
void function-name( Datatype );
Function call
function-name( argument );
An argument is passed to parameter in function definition
Function definition
void function-name( DataType VariableName )
{
statements // use VariableName; its value = value of the argument.
}
1    // using argument and parameter.
2    #include <iostream>
3    using namespace std;
‘*’ is passed to
4    void print_one_line ( char );
parameter.
5                                                                   main      Print_one_line
6    int main()
ch
7    {                                                                 ‘*’
8        print_one_line (‘*’ ); // print one line of stars.
9        print_one_line (‘A’ ); // print one line of ‘A’s.
10       cout <<“Welcome!“<<endl;                                      ‘A’
11       print_one_line (‘A’ );  // print another line of ‘A’s.                    ch
12       print_one_line (‘*’ );   // print another line of stars.
13
14       return 0; // indicates successful termination
15    } // end main
16                                                                    Sequence Diagram
17    void print_one_line ( char ch )
Use parameter ch as a
18    {
variable. Its value
19       Int i;                            comes from the
20       for ( int x = 1; x <= 30; x++ )   argument.
21          cout << ch;
22       cout << endl;
23     } // end of function
******************************
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Welcome!
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
******************************
Argument               and parameter
The value of argument and parameter
Arguments can be constants, variables, and
expressions
The argument will be evaluated to match the
parameter when the function is called.
Force arguments to be of definition type
cout << sqrt(4)    //Converting 4 to double (4.0)
The value will be passed to parameter.
The parameter is a variable and its value is
according to the argument in different call.
1    // using argument and parameter.
2    #include <iostream>
Constants, ‘*’ is passed to parameter,
3    using namespace std;
one line ‘*’.
4    void print_one_line (char );
5
6    int main()                                               Variable, its value ‘A’ is   passed to
7    {                                                        parameter, one line ‘A’.
8         char c=’A’;
9         print_one_line (‘*’ );   // one line ‘*’.
10         print_one_line (c );    // one line ‘A’.
11        cout <<“Welcome!“<<endl;
12        print_one_line (c+ ’d’- ’c’ );    //one line ‘B’.
13        print_one_line (‘*’ );    // print another line of ‘*’.
14        return 0; // indicates successful termination
15     } // end main
16
17    void print_one_line ( char ch )
Expression, its value ‘B’ is
18    {
evaluated and passed to
19       int i;
parameter, one line ‘B’.
20       for ( int x = 1; x <= 30; x++ )
21       cout << ch;
22       cout << endl;
23     } // end of function
main        Print_one_line

constant value                  ch
‘*’

value of variable c    ‘A’
ch

value of expression    ‘B’
ch

Sequence Diagram
******************************
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Welcome!
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
******************************
Argument            and parameter
Definition for multiple arguments and
parameters)
Function prototype
void function-name( DataTypeList );
The name of the function followed by data types of
arguments.
Comma separated list.
Function call
function-name( ArgumentList );
The arguments are passed to the parameters according to
their positions, left to right.
Comma separated list of arguments.
Argument               and parameter
Advanced format (Prototype, Call, and Definition)
Function definition
void function-name( ParameterList )
{
statements
}
If the list is present, it has the following form:
DataType Parameter1, DataType Parameter2, …
Comma separated list.
1    // using list of arguments and parameters, argument promotion.
2    #include <iostream>
3    using namespace std;                     Datatype List.
4    void showavg ( int, int );
5
6    int main()                                    Argument List. The value of i and j, 9
7    {                                             and 2, are passed to num1 and num2.
8         char c=’a’;
9         int i=9, j=2;
10          showavg (i, j);
11        showavg (i, 2.5);
12        showavg (c*300, 11);                 The value of 2.5 (float) will be truncated to 2 and
13        return 0; //successful termination   be passed to num2 (int).
14     } // end main
The type of c*300 will be promoted to int
15
because it’s char * int.
16    void showavg (int num1, int num2)
17    {
18        cout << float(num1 + num2)/2 <<endl;
19     } // end of function
Parameter List.
5.5
5.5
14555.5
Real           Case (A company and its delivery)
Company                               Guy of delivery service
Call delivery service
Product = ‘*’
His job is to
‘*’
handle (deliver)
Control goes back                        this ‫.ٱ‬
(delivery confirmation).

Thinking?
For a guy who delivers the product of that company:
 Does he know what his job is? (function definition)
 Does he know what he will deliver? (parameter)
For the company:
 Does the company knows what the guy will deliver? (argument)
 Does the company care how he will deliver? (Does the main include
the implementation of its functions?)
 Does the company need confirm the delivery? (Control goes back to
main or caller when the function is done.)
Pre-condition                   and post-condition
Pre-condition:
To ensure there is no misuse.
An assertion that must be true before the function call
It may include:
 The acceptable range of argument
 The external resources the function used and their status.

Post-condition:
To ensure the expecting result.
An assertion that should be true after the function is called.
It may include:
 The results
 All the external things this execution can change.
1 // Function void showavg (int, int).
2 // Pre-condition:
3 //             Argument: two integer numbers
4 //             external resource: None
5 // Post-condition:
6 //             result: show the average on screen
7 //             external thing changed: Only the monitor.
8
9 void showavg (int num1, int num2)
10 {
11    cout << float(num1 + num2)/2 <<endl;
12 } // end of function
void my_function ( int    , int        ); //function prototype

int main( )
{      int k=3, m =4 ;

my_function( k      , m ); //function call

return 0;
}

void my_function ( int x , int y        ) //function definition
{

}
Reference         parameter
Value parameter
A parameter that receives a copy of the value of
the corresponding argument.
The change of value of this parameter variable in
the function won’t change any thing in its caller
(main).
1    // using argument and parameter.
2    #include <iostream>
3    using namespace std;
4    void print_one_line (char );
5
6    int main()
7    {
8         char c=’A’;                                        main        function
9         print_one_line (‘*’ );
10         print_one_line (c );               constant value              ch
‘*’
11        cout <<“Welcome!“<<endl;
‘*’
12        print_one_line (c+ ’d’- ’c’ );
13        print_one_line (‘*’ );
14        return 0;                        value of variable c   ‘A’
15     } // end main
ch
16                                                                         ‘A’
17    void print_one_line ( char ch )
18    {
value of expression   ‘B’
19       int i;
ch
20       for ( int x = 1; x <= 30; x++ )
21       cout << ch;                                                        ‘B’
22       cout << endl;
23     } // end of function

Sequence Diagram
Reference            parameter
 A parameter that receives the location of the caller’s
argument (main).
 The change of value of this parameter variable in the
function will bring the change to main after the
function call.
 The argument of its function call should be a
variable (declared in main).
 General format:
void function-name( Datatype & ); //prototype
function-name( ArgumentVariable ); //call
void function-name( DataType & VariableName )
// definition
main           Function (char & ch)
Function (   i     )                ch, i
‘*’                    ‘*’

variable i
ch = ‘A’;
‘A’
‘A’

Sequence Diagram
1     // using reference parameter.
2     #include <iostream>
Datatype &
3     using namespace std;
4     void showavg ( int, int, float & );
5     int main()                                   A variable in main. It will be used as
6     {                                            reference argument.
7          float cf=1.2;
8          int i=9, j=2;
9          showavg (i, j,cf);
10         cout <<i << endl << cf <<endl        Function call. No & here.
11         return 0; //successful termination
12      } // end main
13
14     void showavg (int num1, int num2 , float & avg)
15     {
16         avg = float(num1 + num2)/2;
17         num1 = 2;
18      } // end of function                        The     change of value of reference
parameter. This change in function is
9                                                       brought to main by reference parameter.
5.5
The change of value of value parameter won’t change
the value of the argument variable i in main.
main                 showavg
i              j                       num1    num2     avg, cf

9                  2                    9       2       1.2
cf
1. 2

num1    num2     avg, cf
i   j                  cf                   2       2        5.5
9       2              5.5

Sequence Diagram
Return
 Return results by using reference parameters
 Return result by using return statement in function
Function prototype
Tells compiler return type
int square( int );
Function takes an int and returns an int
Function call
cout << square(x);
After finished, passes back result
Return
 Return result by using return statement in function
Function definition
return-value-type function-name( parameter-list )
{
statements
return Result;
}
Return-value-type: Data type of result returned (use
void if nothing returned)
The value of Result will be evaluated and passed
back to caller (main).
If no data to return (void), use return;
1
2    // using return statement.
3    #include <iostream>
4                                        Function prototype: specifies
5    using std::cout;                    data types of arguments and
6    using std::endl;                    return values. square
expects int, and returns an
7
int.
8    int square( int ); // function prototype
9
10   int main()
11   {
12     // loop 10 times and calculate and output Parentheses () cause
13     // square of x each time                      function to be called. When
14     for ( int x = 2; x <= 10; x++ )               done, it returns the result.
15        cout << square( x ) << " "; // function call
16
17     cout << endl;
18
19     return 0; // indicates successful termination
20
21   } // end main
22
23   // square function definition returns square of an integer
24   int square( int y ) // y is a copy of argument to function
25   {
26      return y * y; // returns square of y as an int
27
28   } // end function square               Definition of square. Returns y
* y, or y squared.

4 9 16 25 36 49 64 81 100
1
2    // using reference parameters for several return values.
3    #include <iostream>
4                                                                     Function prototype: specifies
5    using std::cout;                                                 data types of arguments and
6    using std::endl;                                                 return values.
Square_and_root expects
7
an int, and returns two
8    void square_and_root( int, int&, float& ); // function prototype results in reference parameters
9                                                                     int & and float &.
10   int main()
11   {
12     int s;                                         Parentheses () cause
13     float r;                                       function to be called. When
14     for ( int x = 2; x <= 5; x++ ) {               done, it returns two results in
15                                                    variables s and r.
square_and_root( x, s, r ) ; // function call
16        cout << s << “, " << r << “; "; // show two results
17     }
18     cout << endl;
19     return 0; // indicates successful termination
20
21   } // end main
22
23   // function definition returns square and square root
24   void square_and_root( int x, int &y, float & z )
25   {
26      y = x* x; // returns square of x as an int             Definition of square. Returns the
27      z = sqrt(x); // returns square root of x as an float   change of y and z to main by using
28   } // end function square                                  reference parameter.

4, 1.4121; 9, 1.73205; 16, 2; 25, 2.23607;
24   int square( int y )      24   void square_and_root( int x, int &y, float & z )
25   {                        25   {
26     return y * y;          26     y = x* x;
27                            27     z = sqrt(x);
28   }                        28   }

The function using return statement is easy to read
and can return one value to its caller.
The function using reference parameter
has a long list of parameters.
has a complicated execution.
can return more values.
Exercises
******************************                                1 #include <iostream>
******************************                                2 using namespace std;
Welcome!                                                      3
******************************                                4
******************************                                5 int main()
6 {
1    #include <iostream>                                      7    for ( int x = 1; x <= 30; x++ )
2    using namespace std;                                     8               cout << ”*”;
3    void print_one_line ( );                                 9    cout << endl;
4                                                             10    for ( int x = 1; x <= 30; x++ )
5    int main()                                               11              cout << ”*”;
6    {                                           Function prototype << endl;
12    cout
7         print_one_line ( );                                 13    cout <<“Welcome!“<<endl;
8         print_one_line ( );                                 14    for ( int x = 1; x <= 30; x++ )
9         cout <<“Welcome!“<<endl;                            15               cout << ”*”;
10        print_one_line ( );                                 16    cout << endl;
11        print_one_line ( );                                 17    for ( int x = 1; x <= 30; x++ )
Function call
12        return 0;                                           18               cout << ”*”;
13     } // end main                                          19    cout << endl;
14                                                            20
15     void print_one_line ( ) // function heading            21    return 0;
16     { // function body                                     22 }
17       for ( int x = 1; x <= 30; x++ )
18              cout << ”*”;
19        cout << endl;                           Function definition
20      } // end of function
******************************             1    // using argument and parameter.
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA             2    #include <iostream>
3    using namespace std;
Welcome!
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB             4    void print_one_line (char );
******************************             5
6    int main()
7    {
Type of argument   8         char c=’A’;
9         print_one_line (‘*’ );
10         print_one_line (c );
11        cout <<“Welcome!“<<endl;
12        print_one_line (c+ ’d’- ’c’ );
13        print_one_line (‘*’ );
Argument        14        return 0;
15     } // end main
16
17    void print_one_line ( char ch )
18    {
19       for ( int x = 1; x <= 30; x++ )
20                   cout << ch;
Parameter         21       cout << endl;
22     } // end of function
How   to solve real problems by
using arguments and parameters
Question on page 19: Get the average of
two numbers
Two factors: (x+y) /2 (or (a+b)/2)
Two arguments
Two parameter variables
1     //using multiple arguments and parameters.
2     #include <iostream>
3     using namespace std;
4     void showavg ( int, int );
5
6     int main()
7     {
8          showavg (9, 8);
9          showavg (7, 4);
10         return 0; //successful termination
11      } // end main
12
13     void showavg (int num1, int num2)
14     {
15         cout << float(num1 + num2)/2 <<endl;
16      } // end of function

The average number is printed out when the function is called every time.
How can the caller use the result of function?
Do we need return?
Program using return statement
1    // using return statement.      Return type
2    #include <iostream>
3    using namespace std;
4    float get_avg ( int, int );
5
6    int main()
7    {
8         cout << get_avg (9, 8) <<endl;
9         cout << get_avg (7, 4) <<endl;
10        return 0; //successful termination
11     } // end main
12
Return statement
13    float get_avg (int num1, int num2)
14    {
15        return float(num1 + num2)/2;
16     } // end of function
Program using reference parameter

1    // using return statement.
2    #include <iostream>
3    using namespace std;
4    void get_avg ( int, int, float & );
5
6    int main()
7    {                                                 Reference
8         int r;                                       parameter
9         get_avg (9, 8, r );
10        cout << r <<endl;
11        get_avg (7, 4, r );
12        cout << r <<endl;
13        return 0; //successful termination
14     } // end main
15
16    void get_avg (int num1, int num2, float & res)
17    {
18        res = float(num1 + num2)/2;
19     } // end of function
Solution for exercises
Get the larger one of two numbers
Two factors
Two arguments
Two parameter variables
1    // using return statement.                               “cout <<___ ; //function call”
2    #include <iostream>                                      -> function with return
3    using namespace std;                                     statement
4    int get_larger ( int, int );
5
6    int main()
7    {
8         int x, y;
9         cin >> x >> y;
10        cout << get_larger (x, y) <<endl; //function call
11        return 0; //successful termination
12     } // end main
13
14    int get_larger (int num1, int num2)
15    {
16        if (num1 > num2)
17            return num1;
18        else return num2;
19     } // end of function
1    // using return statement.
2    #include <iostream>
3    using namespace std;
4    int get_larger ( int, int );
5
6    int main()
7    {
8         int x, y;
9         cin >> x >> y;
10        cout << get_larger (x, y) <<endl;
11        return 0; //successful termination
12     } // end main
13
14    int get_larger (int num1, int num2)
15    {
16         return (num1 > num2)? num1: num2;
17     } // end of function
1    // using reference parameter.
2    #include <iostream>
3    using namespace std;                        “cout <<larger;”
4    void get_larger ( int, int, int & );        -> function with reference
parameter “larger”.
5
6    int main()
7    {
8         int x, y, larger;
9         cin >> x >> y;
10        get_larger (x, y, larger );
11        cout << larger <<endl;
12        return 0; //successful termination
13     } // end main
14
15    void get_avg (int num1, int num2, int & res)
16    {
17        res = (num1 > num2)? num1: num2;
18     } // end of function
Random    number generator
Usage
Format
Example
 Random selection
rolling dice, and etc.
 rand function (<cstdlib>)
i = rand();
Generates unsigned integer between 0 and RAND_MAX
(usually 32767)
Generates integer between a and b.
i = rand() % 6 + 1;
 “Rand() % 6” generates a number between 0 and 5 (scaling)
 x % y is between 0 and y – 1, i.e., 10 % 3 is 1
 “+ 1” makes the range 1 to 6 (shift)
 Example: Program to roll dice.
1   // Shifted, scaled integers produced by 1 + rand() % 6.               Head file.
2   #include <iostream>
3   #include <iomanip>
4 #include <cstdlib> // contains function prototype for rand
5
6   using namespace std;
7
8 int main()
9 {
10     // loop 20 times
11     for ( int counter = 1; counter <= 20; counter++ ) {       Output of rand() scaled and
12                                                               shifted to be a number
13        // pick random number from 1 to 6 and output it        between 1 and 6.
14        cout << setw( 10 ) << ( 1 + rand() % 6 );
15        // if counter divisible by 5, begin new line of output
16        if ( counter % 5 == 0 )
17           cout << endl;
18
19     } // end for structure
20
21     return 0; // indicates successful termination
22 } // end main
6   6   5   5   6
5   1   1   5   3
6   6   2   4   2
6   2   3   4   1

Thinking
Is this fair?
1   // Roll a six-sided die 6000 times.
2   #include <iostream>
3   #include <iomanip>
4 #include <cstdlib> // contains function prototype for rand
5
6   using namespace std;
7
8 int main()
9 {
10     int frequency1 = 0;
11     int frequency2 = 0;
12     int frequency3 = 0;
13     int frequency4 = 0;
14     int frequency5 = 0;
15     int frequency6 = 0;
16     int face; // represents one roll of the die
17
18   // loop 6000 times and summarize results
19   for ( int roll = 1; roll <= 6000; roll++ ) {
20      face = 1 + rand() % 6; // random number from 1 to 6
21
22    // determine face value and increment appropriate counter
23    switch ( face ) {
24       case 1:        // rolled 1
25         ++frequency1;
26         break;
27      case 2:       // rolled 2
28         ++frequency2;
29         break;
30      case 3:       // rolled 3
31         ++frequency3;
32         break;
33      case 4:       // rolled 4
34         ++frequency4;
35         break;
36      case 5:       // rolled 5
37         ++frequency5;
38         break;
39        case 6:       // rolled 6
40          ++frequency6;
41          break;
42        default:     // invalid value
43          cout << "Program should never get here!";
Default case included even
44                                                         though it should never be
45      } // end switch                                    reached. This is a matter of
46                                                         good coding style
47    } // end for
48
49    // display results in tabular format
50    cout << "Face" << setw( 13 ) << "Frequency"
51        << "\n 1" << setw( 13 ) << frequency1
52        << "\n 2" << setw( 13 ) << frequency2
53        << "\n 3" << setw( 13 ) << frequency3
54        << "\n 4" << setw( 13 ) << frequency4
55        << "\n 5" << setw( 13 ) << frequency5
56        << "\n 6" << setw( 13 ) << frequency6 << endl;
57
58    return 0; // indicates successful termination
59
60   } // end main
Face   Frequency
1      1003
2      1017
3       983
4       994
5      1004
6       999
Calling rand() repeatedly
Gives the same sequence of numbers
To get different random sequences
Provide a seed value
• Like a random starting point in the sequence
• The same seed will give the same sequence
srand(seed);
• <cstdlib>
• Used before rand() to set the seed
1   // Randomizing die-rolling program.
2   #include <iostream>
3   #include <iomanip>
4 #include <cstdlib>
5   using namespace std;
6
7 int main()
8 {
9    unsigned seed;
10
Setting the seed with
11     cout << "Enter seed: ";                 srand() before rand().
12     cin >> seed;
13     srand( seed ); // seed random number generator
14         // loop 10 times
15     for ( int counter = 1; counter <= 10; counter++ ) {
16        // pick random number from 1 to 6 and output it
17        cout << setw( 10 ) << ( 1 + rand() % 6 );
18        // if counter divisible by 5, begin new line of output
19        if ( counter % 5 == 0 )
20           cout << endl;
21     } // end for
22     return 0; // indicates successful termination
23 } // end main
Enter seed: 67                rand() gives the same
6      1     4   6   2   sequence if it has the same
1      6     1   6   4   initial seed.

Enter seed: 432
4      6     3   1   6
3      1     5   4   2

Enter seed: 67
6      1     4   6   2
1      6     1   6   4
Can use the current time to set the seed
Use current time as seed
srand( time( 0 ) );
time( 0 );
• <ctime>
• Returns current time in seconds
Number = shiftingValue + rand() %
scalingFactor
• shiftingValue = first number in desired range
• scalingFactor = width of desired range
1     // Shifted, scaled integers produced by 1 + rand() % 6.
2     #include <iostream>
3     #include <iomanip>                       Use current time as seed.
4    #include <cstdlib> // contains function prototype for rand
5    #include <ctime> // contains function prototype for time
6     using namespace std;
7
8    int main()
9    {
10       srand ( time( 0 ));
11       for ( int counter = 1; counter <= 20; counter++ ) {
12
13        // pick random number from 1 to 6 and output it
14        cout << setw( 10 ) << ( 1 + rand() % 6 );
15        // if counter divisible by 5, begin new line of output
16        if ( counter % 5 == 0 )
17           cout << endl;
18
19      } // end for structure
20
21       return 0; // indicates successful termination
22     } // end main
1   1   1   3   3
1   4   5   6   6
5   2   3   6   1
1   5   6   3   3

1   5   2   1   4
2   2   3   5   2
4   6   1   3   5
5   5   6   5   2
Scope

Introduction
Local scope
Global scope
Name precedence
Static variable

5 int main()
6 {
main               cf
7      float cf=1.2;                                    i   j
8      int i=9, j=2;                                            1. 2
9      2
9      showavg (i, j,cf);
10     cout <<i << endl << cf <<endl          showavg           avg    num1   num2
11     return 0; //successful termination
12 } // end main
13                                                               5.5
14 void showavg (int num1, int num2 ,
float & avg)                                                     cf
15 {
16      avg = float(num1 + num2)/2;                  9      2   5.5
17      num1 = 2;
18 } // end of function

Introduction        (scope)
Scope
Portion of program where identifier can be used.
Local scope
Global scope
Local   scope
Local variables, function parameters
Scope begins at declaration, ends at right
brace
Variable created when program enters its
block
Variable invalid when program leaves block
Variable destroyed when program reaches
the right brace of this block
Create a new block, giving i block
1    // using arguments and parameters.
scope. When the block ends (the
2    #include <iostream>                             program reaches the right brace of
3    using namespace std;                            the block), this i is destroyed.
4    void showavg ( int, int, float & );
5    int main()                                       Local scope starts from declaration
6    {
Local variable will be invalid
7         float cf=1.2;                                       when the program leaves
8         int j;                                              main for showavg.
9       for ( j = 1; j <= 5; j++ ) {
10           int i = 9;                                          i
11          showavg( i, j, cf ) ; // function call
12           cout <<i << endl << cf <<endl
13        }
14        return 0; //successful termination
15     } // end main
16
17    void showavg (int num1, int num2 , float & avg)
num1
18    {
19        avg = float(num1 + num2)/2;
20     } // end of function
{          {
int i;
int i;     …………
i = i+2;
…………

int i;
i=i+1;
…………

i=i+1;
}          …………

}
Global    scope
Global variables (constants), function
definitions and prototypes
Defined outside of any function in a file
Scope begins at declaration, ends at the
end of this file
Variable created when program starts
Variable is valid from its declaration to the
end of this file.
Variable destroyed when program ends
1   // using global variables.               1   // using global variables.
2   #include <iostream>                      2   #include <iostream>
3   using namespace std;                     3   using namespace std;
4                                            4
5   double c_area( int );                    5 const double pi = 3.14;
6   const double pi = 3.14;                  6
7                                            7 double c_area( int radius)
8 int main()                                 8 {
10     cout << “When pi is " << pi <<endl;   10 } // end function square
11                                           11
12     for ( int x = 1; x <= 10; x++ )       12 int main()
13       cout << c_area( x ) << " ";         13 {
14     cout << endl;                         14     cout << “When pi is " << pi <<endl;
15     return 0;                             15
16 } // end main                             16     for ( int x = 1; x <= 10; x++ )
17                                           17       cout << c_area( x ) << " ";
18 double c_area( int radius)                18     cout << endl;
19 {                                         19     return 0;
20     return radius * radius * pi;          20 } // end main
21 } // end function square                  21
Thinking
Local           Global
When is it created?           -               -
When is it destoried?         End of local    End of file
block
Is it still valid when the
No             Yes
control goes out of the
local block?
Name     precedence
When a function declares a local identifier
with the same name as a global identifier,
the local identifier takes precedence within
the function.
The precedence that a local identifier in a
function has over a global identifier with the
same name in any references that the
function makes to that identifier; also called
name hiding.
1   // using name precedence.
2   #include <iostream>
3   using namespace std;
4
5   double c_area( int );
pi
6   const double pi = 3.14;
7                                            3.14
8 int main()
main
9 {
10     cout << “When pi is " << pi <<endl;
pi   c_area
11
13     cout << c_area(10 ) << " ";                  3
14     cout << endl;
15     return 0;
16 } // end main
17
19 {
20     int pi = 3;
21 } // end function square
When pi is 3.14
300
Static   variable
Variables exist for entire program
Static local variables in function
Keeps value between function calls
Variable created once when program first
entered the function
Only known in own function
Variable destroyed when program ends
1   // using local static.
main
2   #include <iostream>
3   using namespace std;                                                                useLocal
4   void useStaticLocal( )                                          Y=50
5
6 int main()                                                         51
7 {
8    for ( int x = 1; x <= 10; x++ )                                                    useLocal
9       useLocal( );                                                Y=50
10     return 0;
51
11 } // end main
12                                                                                      useLocal
13 void useLocal ( )                                                Y=50
14 {
15     // initialized only first time useStaticLocal is called       51
16
17
int y = 50;
…
18     cout << "local x is " << y ++ << endl;
19 } // end function useStaticLocal                              Local variable of function; it
is initialized every time when
the program call this function.
local x is 50
local x is 50
local x is 50
local x is 50
local x is 50
local x is 50
local x is 50
local x is 50
local x is 50
local x is 50
1   // using local static.
main
2   #include <iostream>
3   using namespace std;                                                             useStaticLocal
4   void useStaticLocal( )                                           Y=50
5
6 int main()                                                         51
7 {
8    for ( int x = 1; x <= 10; x++ )
useStaticLocal
9       useStaticLocal( );
10     return 0;
52
11 } // end main
12                                                                                   useStaticLocal
13 void useStaticLocal ( )
14 {
15     // initialized only first time useStaticLocal is called       53
16
17
static int y = 50;
…
18     cout << "local static x is " << y ++ << endl;
19 } // end function useStaticLocal                              Static local variable of
function; it is initialized only
once, and retains its value
between function calls.
local static x is 50
local static x is 51
local static x is 52
local static x is 53
local static x is 54
local static x is 55
local static x is 56
local static x is 57
local static x is 58
local static x is 59
Inline   function
Inline functions
Keyword inline before function
Asks the compiler to copy code into program
Compiler can ignore inline
Good for small, often-used functions
Example
inline double cube( const double s )
{ return s * s * s; }
const tells compiler that function does not
modify s
1     // Using an inline function to calculate.
2     #include <iostream>
3     using namespace std;
4
5    // Definition of inline function cube. Definition of function
6    // appears before function is called, so a function prototype
7    // is not required. First line of function definition acts as
8    // the prototype.
9     inline double cube( const double side )
10     {
11        return side * side * side; // calculate cube
12     } // end function cube
13
14    int main()
15    {
16       double sideValue;
17       cout << "Enter the side length of your cube: ";
18       cin >> sideValue;
19       // calculate cube of sideValue and display result
20       cout << "Volume of cube with side "
21           << sideValue << " is " << cube( sideValue ) << endl;
22       return 0; // indicates successful termination
23    } // end main
Enter the side length of your cube: 3.5
Volume of cube with side 3.5 is 42.875
Functions with same name and different
parameters
More general, should perform similar tasks
I.e., function to square ints and function to square
floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
signature
Based on name and parameter types (order
matters)
2   #include <iostream>
3   using namespace std;
4
5 inline double square ( const double side )
6 {
7     cout << “double “;
8     return side * side; // calculate double square
9 } // end function square
10
11 inline int square ( const int side )
12 {
13     cout << “integer “;
14     return side * side; // calculate int square
15 } // end function square                                     The proper function is called
16                                                              based upon the argument (int
or double).
17 int main()
18 {
19     // calculate squre of sideValue and display result
20     cout << “Square with side 2 is " << square( 2 ) << endl;
21     cout << “Square with side 3.2 is " << square( 3.2 ) << endl;
22     return 0; // indicates successful termination
23 } // end main
Square with side 2 is integer 4
Square with side 3.2 is double 10.24
1    // Fig. 3.4: fig03_04.cpp
2    // Finding the maximum of three floating-point numbers.
3    #include <iostream>
4
5    using std::cout;
6    using std::cin;
7    using std::endl;
8
9    double maximum( double, double, double ); // function prototype
10
11   int main()
12   {                                      Function maximum takes 3
13     double number1;                      arguments (all double) and
14     double number2;                      returns a double.
15     double number3;
16
17    cout << "Enter three floating-point numbers: ";
18    cin >> number1 >> number2 >> number3;
19
20    // number1, number2 and number3 are arguments to
21    // the maximum function call
22    cout << "Maximum is: "
23        << maximum( number1, number2, number3 ) << endl;
24
25    return 0; // indicates successful termination
26
27   } // end main
28
29   // function maximum definition;
30   // x, y and z are parameters
31   double maximum( double x, double y, double z )
32   {
33      double max = x; // assume x is largest
34
35    if ( y > max )   // if y is larger,
36       max = y;      // assign y to max
37
38    if ( z > max )   // if z is larger,   Comma separated list for
39       max = z;      // assign z to max   multiple parameters.
40
41      return max;     // max is largest value
42   } // end function maximum

Enter three floating-point numbers: 99.32 37.3 27.1928
Maximum is: 99.32

Enter three floating-point numbers: 1.1 3.333 2.22
Maximum is: 3.333

Enter three floating-point numbers: 27.9 14.31 88.99
Maximum is: 88.99

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 0 posted: 1/3/2013 language: English pages: 96