Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions, Interfaces, Parameters 8.1 – 8.2. include using namespace std; int main ( ) { int cal, fatGrams, fatCal; float fatPercent; cout << “enter the.

Similar presentations

Presentation on theme: "Functions, Interfaces, Parameters 8.1 – 8.2. include using namespace std; int main ( ) { int cal, fatGrams, fatCal; float fatPercent; cout << “enter the."— Presentation transcript:

1 Functions, Interfaces, Parameters 8.1 – 8.2

2 include using namespace std; int main ( ) { int cal, fatGrams, fatCal; float fatPercent; cout << “enter the number of calories”; cin >> cal; cout << “enter the number of fat grams;” cin >> fatGrams; fatCal = fatGrams * 9; fatPercent = (float(fatCal)/cal)*100; cout << “number of calories: “ << cal << endl; cout << “percent of calories from fat is: “ << fatPercent << endl; if fatCal < (.3 * cal) // or if fatCal<(fatPercent*cal/100) cout << “Your diet is lowfat!”; return 0; }

3 Use Indentation to Show Semantics if ( x < y) if ( y > 5) cout << “11111” << endl; else cout << “22222” << endl; cout << “33333” << endl; if ( x < y) if ( y > 5) cout << “11111” << endl; else // matches nearest “if” cout << “22222” << endl; cout << “33333” << endl;

4 Functions A function is a program unit Every C++ program must have a function called main() – Program execution always begins with this function Any other functions are subprograms, that must be called directly by the main program or another subprogram

5 Two Types of Functions Value-returning: receives data through its argument list, computes & returns a single value, is used as part of an expression. – y = 3.8 * sqrt(x); diff = fabs(x, y); Void: The function call is a separate stand-alone statement. – GetNextVal(x, y); // hypothetical function Void functions can make programs more readable and can also save coding time if you’re going to use the same code in several places.

6 Interfaces & Encapsulation A function’s interface is a description of what it does and how we communicate with it; i.e., – How we communicate: the parameter list, values that are “passed in” and values that may be “passed out”. – What the function does: What is the purpose of the function? How do we find out the result of executing the function? Functions as a “black box”: we don’t need to know anything about the implementation in order to use it in our programs; we only need to know how to use it.

7 Interfaces & Encapsulation Encapsulation: Hiding the implementation of a module in a separate unit or block with an interface, the only way a function communicates with the rest of the program. – Incoming values: passed from the caller to the function – Outgoing values: produced by the function & returned to the caller – Incoming/outgoing values: values that are passed into the function, changed by the function, and returned to the caller. If we know how to call the function and how to interpret the results, we don’t need to know any details of how the function works. (e.g., do you know how the length function works?)

8 Calling a Function One function calls another by using the name of the function followed by parentheses that enclose a (possibly empty) list of arguments. – Calls are either embedded in expressions, or as separate statements. A function call temporarily transfers control from the calling function to the called function – Thus functions are control statements like loops and decision statements.

9 Modules and Functions Functional decomposition is the process of reducing a big problem to set of smaller ones (modules) – This process may go through several levels When coded, a module is a set of instructions that has a single logical purpose (print a table, find smallest value in an array, …) When coded as a function, modules can only be executed by making a function call, which means you must know the function interface to use a function.

10 User-defined Functions: Control Flow (Figure 8.2 – page 360) Main Function A C B // prototypes int main() {... C(); B(); A(); C(); } void A() {... } void B() {... } void C() {... } Here is a program that has a main function and three subordinate functions (see the procedural decomposition above). Traditionally the main function is written first and the function definitions follow. Notice that the function calls, in main, aren’t necessarily in the same order as the function definitions. Also notice that the same function can be called more than once

11 Functional Decomposition with Void Functions A high-level algorithm is a decomposition of the program into tasks (modules) – You may have to decompose some tasks into smaller tasks – The process stops when you have identified tasks that represent a single logical operation When the process stops, each module/task is coded as a separate void function. Advantages of this approach: – Program development is easier. Write main() first – it should mostly be an outline of the program: a series of function calls – Develop functions 1 or 2 at a time, add in, test – Modular programs are easier to understand and modify – Modules may be reusable

12 Interfaces: Pre- and Post Conditions A good programming practice is to annotate functions with comments that explain what they do. Precondition: tells what must be true before the function is called. Postcondition: What must be true after the function completes.

13 Void Functions: Syntax & Semantics Function call – A function must be called in order to run: FunctionName(arguments); Function declaration & definitions – A function must be declared before it is called: FunctionName(parameters); //prototype – A function definition is similar to the prototype but also includes a header statement (similar to the prototype) & the body of the function – the actual code. Local variables

14 Return Statement (p. 366) Value returning functions have a return statement to tell what value is being returned. Normally, a void function doesn’t have a return value so you don’t need a return statement. Or, if you wish, you can just have a single statement: return; Exception: an abnormal exit from a function. – In case of error you may want to exit function immediately. See example on page 366 – Use of multiple function exits isn’t always considered a good practice as it can lead to confusion about function logic

15 Local Variables Local variables: a function can define its own variables, called local variables. – They are visible inside the function, but not otherwise – Storage for the variables is created when the function is called, destroyed when the function terminates. – Each function’s variables are private to that function, so you can use the same variable names in different functions and they will refer to different things.

16 //This program prints a “Welcome Home” message #include using namespace std; void PrintLines(int numLines); // function prototype // numLines = parameter representing number of lines of // asterisks to print int main() { PrintLines(2); // function call: argument = 2 cout << “Welcome Home!” << endl; PrintLines(4); // function call: argument = 4 return 0; } // ************************************************* void PrintLines(int numLines) // function definition { for (int count = 1; count <= numLines; count++) cout << “********************” endl; } // note: no return value; this is a void function.

17 Program to print a “welcome home” message page 361 //This program prints a “Welcome Home” message #include using namespace std; void PrintLines(int numLines); // prototype // numLines = parameter representing of lines of // asterisks to print int main() { PrintLines(2); // function call argument = 2 cout << “Welcome Home!” << endl; PrintLines(4); // function call: argument = 4 return 0; } // *********************************************** void PrintLines(int numLines) //function definition { for (int count = 1; count <= numLines; count++) cout << “********************” endl; } // note: void function means no return value. Function Prototype: declares the function name, gives parameters so the compiler will know how to process function calls. Prototype: followed by ‘;’ – but not in function definition. The parameter name is optional in the prototype Main function: notice how it gives an outline of what the program does, without giving details. PrintLines is called twice, with a different parameter each time Function definition: this is a void function; it does not return a value. Instead, it performs an operation (printing some lines of asterisks. The definition includes the function header with parameter list: data type, parameter name.

18 Function Names Since a void function is used like a program command, make the name sound like a command by including a verb – for example PrintLines() Follow the naming convention outlined earlier: user-defined functions capitalize the first letter of each word in the function name.

19 Parameters Make a function versatile, reusable The user supplies values/variables that will be used by the function when it executes Parameters are part of the interface to the function; you must understand what the parameters represent in order to use the function.

20 Parameters and Arguments Parameters are used in writing the function (for example numLines in the “welcome home” program). In a function call, arguments specify the actual variables/values that will be used when the function executes. There should be one argument for each parameter, and the types should match

21 Parameter Types Value parameter: A parameter that receives a copy of the value of the matching argument. Reference parameter: A parameter that receives the location (memory address) of the caller’s argument. How to declare in your program: void Example(int& param1,//reference int param2,//value float param3)// value

22 Value Parameters The parameter in the “Welcome Home” program is a value parameter. Possible ways to pass an argument to a value parameter: – PrintLines(2); // pass a literal value – PrintLines(num); //pass an int variable – PrintLines(2*x + y); // an expression In other words, anything that has a value can be passed; (i.e. ; any expression) The expression is evaluated and copied into the function parameter.

23 Parameter Correspondence Arguments and parameters must correspond in number and type. void myFun(int p1, float p2, char ltr) myFun(intVar, 15.25, charVar) For value parameters, the compiler will coerce an argument to match the parameter type if necessary. – E.g.: parameter is an int but your argument is a float. The argument will be coerced to an int.

24 Reference Parameters A reference parameter is declared with an ampersand (&) at the end of the parameter Instead of a value, the location (address) of the argument is passed to the function. In other words, the argument and the parameter refer to the same location in memory When the function completes, whatever value is in that location is available to the calling function. Reference parameters must match in type – no coercion will be done

25 #include using namespace std; void f1(float& fl, int x); int main() { float sal = ; int value = 10; fl( sal, value); cout << “sal = “ << sal << “ “; cout << “value = “ << value; return 0; } void f1(float& fl, int x) { f1 = f ; x = x * x; ) sal = value = 10

26 Arrays as Parameters pages Arrays are automatically passed as reference variables; don’t use the ampersand. When an array is passed its base address is passed – the address of the 1 st element. The function can then access all the elements. But … you must also tell it how many elements

27 Function with Array Parameter void ZeroOut(int anArray[ ], int n) Pre: anArray: int array with n elements Post: all elements of anArray are zero. { int i; // local variable for (i = 0; i < numElts; i++) anArray[i] = 0; } // Store 0 in all array elements

28 Passing Arrays as Arguments When you pass an array to a function you just use the array name (no index) For example, if your program has an array values that has MAX_SIZE elements, you would call zeroOut on it as follows: zeroOut(values, MAX_SIZE); NOT zeroOut(values[ ], MAX_SIZE);

29 Passing Individual Elements Sometimes you will only want to pass one or a few array elements. You can treat them as if they are any simple variables For a function with the following prototype: void f1(int x, int& y); and an array int myArray[10] the following function call is legal: f1(myArray[0], myArray[9])

30 Things to Remember Be sure you understand the interface to the functions: match parameters and arguments accurately. Also pay attention to semantics; Given the following function and function call void divide(int num, int div, int& quot) { quot = num / div; } & divide (bottom, top, answer); The call is syntactically correct, but if you meant to compute top/bottom it’s semantically incorrect.

31 More Things to Remember Parameter list in function definition must give data type of each variable and, if the parameter is a reference parameter, it must also have the ampersand. The function call does not have types or ampersands. A parameter should be a value parameter unless the function is designed to change the parameter permanently.

Download ppt "Functions, Interfaces, Parameters 8.1 – 8.2. include using namespace std; int main ( ) { int cal, fatGrams, fatCal; float fatPercent; cout << “enter the."

Similar presentations

Ads by Google