Function n Function l Introduction l Library function

  • Slides: 96
Download presentation
Function

Function

n. Function l Introduction l Library function l New defined function l Random number

n. Function l Introduction l Library function l New defined function l Random number generator l Scope l Inline function l Function overload

n. Introduction l Why do we need function? ¡ Reuse l Chapter and simplify

n. Introduction l Why do we need function? ¡ Reuse l Chapter and simplify a large program. 7 and Chapter 8 (p 309 -p 436)

n. Library function 1 // using library function. 2 #include <iostream> 3 #include <iomanip>

n. 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

Include the header file l Functions called by writing l ¡ l setw (4);

Include the header file l Functions called by writing l ¡ l setw (4); 4 can be replaced by setw( 10 cout 5<<); setw(5) <<123 << endl; ¡ Constants: ¡ Variables: l X=4; 9 int x=4; l 10 setw(x); cout << setw(x) <<123 << endl; ¡ Expressions: l X=2; 9 int x=2; l setw( 6 -x ); 10 cout << setw(6 -x) <<123 << endl;

l Math library function ¡ Perform common mathematical calculations ¡ Include the header file

l Math library function ¡ Perform common mathematical calculations ¡ Include the header file <cmath> ¡ Example cout << sqrt( 900. 0 ); sqrt (square root) function l The preceding statement would print 30 l

1 // using math library function. Head file. 2 #include <iostream> 3 #include <cmath>

1 // using math library function. Head file. 2 #include <iostream> 3 #include <cmath> 4 5 using std: : cout; 6 using std: : endl; 7 Parentheses () cause function to 8 int main() 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, be

1 // using math library function. 2 #include <iostream> 3 // do not need

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 Without function call, the program 8 int main() 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, needs

Program 1 12 13 for ( int x = -5; x <= 5; x++

Program 1 12 13 for ( int x = -5; x <= 5; x++ ) cout << abs (x) << “, "; Program 2 12 13 14 15 for ( int x = -5; x <= 5; x++ ) { If ( x <0) cout << -x << “, "; else cout << x << “, "; } l. Thinking? l. In program 1: l. Does the function know when it will be called? No l. Is that function reused 11 times in the loop? (Does the name abs appear 11 times? ) Yes l. Do you care how to get absolute number in No main? l. Comparing with a main program providing a detailed implementation of abs inside that loop, is this main more simple and easier to develop? Yes

n. New defined l 3 aspects ¡ ¡ ¡ l l l function Function

n. New defined l 3 aspects ¡ ¡ ¡ l l l function 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.

n 3 aspects l Function prototype ¡ Is used by compiler to check if

n 3 aspects l Function prototype ¡ Is used by compiler to check if the function call matches the function definition. ¡ A simple sample: void function-name( ); l Calling/invoking ¡A a function (function call) 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).

n 3 aspects l Function definition ¡A Function heading, without “; ”. simple function

n 3 aspects l Function definition ¡A Function heading, without “; ”. simple function definition void function-name() { statements } l Simple sample

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

l. A function cannot be defined in other function such like: 17 18 19

