270 likes | 290 Views
cmath. 9.0. double sqrt( double x) { . . . //y = x return y; }. 3.0. Lesson 5 Functions I.
E N D
cmath 9.0 . . . double sqrt( double x) { . . . //y = x return y; } 3.0 . . . Lesson 5Functions I • A function is a small program which accomplishes a specific task. For example, we invoke (call) the function, sqrt(x), in the library cmath to compute the square root of x int main() { . . . b = sqrt( 9.0); . . . }
Re-usability Once we implemented a function, we can invoke it many times in different parts of a program. Furthermore, if we put it in a library, we can let other programmers use it too. Eg, the functions defined in cmath.
A function that computes n!=123... n Store the input of the function Output of the function int fact(int n) { int i, f = 1; i = 1; while ( i<=n) { f = i * f; ++i; } return f; } • Thefunction name is fact, • It has one parameter, n, of typeint • It returns a value of type int
Invocation • To invoke a function for carrying out a task, write <function_name>( <argument_list> ) Eg, To invoke the factorial function, write fact( 5 ), fact( k ), fact( k+2 ) • Arguments are used to provide input to a function. An argument is an expression. It is evaluated when the function is invoked. The value is then passed to the function as the initial value of the corresponding parameter. • The return statement is used to terminate the execution of a function and to specify the output value of a function. Its general form is return <expression>;
5 120 int fact(int n) { int i, f = 1; i = 1; while ( i<=n) { f = i * f; ++i; } return f; } int main() { int i = 4, k; k = fact( i+1); . . . } • When fact( i+1) is evaluated, the execution of main() is suspended. The function fact( n) is activated. The argument,i+1, matches with the parameter, n. Its value, 5, becomes theinitial value of n. • When the while-loop in fact( n) terminates, f’s value is 120. This value is passed back to main() by the return statement and subsequently assigned to k. The execution of fact(n) ends and the execution of main() resumes.
Variables of main() i 4 int k int Variables/parameters of fact() n int 5 int i 6 1 f int 120 int main() { int i = 4, k; k = fact( i+1); . . . } 120 int fact(int n) { int i, f = 1; i = 1; while ( i<=n) { f = i * f; ++i; } return f; } . . .
The type of the returned value must be specified int fact(int n) { int i, f = 1; i = 1; while ( i<=n) { f = i * f; ++i; } return f; } • Use void to indicate that a function doesn’t return a value void print_temperature( double t) { cout << "The temperature in Centigrade is: " << t << endl; }
If a function does not return a value, its execution will be ended after the last statement is executed. No return statement is needed. In case we want to terminate the execution of the function before the last statement is executed, write a bare return statement. return; • A sample call to the function print_temperature( f); void print_temperature( double t) { cout << "The temperature in Centigrade is: " << t << endl; }
A function may have 0, 1, or more parameters. Eg, • The function rand() in cstdlib returns a random int value int rand() • The function pow( x, y) in cmath computes double pow( double x, double y) • main() is a function invoked by the Operating System when the execution of a program is launched. What is the type of its returned value? int
The scope of a variable is the portion of the program that the variable can be referred to. It is not allowed to refer to the variable beyond its scope. • The scope of a variable in a function starts from the declaration up to the end of the block it is declared (indicated by ‘}’). int fibon( int k) { int n; . . . int j; . . . { . . . int m; . . . } . . . } Scope of k and n Scope of j Scope of m
Scope of second i Shadowing If a second variable is declared in the scope of a variable of the same name, the accessibility of the first variable is blocked in the scope of the second variable . int fibon( int k) { int i, n; . . . int i; . . . } Scope of first i
Guess the output void confuse() { int i = 1; { cout << i << endl; int i = 9; cout << i << endl; } cout << i << endl; } The output is
The scope of a parameter is the entire body of the function • The variables declared in a function are local variables. • Two functions may have local variables of the same name. The two variables are different and do not intervene each other. int main () { int j = 3; scramble(); cout << j; return 0; } void scramble( ) { int j j = 0; } The output is
The lifetime of a variable is the period during which the variable is accessible • Each time when a function is invoked, a fresh set of memory cells is allocated to the parameters and the local variables. When the execution of the function ends, the memory cells are de-allocated. • The lifetime of a parameter is the entire period during which the function is being executed. • The lifetime of a local variable is the period during which its scope is being executed.
Pass by value • When a function is invoked, the argument(s) is evaluated. The resulting value is passed to the parameter of the function that matches the argument. The value becomes the initial value of the parameter. Later changes of the parameter’s value have no effect on the variable appeared as argument. void f() { int i = 3; scramble(i); cout << i+1 << endl; } void scramble( int i) { i = 0; } When f() is invoked, the output is
Modular Programming • A module is a logically self-contained part of a larger program. Each module is a function. • To develop a program for accomplishing a large task, first decompose the task into smaller sub-tasks. Next write a function for each sub-task. Test each function thoroughly. Finally, put all functions together to form a large program for the original task. Conduct an integration test. If any subtask is still too large, we can further subdivide it and implement a function for it in the same way.(Divide-and-conquer)
Key steps in developing a simple program • Work out the details of the requirement. What are the input and output? • Determine the key variables needed in the program. • Identify the subtasks. (Top-down) • Specify a function for each subtask. Describe • what it does • the parameters and their significances (input) • the return value (output) • Implement and test each functions (Bottom-up) • Integration: put all functions together to form a program that carries out the entire task.
Case Study: Develop a program for playing Tictactoe. • Step 1. Requirements • The rules of the game • Input: the square of next moves • Output: prompts and the game board • Who makes the first move? • Does the game check illegal moves? • Does the game check winning condition? • Interface Tic Tac Toe TIC TAC TOE 1 2 3 1 │ │ ─┼─┼─ 2 │ │ ─┼─┼─ 3 │ │ 1: Player X's move (give the row and column numbers): 1 1
1 2 3 1 2 3 b[0] b[1] b[2] b[3] b[4] b[5] b[6] b[7] b[8] • Step 2. Key variables char b[9]; //keep track of the board configuration, either ' ', 'O' or 'X' char player; //Current player, either 'O' or 'X' int row, column; //Coordinate of a move
Steps 3 and 4. Subtasks and functions • Print the game board • Check the winning condition • Check whether a move is legal. Set the game board if legal. • 0 row 3 • 0 column 3 • The square specified is empty void print_board( char b[]) bool iswin( char b[], char player) bool move(int r, int c, char player, char b[])
TIC TAC TOE 1 2 3 1 │ │ ─┼─┼─ 2 │ │ ─┼─┼─ 3 │ │ • Step 5A. Coding Special characters \xB3 │ \xC4 ─ \xC5┼ void print_board( char b[]) { cout << "\nTIC TAC TOE\n\n"; cout << " 1 2 3" << endl; cout << "1 " << b[0] << "\xB3" << b[1] << "\xB3" << b[2] << endl; cout << " \xC4" << "\xC5" << "\xC4" << "\xC5" << "\xC4" << endl; . . . }
b[0] b[1] b[2] 1 2 3 1 2 3 b[3] b[4] b[5] b[6] b[7] b[8] • Step 5B. Coding bool iswin( char b[], char p) { if (b[0] == p && b[1] == p && b[2] == p) return true; if (b[3] == p && b[4] == p && b[5] == p) return true; . . . return false; }
Step 5C. Coding bool move( int row, int col, char player, char b[]) { int i = (row-1)*3 + col - 1; if ( . . . && b[i] == ' ') { b[i] = player; return true; } cout << "Illegal move!!! " << "Give another square: "; return false; } • 0 row 3 • 0 column 3 • The square specified is empty
Step 5D. Coding The pseudo-code of main() Declare variables; Initialization: give initial values to the variables; Loop 9 times Print the game board; Prompt the player for a move repeatedly until a legal move is specified; Set the game board; Stop the game if the player wins; Alternate the players; End-loop Print the game board; Declare a tie;
Calling Sequences main() print_board() iswin() move()
The calling Sequence of a program that manipulates polynomials. main() readpoly() printpoly( p) addpoly( p, q) multpoly( p, q) addterm(p, t) Polynomial search(p, e)
Reading Assignment • Chapters 3 of the Text P. 109 - 156