Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

Slides:



Advertisements
Similar presentations
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 5 Functions.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 5. Functions.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
1 Lecture 6 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 6: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Chapter 6: User-Defined Functions I
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Basic Elements of C++ Chapter 2.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Functions.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Lecture 9m: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.
CPS120: Introduction to Computer Science Functions.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
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.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
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.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
Chapter 9: Value-Returning Functions
Chapter 6: User-Defined Functions I
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Chapter 7: User-Defined Functions II
User-Defined Functions
بسم الله الرحمن الرحيم.
Chapter 6: User-Defined Functions I
Predefined Functions Revisited
Presentation transcript:

Chapter 9 Functions Dept of Computer Engineering Khon Kaen University

178110: Computer Programming (II/2546) 2 Introduction Most useful programs are much larger than the programs we have considered so far To make large program manageable, programmers modularise them into subprograms They can be compiled and tested separately and reused in different programs

178110: Computer Programming (II/2546) 3 Standard C++ Library Functions The standard C++ library is a collection of pre-defined functions and other program elements which are accessed through header files

178110: Computer Programming (II/2546) 4 The Square Root Function #include // define sqrt() function #include // define cout using namespace std; int main() { int x = 4; double y = sqrt(x); // calling a function by using its name cout << “sqrt(“ << x << “) = “ << y << endl; } sqrt(4) = 2

178110: Computer Programming (II/2546) 5 y = sqrt(x) The expression x in the () is called the argument or actual parameter of the function call and we say that it is passed by value to the function Black box sqrt() main() x y int double

178110: Computer Programming (II/2546) 6 Mathematical Functions Most of the mathematical functions that you find on a pocket calculator are declared in the header file. The examples of these functions are sin(x), cos(x), tan(x), asin(x), acos(x), etc. floor(x), ceil(x) fabs(x), abs(x) sqrt(x), pow(x,p), log(x)

178110: Computer Programming (II/2546) 7 Useful Header Files in C++ : Defines mathematical functions : Defines functions for standard input and output : Defines utility functions : Defines functions for processing strings : Defines time and date functions To learn how to use functions in these files,

178110: Computer Programming (II/2546) 8 User-defined Functions Programmers also need to be able to define their own functions A user-defined function has two parts: its head and its body The syntax of the head of a function is: return-type func_name(parameter-list) The body of a function is the block of code that follows its head

178110: Computer Programming (II/2546) 9 Return Statement return expression; A functions’ return statement serves two purposes: It terminates the execution of the function It returns a value to the calling program Where expression is any expression whose value could be assigned to a variable whose type is the same as the function’s return type

178110: Computer Programming (II/2546) 10 Sample User-Defined Function int cube(int x) { return x*x*x; } What is each part of the function called? What is returned from executing ‘cube(2)’? Can the function return nothing?

178110: Computer Programming (II/2546) 11 Test Drivers Whenever you create your own functions, you should immediately test it with a simple program Such program is called a test driver Why do we need to immediately test each function that we just define? What is the main concept behind designing a test driver?

