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.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Functions. COMP104 Functions / Slide 2 Introduction to Functions * A complex problem is often easier to solve by dividing it into several smaller parts,
Modular Programming With Functions
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Chapter 6: User-Defined Functions I
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Chapter 6: User-Defined Functions I
Functions A function is a snippet of code that performs a specific task or tasks. You use a multitude of functions daily when you do such things as store.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
1 Chapter 9 Scope, Lifetime, and More on Functions.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Functions Why we use functions C library functions Creating our own functions.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 ICS103 Programming in C Lecture 8: Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter 9: Value-Returning Functions
User-Written Functions
Chapter 6 - Functions modular programming general function format
Chapter 6: User-Defined Functions I
Methods Chapter 6.
Functions, Part 2 of 2 Topics Functions That Return a Value
Iterative Constructs Review
CMPT 201 Functions.
CSC113: Computer Programming (Theory = 03, Lab = 01)
CSCI 161: Introduction to Programming Function
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
User-Defined Functions
2011/11/20: Lecture 15 CMSC 104, Section 4 Richard Chang
Chapter 5 - Functions Outline 5.1 Introduction
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Chapter 9 Scope, Lifetime, and More on Functions
User Defined Functions
6 Chapter Functions.
Functions, Part 1 of 3 Topics Using Predefined Functions
Iterative Constructs Review
CPS120: Introduction to Computer Science
Chapter 6: User-Defined Functions I
Chapter 9: Value-Returning Functions
Functions, Part 1 of 3 Topics Using Predefined Functions
Predefined Functions Revisited
Functions, Part 1 of 3 Topics Using Predefined Functions
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Presentation transcript:

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

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

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

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

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.

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

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

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

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

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

Guess the output void confuse() { int i = 1; { cout << i << endl; int i = 9; 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

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 1 2 3 b[1] b[3] b[4] b[5] b[8] b[7] b[6] b[0] b[2]

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[])

Step 5A. Coding Special characters \xB3 │ \xC4 ─ \xC5 ┼ TIC TAC TOE 1 2 3 1 │ │ ─┼─┼─ 2 │ │ 3 │ │ 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; . . . }

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

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

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;

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