l. A function cannot be defined in other function such like: 17 18 19 20 21 22 void print_star_one_line ( ) { void print_one_star ( ) { cout << ”*” << end; } // end of function print_one_star . . . . } // end of function print_star_one_line

*************** AAAAAAAAAAAAAAA Welcome! AAAAAAAAAAAAAAA *************** l. Thinking? l. Do we need two different functions?

*************** AAAAAAAAAAAAAAA Welcome! AAAAAAAAAAAAAAA *************** l. Thinking? l. Do we need two different functions?

n. Argument and parameter l Make function more general by input parameter. l With

n. Argument and parameter l Make function more general by input parameter. l With parameter in the function definition, function call with different value of argument can fulfill similar tasks. l Argument: A variable or expression listed in a function call; ¡ Also called actual argument or actual parameter. ¡ l Parameter: ¡ A variable declared in a function heading; ¡ Also called formal argument or formal parameter.

n. Argument l Example. ¡ Express and parameter the following procedure: Two numbers; add

n. Argument l Example. ¡ Express and parameter the following procedure: Two numbers; add them together; divide by 2. l Try 9 and 8 l Try 7 and 4 l ¡ 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 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // using list of arguments and parameters, argument promotion. #include <iostream> using namespace std; We tried 9 and 8. void showavg ( int, int ); int main() { showavg (9, 8); showavg (7, 4); return 0; //successful termination } // end main void showavg (int num 1, int num 2) { cout << float(num 1 + num 2)/2 <<endl; } // end of function We tried 7 and 4 Instead of x and y (or a and b), I used num 1 and num 2.

n. Argument l General format (Prototype, Call, and Definition) ¡ Function l and parameter

n. Argument l General format (Prototype, Call, and Definition) ¡ Function l and parameter prototype Tells compiler argument type. void function-name( Datatype ); ¡ Function call function-name( argument ); l An argument is passed to parameter in function definition ¡ Function definition void function-name( Data. Type Variable. Name ) { statements // use Variable. Name; its value = value of the argument. }

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // using argument and parameter. #include <iostream> using namespace std; void print_one_line ( char ); ‘*’ is passed to parameter. int main() { print_one_line (‘*’ ); // print one line of stars. print_one_line (‘A’ ); // print one line of ‘A’s. cout <<“Welcome!“<<endl; print_one_line (‘A’ ); // print another line of ‘A’s. print_one_line (‘*’ ); // print another line of stars. main ‘*’ ‘A’ Print_one_line ch ch return 0; // indicates successful termination } // end main void print_one_line ( char ch ) { Int i; for ( int x = 1; x <= 30; x++ ) cout << ch; cout << endl; } // end of function Use parameter ch as a variable. Its value comes from the argument. Sequence Diagram

*************** AAAAAAAAAAAAAAA Welcome! AAAAAAAAAAAAAAA ***************

*************** AAAAAAAAAAAAAAA Welcome! AAAAAAAAAAAAAAA ***************

n. Argument l The and parameter value of argument and parameter ¡ Arguments can

n. Argument l The and parameter 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. l Force arguments to be of definition type cout << sqrt(4) ¡ The //Converting 4 to double (4. 0) value will be passed to parameter. ¡ The parameter is a variable and its value is according to the argument in different call.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // using argument and parameter. #include <iostream> using namespace std; void print_one_line (char ); Constants, ‘*’ is passed to parameter, one line ‘*’. int main() Variable, its value ‘A’ is { parameter, one line ‘A’. char c=’A’; print_one_line (‘*’ ); // one line ‘*’. print_one_line (c ); // one line ‘A’. cout <<“Welcome!“<<endl; print_one_line (c+ ’d’- ’c’ ); //one line ‘B’. print_one_line (‘*’ ); // print another line of ‘*’. return 0; // indicates successful termination } // end main void print_one_line ( char ch ) { int i; for ( int x = 1; x <= 30; x++ ) cout << ch; cout << endl; } // end of function Expression, its value ‘B’ is evaluated and passed to parameter, one line ‘B’. passed to

main constant value ‘*’ value of variable c ‘A’ value of expression ‘B’ Print_one_line

main constant value ‘*’ value of variable c ‘A’ value of expression ‘B’ Print_one_line ch ch ch Sequence Diagram

*************** AAAAAAAAAAAAAAA Welcome! BBBBBBBBBBBBBBB ***************

*************** AAAAAAAAAAAAAAA Welcome! BBBBBBBBBBBBBBB ***************

n. Argument and parameter l Advanced format (Prototype, Call, and Definition for multiple arguments

n. Argument and parameter l Advanced format (Prototype, Call, and Definition for multiple arguments and parameters) ¡ Function prototype void function-name( Data. Type. List ); The name of the function followed by data types of arguments. l Comma separated list. l ¡ Function call function-name( Argument. List ); The arguments are passed to the parameters according to their positions, left to right. l Comma separated list of arguments. l

n. Argument l Advanced ¡ Function and parameter format (Prototype, Call, and Definition) definition

n. Argument l Advanced ¡ Function and parameter format (Prototype, Call, and Definition) definition void function-name( Parameter. List ) { statements } l If the list is present, it has the following form: Data. Type Parameter 1, Data. Type Parameter 2, … l Comma separated list.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // using list of arguments and parameters, argument promotion. #include <iostream> Datatype List. using namespace std; void showavg ( int, int ); int main() { char c=’a’; int i=9, j=2; showavg (i, j); showavg (i, 2. 5); showavg (c*300, 11); return 0; //successful termination } // end main Argument List. The value of i and j, 9 and 2, are passed to num 1 and num 2. The value of 2. 5 (float) will be truncated to 2 and be passed to num 2 (int). The type of c*300 will be promoted to int because it’s char * int. void showavg (int num 1, int num 2) { cout << float(num 1 + num 2)/2 <<endl; } // end of function 5. 5 14555. 5 Parameter List.

n. Real Case (A company and its delivery) Company Product = ‘*’ Guy of

n. Real Case (A company and its delivery) Company Product = ‘*’ Guy of delivery service Call delivery service ‘*’ Control goes back (delivery confirmation). His job is to handle (deliver) this ٱ. l Thinking? ¡ For a guy who delivers the product of that company: l l ¡ Does he know what his job is? (function definition) Does he know what he will deliver? (parameter) For the company: l l l 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. )

n. Pre-condition and post-condition l Pre-condition: To ensure there is no misuse. ¡ An

n. Pre-condition and post-condition l Pre-condition: To ensure there is no misuse. ¡ An assertion that must be true before the function call ¡ It may include: ¡ l l The acceptable range of argument The external resources the function used and their status. l Post-condition: To ensure the expecting result. ¡ An assertion that should be true after the function is called. ¡ It may include: ¡ l l The results All the external things this execution can change.

1 // Function void showavg (int, int). 2 // Pre-condition: 3 // Argument: two

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 num 1, int num 2) 10 { 11 cout << float(num 1 + num 2)/2 <<endl; 12 } // end of function

void my_function ( int , int ); //function prototype int main( ) { int

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

n. Reference l Value ¡A parameter that receives a copy of the value of

n. Reference l Value ¡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 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // using argument and parameter. #include <iostream> using namespace std; void print_one_line (char ); int main() { char c=’A’; print_one_line (‘*’ ); print_one_line (c ); cout <<“Welcome!“<<endl; print_one_line (c+ ’d’- ’c’ ); print_one_line (‘*’ ); return 0; } // end main constant value of variable c ‘*’ ‘A’ function ch ‘*’ ch ‘A’ void print_one_line ( char ch ) { int i; for ( int x = 1; x <= 30; x++ ) cout << ch; cout << endl; } // end of function value of expression ‘B’ ch ‘B’ Sequence Diagram

n. Reference parameter l A parameter that receives the location of the caller’s argument

n. Reference parameter l A parameter that receives the location of the caller’s argument (main). l The change of value of this parameter variable in the function will bring the change to main after the function call. l The argument of its function call should be a variable (declared in main). l General format: void function-name( Datatype & ); //prototype function-name( Argument. Variable ); //call void function-name( Data. Type & Variable. Name ) // definition

main Function ( i ) ‘*’ variable i ‘A’ Function (char & ch) ch,

main Function ( i ) ‘*’ variable i ‘A’ Function (char & ch) ch, i ‘*’ ch = ‘A’; ‘A’ Sequence Diagram

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

main i j 9 showavg num 1 2 9 num 2 avg, cf 2

main i j 9 showavg num 1 2 9 num 2 avg, cf 2 1. 2 num 2 avg, cf cf 1. 2 num 1 i 9 j cf 2 2 5. 5 Sequence Diagram 2 5. 5

n. Return l Return results by using reference parameters l Return result by using

n. Return l Return results by using reference parameters l Return result by using return statement in function ¡ Function prototype l Tells compiler return type int square( int ); Function takes an int and returns an int Function call cout << square(x); l After finished, passes back result l ¡

n. Return l Return result by using return statement in function ¡ Function definition

n. Return l Return result by using return statement in function ¡ Function definition return-value-type function-name( parameter-list ) { statements return Result; } l 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). l If no data to return (void), use return; l

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // using return statement. #include <iostream> using std: : cout; using std: : endl; Function prototype: specifies data types of arguments and return values. square expects int, and returns an int square( int ); // function prototype int main() { // loop 10 times and calculate and output Parentheses () cause function // square of x each time to be called. When done, it returns the result. for ( int x = 2; x <= 10; x++ ) cout << square( x ) << " "; // function call cout << endl; return 0; // indicates successful termination } // end main

