Lesson 5 Functions I A function is a

  • Slides: 27
Download presentation
Lesson 5 Functions I Ø A function is a small program which accomplishes a

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 int main() {. . . b = sqrt( 9. 0); . . . } 9. 0 cmath. . . double sqrt( double x) {. . . //y = x return y; } 3. 0 . . . 1

Ø Re-usability Once we implemented a function, we can invoke it many times in

Ø 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) double exp( double x) double log( double x) double pow( double x, double y) returns the natural log, i. e. , ln( x) returns double sin( double x) double asin( double x) returns sin( x), x in radian returns arc sine of x 2

A function that computes n!=1 2 3. . . n int fact( int n)

A function that computes n!=1 2 3. . . 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 3

Invocation Ø To invoke a function for carrying out a task, write <function_name>( <argument_list>

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+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>; 4

int main() { int i = 4, k; k = fact( i+1); . .

int main() { int i = 4, k; k = fact( i+1); . . . } 5 int fact( int n) { int i, f = 1; 120 } i = 1; while ( i<=n) { f = i * f; ++i; } return f; Ø 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 5 execution of main() resumes.

int main() { int i = 4, k; Variables of main() i k 4

int main() { int i = 4, k; Variables of main() i k 4 120 int k = fact( i+1); . . . } int fact( int n) { int i, f = 1; . . . } i = 1; while ( i<=n) { f = i * f; ++i; } return f; Variables/parameters of fact() n i f 5 6 1 120 int int 6

Ø The type of the returned value must be specified int fact( int n)

Ø 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; } 7

Ø If a function does not return a value, its execution will be ended

Ø If a function does not return a value, its execution will be ended after the last statement is executed. No return statement is needed. void print_temperature( double t) { cout << "The temperature in Centigrade is: " << t << endl; } 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); 8

Ø A function may have 0, 1, or more parameters. Eg, ØThe function rand()

Ø 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 9

Ø The scope of a variable is the portion of the program that the

Ø 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; . . . Scope of k and n int j; . . . Scope of j { . . . int m; . . . Scope of m }. . . } 10

Shadowing If a second variable is declared in the scope of a variable of

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 } 11

Ø Guess the output void confuse() { int i = 1; { cout <<

Ø Guess the output void confuse() { int i = 1; { cout << i << endl; int i = 9; cout << i << endl; } The output is } cout << i << endl; 12

Ø The scope of a parameter is the entire body of the function Ø

Ø 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; The output is } void scramble( ) { int j j = 0; } 13

Ø The lifetime of a variable is the period during which the variable 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. 14

Ø Pass by value When a function is invoked, the argument(s) is evaluated. The

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

Modular Programming Ø A module is a logically self-contained part of a larger program.

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) 16

Key steps in developing a simple program 1. Work out the details of the

Key steps in developing a simple program 1. Work out the details of the requirement. What are the input and output? 2. Determine the key variables needed in the program. 3. Identify the subtasks. (Top-down) 4. Specify a function for each subtask. Describe Ø what it does Ø the parameters and their significances (input) Ø the return value (output) 5. Implement and test each functions (Bottom-up) 6. Integration: put all functions together to form a program that carries out the entire task. 17

Case Study: Develop a program for playing Tictactoe. Ø Step 1. Requirements Ø The

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 │ │ 18 1: Player X's move (give the row and column numbers): 1 1

Ø Step 2. Key variables char b[9]; char player; //keep track of the board

Ø Step 2. Key variables char b[9]; char player; //keep track of the board configuration, either ' ', 'O' or 'X' //Current player, either 'O' or 'X' int row, column; //Coordinate of a move 1 2 3 1 b[0] b[1] b[2] 2 b[3] b[4] b[5] 3 b[6] b[7] b[8] 19

Ø Steps 3 and 4. Subtasks and functions 1. Print the game board void

Ø Steps 3 and 4. Subtasks and functions 1. Print the game board void print_board( char b[]) 2. Check the winning condition bool iswin( char b[], char player) 3. Check whether a move is legal. Set the game board if legal. Ø 0 row 3 Ø 0 column 3 Ø The square specified is empty bool move(int r, int c, char player, char b[]) 20

Ø Step 5 A. Coding Special characters x. B 3 x. C 4 x.

Ø Step 5 A. Coding Special characters x. B 3 x. C 4 x. C 5 │ ─ ┼ TIC TAC TOE 1 2 3 1 │ │ ─┼─┼─ 2 │ │ ─┼─┼─ 3 │ │ void print_board( char b[]) { cout << "n. TIC TAC TOEnn"; cout << " 1 2 3" << endl; cout << "1 " << b[0] << "x. B 3" << b[1] << "x. B 3" << b[2] << endl; cout << " x. C 4" << "x. C 5" << "x. C 4" << endl; . . . } 21

Ø Step 5 B. Coding 1 2 3 1 b[0] b[1] b[2] 2 b[3]

Ø Step 5 B. Coding 1 2 3 1 b[0] b[1] b[2] 2 b[3] b[4] b[5] 3 b[6] b[7] b[8] 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; } 22

Ø Step 5 C. Coding bool move( int row, int col, char player, {

Ø Step 5 C. Coding bool move( int row, int col, char player, { int i = (row-1)*3 + col - 1; if (. . . && b[i] == ' ') { b[i] = player; return true; } char b[]) 0 row 3 0 column 3 The square specified is empty cout << "Illegal move!!! " << " Give another square: "; return false; } 23

Ø Step 5 D. Coding The pseudo-code of main() Declare variables; Initialization: give initial

Ø Step 5 D. 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; 24

Ø Calling Sequences main() print_board() iswin() move() 25

Ø Calling Sequences main() print_board() iswin() move() 25

Ø The calling Sequence of a program that manipulates polynomials. main() readpoly() printpoly( p)

Ø 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) 26

Reading Assignment Ø Chapters 3 of the Text P. 109 - 156 27

Reading Assignment Ø Chapters 3 of the Text P. 109 - 156 27