Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

Similar presentations


Presentation on theme: "Chapter 9 Functions Dept of Computer Engineering Khon Kaen University."— Presentation transcript:

1 Chapter 9 Functions Dept of Computer Engineering Khon Kaen University

2 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

3 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

4 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

5 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 4 4 2 2 y int double

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

7 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, http://www.cplusplus.com/ref/

8 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

9 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

10 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?

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

12 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?

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

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

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

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

17 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’?

18 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?

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

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

21 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?

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

23 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

24 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?

25 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?

26 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?

27 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

28 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?

29 178110: Computer Programming (II/2546) 29 Sample Pass by Reference void computeCircle(double &area, double &circumference, double r) { const double PI = 3.14159265358979; 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; }

30 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?

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

32 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

33 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

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

35 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

36 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?

37 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?

38 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

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

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

41 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?

42 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(); }

43 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

44 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

45 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?

46 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


Download ppt "Chapter 9 Functions Dept of Computer Engineering Khon Kaen University."

Similar presentations


Ads by Google