178110: Computer Programming (II/2546) 12 Sample Test Driver int cube(int x) { return x*x*x;} int main() { int n = 1; while (n != 0) { cin >> n; cout << “\tcube(“ << n << “) = “ << cube(n) << endl; } What is the output if n = 2, 3, 4? Can we write a better program?

178110: Computer Programming (II/2546) 13 Sample Test Driver int max(int x, int y) { // return a larger # if (x < y) return y; else return x; } int main() { // test the max() function int m, n; do { cin >> m >> n; cout << “max (“ << m << “,” << n <<“) = “ << max(m,n) << endl; } while (m != 0); }

178110: Computer Programming (II/2546) 14 Function Declaration & Definition Function declaration lists only the header of the function to provide the compiler with all information it needs to compile the rest of the function Ex: int max(int m, int n) Function definition needs to include both the header and the body of the function Ex: int max(int m, int n) { if (x < y) return y; else return x;}

178110: Computer Programming (II/2546) 15 Parameters vs. Arguments Parameters are variables that are listed in the function’s parameter list int max(int m, n) Arguments are variables that are listed in the function’s calls int main() { int m = 2, n = 3; int max_number = max(m, n); }

178110: Computer Programming (II/2546) 16 Local Variables & Functions A local variable is simply a variable that is declared inside a block and can then be accessed only from within that block Since the body of a function itself is a block, variables declared within a function are local variables to that function; they exist only while the function is executing Are function’s formal parameters regarded as being local to the function?

178110: Computer Programming (II/2546) 17 Sample Local Variables long fact(int n) { if (n < 0) return 0; int f = 1; while (n > 1) f*= n--; return f; } int main() { long f = fact(2); } Which variables are local variables in function ‘fact’?

178110: Computer Programming (II/2546) 18 Void Function A function does not need to return a value In C++, such a function is identified simply by placing the keyword void where the function’s return type would be It does not need to include a return statement. If it does have a return statement, then it should appear simply as return; Do we need to do ‘return;’ at the end of the function?

178110: Computer Programming (II/2546) 19 Sample Function with Void void printMonth(int); int main() { printMonth(1); } void printMonth(int m) { if (m 12) cerr << “Error”; return; switch (m) { case 1: cout << “January”; break; … }

178110: Computer Programming (II/2546) 20 Boolean Functions In some situations, it is helpful to use a function to evaluate a condition, typically within an if or a while statement bool isLeapYear(int y) { return (y%4 == 0 && y%100 != 0 || y%400 == 0); } int main() { if (isLeapYear(2004)) cout << “2004 is a leap year\n”; }

178110: Computer Programming (II/2546) 21 I/O Functions We have already seen examples of output functions that send information to the standard output The next example illustrates an input example How to write a function that prompts the user for his/her age and that keeps asking for the number until it is the range of 0 to 120?

178110: Computer Programming (II/2546) 22 Robust I/O Function int age() {int n; while (true) { cout << “How old are you:”; cin >> n; if (n < 0) cout << “Your age could not be negative\n”; else if (n > 120) cout << “Your age could not be over 120\n”; else return n;}} int main() { cout << “You are “ << age() << “ years old” << endl;}

178110: Computer Programming (II/2546) 23 Passing by Value vs. by Reference Pass-by-value (value parameters) The values of variables are passed. The values of variables are read-only; they do not change when they are referred outside the function Pass-by-reference (reference parameters) The addresses of variables are passed. The values of variables are read-write; they can be modified and this modification is still in effect even at outside the function

178110: Computer Programming (II/2546) 24 Sample Pass by Value vs. by Reference void swap(float x, float y) { float temp =x; x = y; y = temp; } int main() { float a = 22.2, b = 44.4; cout << “a = “ << a << “ b = “ << b << endl; swap(a, b); cout << “a = “ << a << “ b = “ << b << endl; } What is the output?

178110: Computer Programming (II/2546) 25 Sample Pass by Value vs. by Reference void swap(float &x, float &y) { float temp =x; x = y; y = temp; } int main() { float a = 22.2, b = 44.4; cout << “a = “ << a << “ b = “ << b << endl; swap(a, b); cout << “a = “ << a << “ b = “ << b << endl; } What is the output?

178110: Computer Programming (II/2546) 26 Sample Pass by Value vs. by Reference void f(int x, int &y) { x = 88; y = 99;} int main() { int a = 22, b = 44; cout << “a = “ << a << “, b = “ << b << endl; f(a,b); cout << “a = “ << a << “, b = “ << b << endl; f(2*a-3, b); cout << “a = “ << a << “, b = “ << b << endl;} What is the output?

178110: Computer Programming (II/2546) 27 Pass by Value vs. by Reference Passing by ValuePassing by Reference int x;int &x; x is a local variablex is a local reference x is a duplicate of the argument x is a synonym for the argument Argument cannot changeArgument can change Arg can be a constant, a variable, an expression Argument is a variable Argument is read-onlyArgument is read- write

178110: Computer Programming (II/2546) 28 When to Pass by Reference? Besides when we want to change the variables after the function returns to the calling function How to return more than one value from the function? How to write a function that accepts a radius of a circle and returns the area and the circumference of a circle whose radius ahs the given length r?

178110: Computer Programming (II/2546) 29 Sample Pass by Reference void computeCircle(double &area, double &circumference, double r) { const double PI = ; area = PI*r*r; circumference = 2*PI*r; } int main() { double r, a, c; cout << “Enter radius: “; cin >> r; computeCircle(a, c, r); cout << “ area = “ << a << “ circumference = “ << c << endl; }

178110: Computer Programming (II/2546) 30 Passing by Constant Reference If you don’t want the function to change its content (for example, if the purpose of the function is to print the object), then passing by reference can be risky Passing by constant reference works the same way as passing by reference, except that the function is prevented from changing the value of the parameter In which case, we prefer to pass by constant reference over pass by value?

178110: Computer Programming (II/2546) 31 Sample Pass by Value vs. by Reference void f(int x, int &y, const int &z) { x+= z; y += z; cout << “x = “ << x << “, y = “ << y << “, z = “ << z << endl;} int main() { int a = 22, b = 33, c = 44; cout << “a = “ << a << “, b = “ << b << “, c = “ << c << endl; f(a,b,c); cout << “a = “ << a << “, b = “ << b << “, c = “ << c << endl; f(2/a-3,b,c); cout << “a = “ << a << “, b = “ << b << “, c = “ << c << endl; }

178110: Computer Programming (II/2546) 32 Inline Functions Do we always want to call a function? A function call involves substantial overhead. Extra time and space have to be used to invoke the function, pass parameters to it, allocate storage for its local variables, store the current variables and the location of execution in the main program In some cases, it is better to avoid all of this by specifying the function to be inline

178110: Computer Programming (II/2546) 33 Inline Functions (Cont.) Inline functions tell the compiler to replace each call to the function with explicit code for the function To the programmer, an inline function appears the same as an ordinary function, except for the use of the inline function

178110: Computer Programming (II/2546) 34 Sample Inlining Function inline int cube(int x) { return x*x*x;} int main() { cout << cube(4) << endl; int x, y; cin >> x; y = cube(2*x – 3); } cout << cube(4) …  cout << 4*4*4 … y = cube(2*x-3)  y = (2*x-3)*(2*x-3)*(2*x-3);

178110: Computer Programming (II/2546) 35 Scope The scope of a name consists of that part of the program where it can be used It beings where the name is declared If that declaration is inside a function then the scope extends to the end of the innermost block contains the declaration A program can have several objects with the same name if their scopes are nested or disjoint

178110: Computer Programming (II/2546) 36 Sample Scopes int x = 11;// global variable x int main() { int x = 22; { int x = 33; cout << “In block1 x = “ << x << endl;} {int x = 44; cout << “In block2 x = “ << x << endl;} cout << “x = “ << x << “ ::x = “ << ::x << endl;} What is the output?

178110: Computer Programming (II/2546) 37 Sample Scopes and Functions int x = 11; void f() { int x = 44; cout << “In f(): x = “ << x << endl;} void g() {cout << “In g(): x = “ << x << endl;} int main() { int x = 22; cout << “In main x = “ << x << endl; f(); g(); } What is the output?

178110: Computer Programming (II/2546) 38 Overloading C++ allows you to use the same function name for different functions as long as they have different parameter type lists Two parameter lists are different if They contain a different number of parameter Or there must be at least one position in their parameter lists where the types are different

178110: Computer Programming (II/2546) 39 Sample Overloading Program #include using namespace std; int max(int, int); int max(int, int, int); int main() { cout << max(99,77) << " " << max(55, 66, 33); } int max(int x, int y) { return (x > y? x: y); } int max(int x, int y, int z) { int m = (x > y ? x: y); return (z > m? z:m); }

178110: Computer Programming (II/2546) 40 The main Function A Complete C++ program is a program made up of the main() function together with all other functions that are called either directly or indirectly from it main() is a function with return type int, it is normal to end its block with return 0; int main() { return 0;}

178110: Computer Programming (II/2546) 41 Using ‘return’ to Terminate a Program If ‘return’ is called in a main function, it is used to terminate a program int main() { int n, d; cout << “Enter two integers:”; cin >> n >> d; if (d == 0) return 0; cout << n << “/” << d << “ = “ << n/d << endl; } What are the outputs when n=99, d = 17 and when n = 99, d = 0?

178110: Computer Programming (II/2546) 42 Terminating a Program Abnormally There are many ways to terminate a program abnormally, such as Use a return statement in main() Example: int main() { return 1; } Call the exit() function Example: int main() {exit(1); } Call the abort() function Example: int main() { abort(); }

178110: Computer Programming (II/2546) 43 Default Arguments In C++, the number of arguments that a function has can vary during run-time This is done by providing default values for the optional arguments All default argument names of a function are bound when the function is declared All functions have their types checked at declaration, and are evaluated at each point of call

178110: Computer Programming (II/2546) 44 Evaluating C++ Default Arguments When a function defined with default arguments is called with trailing arguments missing, the default expressions are evaluated void f(int a, int b = 2, int c = 3); // declaration f(a); // same as call f(a, 2, 3) f(a,10); // same as call f(a,10,3) f(a,10,20); // no default arguments

178110: Computer Programming (II/2546) 45 Sample Default Arguments double p(double x, double a0, double a1 = 0, double a2 = 0) { return a0 + (a1 + a2*x)*x;} int main() { double x = 2; cout << “p(x,2) = “ << p(x,2) << endl; cout << “p(x,2,3) = “ << p(x,2,3) << endl; cout << “p(x,2,3,4) = “ << p(x,2,3,4) << endl;} What is the output?

178110: Computer Programming (II/2546) 46 Reviews What are functions? Why do need them? What are the header and the body parts of functions? Function declaration vs. function definition Parameters vs. arguments Passed by values vs. pass by references Terminating functions and programs Default arguments