23 24 25 26 27 28 // square function definition returns square of an

23 24 25 26 27 28 // square function definition returns square of an integer int square( int y ) // y is a copy of argument to function { return y * y; // returns square of y as an int } // end function square 4 9 16 25 36 49 64 81 100 Definition of square. Returns y * y, or y squared.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // using reference parameters for several return values. #include <iostream> Function prototype: specifies using std: : cout; data types of arguments and return values. using std: : endl; Square_and_root expects an int, and returns two void square_and_root( int, int&, float& ); // function prototype results in reference parameters int & and float &. int main() { int s; Parentheses () cause function float r; to be called. When done, it returns two results in variables for ( int x = 2; x <= 5; x++ ) { square_and_root( x, s, r ) ; // function calls and r. cout << s << “, " << r << “; "; // show two results } cout << endl; return 0; // indicates successful termination } // end main

23 24 25 26 27 28 // function definition returns square and square root

23 24 25 26 27 28 // function definition returns square and square root void square_and_root( int x, int &y, float & z ) { y = x* x; // returns square of x as an int z = sqrt(x); // returns square root of x as an float } // end function square 4, 1. 4121; 9, 1. 73205; 16, 2; 25, 2. 23607; Definition of square. Returns the change of y and z to main by using reference parameter.

24 25 26 27 28 int square( int y ) { return y *

24 25 26 27 28 int square( int y ) { return y * y; } l. The 24 25 26 27 28 void square_and_root( int x, int &y, float & z ) { y = x* x; z = sqrt(x); } function using return statement is easy to read and can return one value to its caller. l. The function using reference parameter lhas a long list of parameters. lhas a complicated execution. lcan return more values. l. Exercises

1 #include <iostream> 2 using namespace std; 3 4 5 int main() 6 {

1 #include <iostream> 2 using namespace std; 3 4 5 int main() 6 { #include <iostream> 7 for ( int x = 1; x <= 30; x++ ) using namespace std; 8 cout << ”*”; void print_one_line ( ); 9 cout << endl; 10 for ( int x = 1; x <= 30; x++ ) int main() 11 cout << ”*”; Function prototype { 12 cout << endl; print_one_line ( ); 13 cout <<“Welcome!“<<endl; print_one_line ( ); 14 for ( int x = 1; x <= 30; x++ ) cout <<“Welcome!“<<endl; 15 cout << ”*”; print_one_line ( ); 16 cout << endl; print_one_line ( ); 17 for ( int x = 1; x <= 30; x++ ) Function call return 0; 18 cout << ”*”; } // end main 19 cout << endl; 20 void print_one_line ( ) // function heading 21 return 0; { // function body 22 } for ( int x = 1; x <= 30; x++ ) cout << ”*”; Function definition cout << endl; } // end of function ****************************** Welcome! ****************************** 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

*************** AAAAAAAAAAAAAAA Welcome! BBBBBBBBBBBBBBB *************** Type of argument Argument Parameter 1 2 3 4

*************** AAAAAAAAAAAAAAA Welcome! BBBBBBBBBBBBBBB *************** Type of argument Argument Parameter 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // using argument and parameter. #include <iostream> using namespace std; void print_one_line (char ); int main() { char c=’A’; print_one_line (‘*’ ); print_one_line (c ); cout <<“Welcome!“<<endl; print_one_line (c+ ’d’- ’c’ ); print_one_line (‘*’ ); return 0; } // end main void print_one_line ( char ch ) { for ( int x = 1; x <= 30; x++ ) cout << ch; cout << endl; } // end of function

n. How to solve real problems by using arguments and parameters l Question on

n. How to solve real problems by using arguments and parameters l Question on page 19: Get the average of two numbers l Two factors: (x+y) /2 (or (a+b)/2) l Two arguments l Two parameter variables

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 //using multiple arguments and parameters. #include <iostream> using namespace std; void showavg ( int, int ); int main() { showavg (9, 8); showavg (7, 4); return 0; //successful termination } // end main void showavg (int num 1, int num 2) { cout << float(num 1 + num 2)/2 <<endl; } // end of function l. The average number is printed out when the function is called every time. l. How can the caller use the result of function?

l Do we need return? ¡ Program 1 2 3 4 5 6 7

l Do we need return? ¡ Program 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 using return statement // using return statement. #include <iostream> using namespace std; float get_avg ( int, int ); Return type int main() { cout << get_avg (9, 8) <<endl; cout << get_avg (7, 4) <<endl; return 0; //successful termination } // end main float get_avg (int num 1, int num 2) { return float(num 1 + num 2)/2; } // end of function Return statement

¡ Program 1 2 3 4 5 6 7 8 9 10 11 12

¡ Program 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 using reference parameter // using return statement. #include <iostream> using namespace std; void get_avg ( int, float & ); int main() { int r; get_avg (9, 8, r ); cout << r <<endl; get_avg (7, 4, r ); cout << r <<endl; return 0; //successful termination } // end main void get_avg (int num 1, int num 2, float & res) { res = float(num 1 + num 2)/2; } // end of function Reference parameter

¡ Solution for exercises Get the larger one of two numbers l Two factors

¡ Solution for exercises Get the larger one of two numbers l Two factors l Two arguments l Two parameter variables l

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // using return statement. #include <iostream> using namespace std; int get_larger ( int, int ); int main() { int x, y; cin >> x >> y; cout << get_larger (x, y) <<endl; //function call return 0; //successful termination } // end main int get_larger (int num 1, int num 2) { if (num 1 > num 2) return num 1; else return num 2; } // end of function “cout <<___ ; //function call” > function with return statement

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // using return statement. #include <iostream> using namespace std; int get_larger ( int, int ); int main() { int x, y; cin >> x >> y; cout << get_larger (x, y) <<endl; return 0; //successful termination } // end main int get_larger (int num 1, int num 2) { return (num 1 > num 2)? num 1: num 2; } // end of function

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // using reference parameter. #include <iostream> using namespace std; void get_larger ( int, int & ); “cout <<larger; ” -> function with reference parameter “larger”. int main() { int x, y, larger; cin >> x >> y; get_larger (x, y, larger ); cout << larger <<endl; return 0; //successful termination } // end main void get_avg (int num 1, int num 2, int & res) { res = (num 1 > num 2)? num 1: num 2; } // end of function

n. Random l Usage l Format l Example number generator

n. Random l Usage l Format l Example number generator

l Random selection ¡ l rolling dice, and etc. rand function (<cstdlib>) i =

l Random selection ¡ l 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. ¡ l l 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.

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 between 1 and 6. 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

6 5 6 6 6 1 6 2 5 1 2 3 5 5

6 5 6 6 6 1 6 2 5 1 2 3 5 5 4 4 6 3 2 1 l. Thinking Is this fair?

1 // Roll a six-sided die 6000 times. 2 #include <iostream> 3 #include <iomanip>

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 frequency 1 = 0; 11 int frequency 2 = 0; 12 int frequency 3 = 0; 13 int frequency 4 = 0; 14 int frequency 5 = 0; 15 int frequency 6 = 0; 16 int face; // represents one roll of the die 17

18 19 20 21 22 23 24 25 26 27 28 29 30 31

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 // loop 6000 times and summarize results for ( int roll = 1; roll <= 6000; roll++ ) { face = 1 + rand() % 6; // random number from 1 to 6 // determine face value and increment appropriate counter switch ( face ) { case 1: // rolled 1 ++frequency 1; break; case 2: // rolled 2 ++frequency 2; break; case 3: // rolled 3 ++frequency 3; break; case 4: // rolled 4 ++frequency 4; break; case 5: // rolled 5 ++frequency 5; break;

39 40 41 42 43 44 45 46 47 48 49 50 51 52

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 case 6: // rolled 6 ++frequency 6; break; default: // invalid value cout << "Program should never get here!"; } // end switch } // end for // display results in tabular format cout << "Face" << setw( 13 ) << "Frequency" << "n 1" << setw( 13 ) << frequency 1 << "n 2" << setw( 13 ) << frequency 2 << "n 3" << setw( 13 ) << frequency 3 << "n 4" << setw( 13 ) << frequency 4 << "n 5" << setw( 13 ) << frequency 5 << "n 6" << setw( 13 ) << frequency 6 << endl; return 0; // indicates successful termination } // end main Default case included even though it should never be reached. This is a matter of good coding style

Face 1 2 3 4 5 6 Frequency 1003 1017 983 994 1004 999

Face 1 2 3 4 5 6 Frequency 1003 1017 983 994 1004 999

l Calling rand() repeatedly ¡ Gives the same sequence of numbers ¡ To get

l Calling rand() repeatedly ¡ Gives the same sequence of numbers ¡ To get different random sequences l Provide a seed value • Like a random starting point in the sequence • The same seed will give the same sequence l srand(seed); • <cstdlib> • Used before rand() to set the seed

1 // Randomizing die-rolling program. 2 #include <iostream> 3 #include <iomanip> 4 #include <cstdlib>

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 6 1 1 6 4 1 6 6 2 4 Enter

Enter seed: 67 6 1 1 6 4 1 6 6 2 4 Enter seed: 432 4 6 3 1 3 5 1 4 6 2 Enter seed: 67 6 1 1 6 4 1 6 6 2 4 rand() gives the same sequence if it has the same initial seed.

¡ Can use the current time to set the seed Use current time as

¡ Can use the current time to set the seed Use current time as seed l srand( time( 0 ) ); l time( 0 ); l • <ctime> • Returns current time in seconds l Number = shifting. Value + rand() % scaling. Factor • shifting. Value = first number in desired range • scaling. Factor = width of desired range

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

1 1 5 1 1 4 2 5 1 5 3 6 6 3

1 1 5 1 1 4 2 5 1 5 3 6 6 3 3 6 1 3 1 2 4 5 5 2 6 5 2 3 1 6 1 5 3 5 4 2 5 2

n. Scope l Introduction l Local scope l Global scope l Name precedence l

n. Scope l Introduction l Local scope l Global scope l Name precedence l Static variable

n. Introduction 5 int main() 6 { 7 float cf=1. 2; 8 int i=9,

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

n. Introduction (scope) l Scope ¡ Portion l Local of program where identifier can

n. Introduction (scope) l Scope ¡ Portion l Local of program where identifier can be used. scope l Global scope

n. Local l Local scope variables, function parameters l Scope begins at declaration, ends

n. Local l Local scope variables, function parameters l Scope begins at declaration, ends at right brace l Variable created when program enters its block l Variable invalid when program leaves block l Variable destroyed when program reaches the right brace of this block

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // using arguments and parameters. #include <iostream> using namespace std; void showavg ( int, float & ); int main() { float cf=1. 2; int j; for ( j = 1; j <= 5; j++ ) { int i = 9; showavg( i, j, cf ) ; // function call cout <<i << endl << cf <<endl } return 0; //successful termination } // end main Create a new block, giving i block scope. When the block ends (the program reaches the right brace of the block), this i is destroyed. Local scope starts from declaration void showavg (int num 1, int num 2 , float & avg) { avg = float(num 1 + num 2)/2; } // end of function Local variable will be invalid when the program leaves main for showavg. i num 1

n. Global l Global scope variables (constants), function definitions and prototypes l Defined outside

n. Global l Global scope variables (constants), function definitions and prototypes l Defined outside of any function in a file l Scope begins at declaration, ends at the end of this file l Variable created when program starts l Variable is valid from its declaration to the end of this file. l Variable destroyed when program ends

1 // using global variables. 2 #include <iostream> 3 using namespace std; 4 5

1 // using global variables. 2 #include <iostream> 3 using namespace std; 4 5 double c_area( int ); 6 const double pi = 3. 14; 7 8 int main() 9 { 10 cout << “When pi is " << pi <<endl; 11 12 for ( int x = 1; x <= 10; x++ ) 13 cout << c_area( x ) << " "; 14 cout << endl; 15 return 0; 16 } // end main 17 18 double c_area( int radius) 19 { 20 return radius * pi; 21 } // end function square 1 // using global variables. 2 #include <iostream> 3 using namespace std; 4 5 const double pi = 3. 14; 6 7 double c_area( int radius) 8 { 9 return radius * pi; 10 } // end function square 11 12 int main() 13 { 14 cout << “When pi is " << pi <<endl; 15 16 for ( int x = 1; x <= 10; x++ ) 17 cout << c_area( x ) << " "; 18 cout << endl; 19 return 0; 20 } // end main 21

l. Thinking End of local block End of file No Yes

l. Thinking End of local block End of file No Yes

n. Name l When precedence a function declares a local identifier with the same

n. Name l When precedence a function declares a local identifier with the same name as a global identifier, the local identifier takes precedence within the function. l 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

1 // using name precedence. 2 #include <iostream> 3 using namespace std; 4 5 double c_area( int ); 6 const double pi = 3. 14; 7 8 int main() 9 { 10 cout << “When pi is " << pi <<endl; 11 13 cout << c_area(10 ) << " "; 14 cout << endl; 15 return 0; 16 } // end main 17 18 double c_area( int radius) 19 { 20 int pi = 3; 20 return radius * pi; 21 } // end function square pi 3. 14 main pi 3 c_area

When pi is 3. 14 300

When pi is 3. 14 300

n. Static variable l Variables exist for entire program l Static local variables in

n. Static variable l Variables exist for entire program l 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. 2 #include <iostream> 3 using namespace std; 4 void

1 // using local static. 2 #include <iostream> 3 using namespace std; 4 void use. Static. Local( ) 5 6 int main() 7 { 8 for ( int x = 1; x <= 10; x++ ) 9 use. Local( ); 10 return 0; 11 } // end main 12 13 void use. Local ( ) 14 { 15 // initialized only first time use. Static. Local is called 16 int y = 50; 17 18 cout << "local x is " << y ++ << endl; 19 } // end function use. Static. Local main use. Local Y=50 51 … 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

1 // using local static. 2 #include <iostream> 3 using namespace std; 4 void

1 // using local static. 2 #include <iostream> 3 using namespace std; 4 void use. Static. Local( ) 5 6 int main() 7 { 8 for ( int x = 1; x <= 10; x++ ) 9 use. Static. Local( ); 10 return 0; 11 } // end main 12 13 void use. Static. Local ( ) 14 { 15 // initialized only first time use. Static. Local is called 16 static int y = 50; 17 18 cout << "local static x is " << y ++ << endl; 19 } // end function use. Static. Local main use. Static. Local Y=50 51 use. Static. Local 52 use. Static. Local 53 … 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

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

n. Inline function l Inline functions ¡ Keyword inline before function ¡ Asks the

n. Inline function l Inline functions ¡ Keyword inline before function ¡ Asks the compiler to copy code into program instead of making function call Reduce function-call overhead l Compiler can ignore inline l ¡ Good for small, often-used functions l Example inline double cube( const double s ) { return s * s; } tells compiler that function does not modify s ¡ const

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Using an inline function to calculate. #include <iostream> using namespace std; // Definition of inline function cube. Definition of function // appears before function is called, so a function prototype // is not required. First line of function definition acts as // the prototype. inline double cube( const double side ) { return side * side; // calculate cube } // end function cube int main() { double side. Value; cout << "Enter the side length of your cube: "; cin >> side. Value; // calculate cube of side. Value and display result cout << "Volume of cube with side " << side. Value << " is " << cube( side. Value ) << endl; return 0; // indicates successful termination } // end main

Enter the side length of your cube: 3. 5 Volume of cube with side

Enter the side length of your cube: 3. 5 Volume of cube with side 3. 5 is 42. 875

n. Function l Function overloading ¡ Functions with same name and different parameters ¡

n. Function l Function overloading ¡ Functions with same name and different parameters ¡ More general, should perform similar tasks l 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; } l Overloaded functions distinguished by signature ¡ Based on name and parameter types (order matters)

1 // Using function overloading to calculate. 2 #include <iostream> 3 using namespace std;

1 // Using function overloading to calculate. 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 The proper function is called 15 } // end function square based upon the argument (int 16 or double). 17 int main() 18 { 19 // calculate squre of side. Value 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

Square with side 2 is integer 4 Square with side 3. 2 is double 10. 24

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 3. 4: fig 03_04. cpp // Finding the maximum of three floating-point numbers. #include <iostream> using std: : cout; using std: : cin; using std: : endl; double maximum( double, double ); // function prototype int main() { double number 1; double number 2; double number 3; Function maximum takes 3 arguments (all double) and returns a double. cout << "Enter three floating-point numbers: "; cin >> number 1 >> number 2 >> number 3; // number 1, number 2 and number 3 are arguments to // the maximum function call cout << "Maximum is: " << maximum( number 1, number 2, number 3 ) << endl; return 0; // indicates successful termination

26 27 28 29 30 31 32 33 34 35 36 37 38 39

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 } // end main // function maximum definition; // x, y and z are parameters double maximum( double x, double y, double z ) { double max = x; // assume x is largest if ( y > max ) max = y; // if y is larger, // assign y to max if ( z > max ) max = z; // if z is larger, // assign z to max Comma separated list for multiple parameters. return max; // max is largest value } // end function maximum l. Enter three floating-point numbers: 99. 32 37. 3 27. 1928 l. Maximum is: 99. 32 l. Enter three floating-point numbers: 1. 1 3. 333 2. 22 l. Maximum is: 3. 333 l. Enter three floating-point numbers: 27. 9 14. 31 88. 99 l. Maximum is: 88. 99