Download
function n.
Skip this Video
Loading SlideShow in 5 Seconds..
Function PowerPoint Presentation

Function

325 Vues Download Presentation
Télécharger la présentation

Function

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Function

  2. Function • Introduction • Library function • New defined function • Random number generator • Scope • Inline function • Function overload

  3. Introduction • Why do we need function? • Reuse and simplify a large program. • Chapter 7 and Chapter 8 (p309-p436)

  4. 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 return0; // indicates successful termination 12 13 } // end main 14 123

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

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

  7. 1 // using math library function. 2 #include <iostream> 3 #include <cmath> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 // loop 10 times and calculate and output 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 return0; // indicates successful termination 18 } // end main Head file. Parentheses () cause function to be called. When the call done, the function result will be provided. 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5,

  8. 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() 9 { 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 elsecout << x << “, "; 15 } 16 cout << endl; 17 18 return0; // indicates successful termination 19 } // end main Without function call, the program needs implementation of abs here. 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5,

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

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

  11. 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).

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

  13. ****************************** ****************************** Welcome! ****************************** ******************************

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

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

  16. ****************************** AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Welcome! AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ****************************** • Thinking? • Do we need two different functions?

  17. 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 similar tasks. • 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.

  18. 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?

  19. 1 // using list of arguments and parameters, argument promotion. 2 #include <iostream> 3 using namespace std; 4 voidshowavg ( int, int ); 5 6 int main() 7 { 8 showavg (9, 8); 9 showavg (7, 4); 10 return0; //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 We tried 9 and 8. We tried 7 and 4 Instead of x and y (or a and b), I used num1 and num2.

  20. 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. }

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

  22. ****************************** AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Welcome! AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ******************************

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

  24. 1 // using argument and parameter. 2 #include <iostream> 3 using namespace std; 4 voidprint_one_line (char ); 5 6 int main() 7 { 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 return0; // indicates successful termination 15 } // end main 16 17 void print_one_line ( char ch ) 18 { 19 int i; 20 for ( int x = 1; x <= 30; x++ ) 21 cout << ch; 22 cout << endl; 23 } // end of function Constants, ‘*’ is passed to parameter, one line ‘*’. Variable, its value ‘A’ is passed to parameter, one line ‘A’. Expression, its value ‘B’ is evaluated and passed to parameter, one line ‘B’.

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

  26. ****************************** AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Welcome! BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB ******************************

  27. Argument and parameter • Advanced format (Prototype, Call, and 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.

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

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

  30. Real Case (A company and its delivery) Company Guy of delivery service Call delivery service Product = ‘*’ His job is to handle (deliver) this ٱ. ‘*’ Control goes back (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.)

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

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

  33. void my_function ( ); //function prototype int main( ) { my_function( ); //function call return 0; } void my_function ( ) //function definition { } int k int x , int , m , int y int k=3, m =4 ;

  34. 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).

  35. 1 // using argument and parameter. 2 #include <iostream> 3 using namespace std; 4 voidprint_one_line (char ); 5 6 int main() 7 { 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 (‘*’ ); 14 return0; 15 } // end main 16 17 void print_one_line ( char ch ) 18 { 19 int i; 20 for ( int x = 1; x <= 30; x++ ) 21 cout << ch; 22 cout << endl; 23 } // end of function main function ch constant value ‘*’ ‘*’ value of variable c ‘A’ ch ‘A’ value of expression ‘B’ ch ‘B’ Sequence Diagram

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

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

  38. 1 // using reference parameter. 2 #include <iostream> 3 using namespace std; 4 voidshowavg ( int, int, float & ); 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 return0; //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 A variable in main. It will be used as reference argument. Datatype & Function call. No & here. The change of value of reference parameter. This change in function is brought to main by reference parameter. The change of value of value parameter won’t change the value of the argument variable i in main. 9 5.5

  39. main showavg i j num1 num2 avg, cf 9 2 1.2 9 2 cf 1. 2 num1 num2 avg, cf i j cf 2 2 5.5 9 2 5.5 Sequence Diagram

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

  41. 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;

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

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

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

  45. 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 27 z = sqrt(x); // returns square root of x as an float 28 } // end function square Definition of square. Returns the change of y and z to main by using reference parameter. 4, 1.4121; 9, 1.73205; 16, 2; 25, 2.23607;

  46. 24 int square( int y ) 25 { 26 return y * y; 27 28 } 24 void square_and_root( int x, int &y, float & z ) 25 { 26 y = x* x; 27 z = sqrt(x); 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

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

  48. ****************************** AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Welcome! BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB ****************************** 1 // using argument and parameter. 2 #include <iostream> 3 using namespace std; 4 voidprint_one_line (char ); 5 6 int main() 7 { 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 (‘*’ ); 14 return0; 15 } // end main 16 17 void print_one_line ( char ch ) 18 { 19 for ( int x = 1; x <= 30; x++ ) 20 cout << ch; 21 cout << endl; 22 } // end of function Type of argument Argument Parameter

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