1 / 50

Section 4 - Functions

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 in a program helps reduce the size of, and therefore simplifies, the program.

khenriksen
Télécharger la présentation

Section 4 - Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Section 4 - Functions

  2. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function in a program helps reduce the size of, and therefore simplifies, the program. Functions are also an important way to avoid the duplication of code. - Code that needs to be executed in more than one place can be factored out into a function. - Code duplication is a problem during program maintenance. When code is repeated in more than one place, it is easy to fix an error in one place and forget to fix it in others. - Encapsulating commonly used operations into functions also promotes the reuse of code from one program to another.

  3. Modular Programming • Modular programming - breaking a program up into smaller, manageable units – functions, methods, subroutine, … • Function - a collection of statements to perform a specific task • Motivation for modular programming: • Improves maintainability of programs • Simplifies the process of writing programs How may a large problem be split up into smaller, manageable units - Use the concept of Stepwise Refinement

  4. Stepwise Refinement One of the most powerful strategies for problem solving is the process of stepwise refinement. To solve a difficult task, break it down into simpler tasks. Then keep breaking down the simpler tasks into even simpler ones, until you are left with tasks that you know how to solve.

  5. Stepwise RefinementProblem: Making coffee COFFEE? I need coffee!

  6. Stepwise Refinement We will break this problem into steps (and for then those steps that can befurther broken, wewill break them) (and for then those steps that can befurther broken, wewill break them) (and for then those steps that can befurther broken, wewill break them) (and for then those steps that can befurther broken, wewill break them) … and so on… until the sub-problems are small enough to be just a few steps

  7. Stepwise Refinement This is the whole problem - this is like main(). I need to get coffee!

  8. Stepwise Refinement The whole problem can be broken into:if we can ask someone to give us coffee, we are donebut if not, we can make coffee (which we willhave to break into its parts) Beg?orMake?

  9. Stepwise Refinement The make coffee sub-problem can be broken into:if we have instant coffee, we can make thatbut if not, we can brew coffee(Maybe these will have parts!) OK.Iwill make it myself

  10. Stepwise Refinement Making instant coffee breaks into:1. Boil Water 2. Mix (Stir if you wish)(Do these have sub-problems?) Instant? Easy…

  11. Stepwise Refinement Boiling water appearsnot to be so easy.Many steps,but none have sub-steps. Boil water?Can I do that?

  12. Stepwise Refinement Going back to the branch betweeninstant or brew, we need to think about brewing.Can we break that into parts? OK.Iwill make it myself

  13. Stepwise Refinement Brewing coffee has several steps.Do any need more breakdown(Grind the coffee beans)? Or I can brew

  14. Stepwise Refinement Grinding is a two step processwith no sub-sub-steps. Grinding…Is that it?

  15. Stepwise Refinement Are wedone yet?

  16. Stepwise Refinement – The Complete Process Shown To write the“get coffee” program,you would write functionsfor each sub-problem.

  17. A function is a language construct for grouping statements together to perform some action. Using a function, you can write the code once for performing an action in a program and reuse it by many other programs. For example, often you need to find the maximum between two numbers. - Whenever you need this function, you would have to write the following code: int result; if (num1 > num2) result = num1; else result = num2;

  18. If you define these statements for finding a maximum number between any two numbers as a function, you do not have to repeatedly write the same code. You need to define it just once and reuse it by any other programs. A function is a sequence of instructions with a name. A function is invoked (or called) by another statement in order to have the function’s statement(s) executed. Example y = f(a); // call function f()

  19. A function call specifies - The function name - The name indicates what function is to be called y = f(a); - The data values(aka parameters)to be used in the call - The values are the data that the called functionrequires in order to do its task y = f(a); Example The sqrt function calculates the square root of a number supplied as a data value.

  20. A function call may produce a return value - The return value is the result of the function call - The return value may be assigned to a variable, output, etc. y = f(a);

  21. int main() { double z = pow(2, 3); ... } By using the expression pow(2, 3), the statement double z = pow(2, 3); in maincalls the pow function, asking it to compute 23. The execution of the main function is temporarily suspended. The statements of the pow() function execute and compute the result. The pow() function returns its result back to main, and the main function resumes execution. The values 2 and 3 are known as actual parameters

  22. Example • int main() • { • double z = pow(2, 3); • // display result of calculation • // stored in variable z • cout << z << endl; • // return from main • return 0; • }

  23. Defining and Calling Functions • Function call: a statement causes a function to execute • Function definition: statements that make up a function • A function definition is composed of • - Function header or signature • - Function body

  24. A function may accept data from the calling function in order to carry out its specific action. This data must be specified in the function definition and is known as formal parameters. When a function is called, the formal parameters take the values of the actual parameters

  25. A function is a collection of statements that are grouped together to perform an operation.

  26. Function Definition • Definition includes • return type: if the function returns a result to the calling statement, the data type of the value that function returns must be specified, otherwise void must be specified. • name: name of the function. Function names follow same rules as variables • parameter list: variables containing values passed to the function • body: statements that perform the function’s task, enclosed in {}

  27. Calling a Function • To call a function, use the function name followed by () and ; • printHeading(); • When called, the program executes the body of the called function • After the function terminates, execution resumes in the calling function after the point of call.

  28. Calling Process Flow of control is temporarily transferred to the invokedfunction - A correspondence is established between actual parameters ofthe call with the formal parameters of the function definition cout << "Enter number: "; double a; cin >> a; y = f(a); cout << y; Value of a is given to x double f(double x) { double result = x*x + 2*x + 5; return result; }

  29. Calling Functions • main() can call any number of functions • Functions can call other functions • Compiler must know the following about a function before it is called: • name • return type • number of parameters • data type of each parameter

  30. Function Prototypes • Ways to notify the compiler about a function before a call to the function: • Place function definition before calling function’s definition • Use a function prototype (function declaration) – like the function definition, but without the body • Prototype: void printHeading();

  31. Function Prototypes Before a function can be called from the program, its interface must be specified - Prototype or complete definition Type of value thatA description of the type the the function returnsparameters (if any) are to take FunctionType FunctionName ( ParameterList ) Identifier name of function int Max(int a, int b)

  32. Functions can be categorized into - Value-returning functions - Such functions must be defined with the return type - Non value-returning functions - Such functions must be defined with the keyword void instead of a return type.

  33. Function Return Type • If a function returns a value, the type of the value must be indicated • int main() • If a function does not return a value, its return type is void: • void printHeading() • { • cout << "\tMonthly Sales\n"; • }

  34. Value-Returning Functions • A value-returning function returns precisely one value after completing its assigned task • Value is returned to the statement that called function • Example • You use pow( ) to raise a number to a power and return result as a double number

  35. Passing Data by Value • Pass by value: when an argument is passed to a function, its value is copied into the parameter. • Changes to the parameter within the function do notaffect the value of the argument

  36. Passing Information to Parameters by Value • Example int val=5; • evenOrOdd(val); • evenOrOdd() can change variable num, but it will have no effect on variable val argument in calling function parameter in evenOrOdd function val num 5 5

  37. Functions use value parameter passing - Also known as pass by value or call by value The actual parameter is evaluated and a copy is given to the invoked function

  38. invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2

  39. The return Statement • Used to end execution of a function • Can be placed anywhere in a function • Statements that follow the return statement will not be executed • Can be used to prevent abnormal termination of program • Without a return statement, the function ends at its last statement

  40. Example - Returning a Boolean Value • Function can return true or false • Declare return type in function prototype and heading as bool • Function body must contain return statement(s) that return true or false • Calling function can use return value in a relational expression

  41. Boolean return Example bool validTest(int); // prototype bool validTest(int test) // header { int lScore = 0, hScore = 100; if (test >= lScore && test <= hScore) return true; else return false; } if (validTest(score)) {...} // call

  42. Parameters The parameters that are passed to a function are used to exchange information between the calling function and the one that is called. There are two kinds of parameters, value parameters and reference parameters.

  43. Function Called Formal parameters of the function definition are replaced by actual parameters or arguments cout << CircleArea(MyRadius) << endl; To process the call, the statement that contains the call is suspended and the CircleArea()function executes The cout statement is then completed using the value supplied by CircleArea()

  44. #include <iostream> using namespace std; float CircleArea(float r); // main(): manage circle computation int main() { cout << "Enter radius: "; float MyRadius; cin >> MyRadius; float Area = CircleArea(MyRadius); cout << "Circle has area " << Area; return 0; } // CircleArea(): compute area of radius r circle float CircleArea(float r) { const float Pi = 3.1415; return Pi * r * r; }

  45. Function Overloading A function name can be overloaded - Two functions with the same name but with different function definitions Typically this means different formal parameter lists - Difference in number of parameters Min(a, b, c) Min(a, b) - Difference in types of parameters Min(10, 20) Min(4.4, 9.2)

  46. Example int Min(int a, int b) { cout << "Using int min()" << endl; if (a > b) return b; else return a; } double Min(double a, double b) { cout << "Using double min()" << endl; if (a > b) return b; else return a; } int main() { int a = 10; int b = 20; double x = 4.4; double y = 9.2; int c = Min(a, b); cout << "c is " << c << endl; int z = Min(x, y); cout << "z is " << z << endl; return 0; }

  47. Function Overloading Compiler uses function overload resolution to call the most appropriate function First looks for a function definition where the formal and actual parameters exactly match If there is no exact match, the compiler will attempt to cast the actual parameters to ones used by an appropriate function The rules for function definition overloading are very complicated Advice Be very careful when using this feature

More Related