Download presentation
Presentation is loading. Please wait.
Published byAshlynn Reeves Modified over 6 years ago
1
Lesson 5 Functions 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 cmath double sqrt( double x) { //y = x return y; } 9.0 int main() { b = sqrt( 9.0); } 3.0
2
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. double sqrt( double x) returns double exp( double x) double log( double x) returns the natural log, i.e., ln( x) double pow( double x, double y) double sin( double x) returns sin( x), x in radian double asin( double x) returns arc sine of x
3
A function that computes n!=123... n
int fact( int n) { int i, f = 1; i = 1; while ( i<=n) { f = i * f; ++i; } return f; Store the input of the function The function name is fact, It has one parameter, n, of type int It returns a value of type int Output of the function
4
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
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); . . . } 5 120 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 the initial 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.
6
i k 4 120 n 5 . i f 1 6 120 Variables of main() int main() {
int i = 4, k; k = fact( i+1); . . . } i k int 4 120 int fact( int n) { int i, f = 1; i = 1; while ( i<=n) { f = i * f; ++i; } return f; Variables/parameters of fact() n int 5 . i f int 1 6 120
7
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; }
8
A sample call to the function
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; }
9
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
10
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
11
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 Scope of second i
12
Guess the output void confuse() { int i = 1;
{ cout << i << endl; int i = 9; cout << i << endl; } The output is
13
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
14
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.
15
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
16
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)
17
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.
18
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
19
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 1 2 3 b[1] b[3] b[4] b[5] b[8] b[7] b[6] b[0] b[2]
20
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[])
21
Step 5A. Coding Special characters \xB3 │ \xC4 ─ \xC5 ┼
TIC TAC TOE 1 2 3 1 │ │ ─┼─┼─ 2 │ │ 3 │ │ Special characters \xB3 │ \xC4 ─ \xC ┼ void print_board( char b[]) { cout << "\nTIC TAC TOE\n\n"; cout << " " << endl; cout << "1 " << b[0] << "\xB3" << b[1] << "\xB3" << b[2] << endl; cout << " \xC4" << "\xC5" << "\xC4" << "\xC5" << "\xC4" << endl; }
22
Step 5B. Coding 1 2 3 1 2 3 b[1] b[3] b[4] b[5] b[8] b[7] b[6] b[0]
1 2 3 b[1] b[3] b[4] b[5] b[8] b[7] b[6] b[0] b[2] 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; }
23
Step 5C. Coding 0 row 3 0 column 3
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
24
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 Declare a tie;
25
Calling Sequences main() print_board() iswin() move()
26
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)
27
Reading Assignment Chapters 3 of the Text P
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.