Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.

Similar presentations


Presentation on theme: "Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition."— Presentation transcript:

1 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Revised 2015 EL Jones, FAMU,

2 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5 Passing Data by Value 6.6 The return Statement 6.7 Returning a Value from a Function 6.8 Returning a Boolean Value 6-2

3 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics (continued) 6.9 Using Functions in a Menu-Driven Program 6.10 Local and Global Variables 6.11 Static Local Variables 6.12 Default Arguments 6.13 Using Reference Variables as Parameters 6.14 Overloading Functions 6.15 The exit() Function 6.16 Stubs and Drivers 6-3

4 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 6 - Functions Part 1 (Modular Programming) 8-4

5 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection of statements to perform a specific task Motivation for modular programming –Simplifies the process of writing programs –Improves maintainability of programs 6-5

6 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A First Picture 6-6 int main //yours { ssssss } Mono-lithic int main //yours { ssssss } Poly-lithic (now) #include //others #include … int main //yours { ssssss } Poly-lithic (future) #include // others #include … module (… ) //yours { … }

7 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using Modules 6-7 int main //yours { float pi = 3.14159, sqrtPI; sqrtPI = sqrt(pi); cout << “square root of PI = “; << sqrtPI << endl; } Using C++ library modules #include #include <iostream int main //yours { int x, y; cin >> x >> y; cout << Sum(x,y) << endl; } Using your own modules #include // others #include … //Compute sum of two integers. int Sum (int a, int b) // yours { return a+b; }

8 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using Modules 6-8 int main //yours { string S; getline(cin, S); cout << “String= “ << S << endl; } Using C++ library modules #include #include <iostream int main //yours { string q = “HELLO, Joe”; Show(q); } Using your own modules #include // others #include … //Display string. void Show (string myStr) // yours { cout <<endl<< myStr << endl; }

9 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Modular Programming - Terminology A module has these characteristics –A job description (what it does) –Raw materials (called parameters) that must be provided to for the module to do its job. –Results produced by the function C++ functions that implement modules require: –Documentation of the job the function performs –An interface specification identifying the raw materials and results –A body that implements an algorithm to transform raw materials into results 6-9

10 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Your First Function 6-10 int main //yours { int a,b, x, y, s; cin >> x >> y >> a >> b; s = Sum(x,y); // CALL, invoke or activate function.. cout << “SUM1 = “ << s << endl; cout << “S2 = “ << Sum(a,b) << endl; // Invocation of function.. } // Compute sum of two integers. int Sum (int a, int b) // interface – 2 integers, one int result. { return a+b; } // end of body

11 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Prototype The compiler must know the following about a function before it can be called –name –return type –number of parameters –data type of each parameter int Big (int x, int y); int Sum (int, int); void printHeading( ); 6-11

12 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Definition Definition includes Header: return type: data type of the value the function returns to the part of the program that called it name: name of the function. Function names follow same rules as variable names parameter list: variables that hold the values passed to the function body : block of statements that perform the function’s task 6-12

13 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Definition 6-13

14 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Definition = header + body The function header consists of * –the function return type –the function name –the function parameter list Examples: int main() int Big (int x, int y) Note: no semicolon (;) after header … because … a body follows!! 6-14

15 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Calling and Defining Functions Function call: expression or statement that causes a function to execute  root = pow(x, 0.5); // call is an expression  getline(cin, myName); // call is a statement Function definition: statements that carry out the work of the function int main( )int Big(int x, int y) // header { cout y) return x; return 0; else return y;} 6-15

16 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Scope Rules for Functions Same as for variables: declare BEFORE using. A function call can PRECEDE the function definition. Possible order of code sections: prototypesdefinitionsprototypes calls (main)calls (main)definitions definitionscalls (main) 6-16

17 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Prototype Notes Place prototypes near top of program Program must include either prototype or full function definition before any call to the function, otherwise a compiler error occurs When using prototypes, function definitions can be placed in any order in the source file. Traditionally, after the main. 6-17

18 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 6 - Functions Part 2 (Function Calls, Passing Values to Functions) 8-18

19 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Calling a Function When a function is called by a module, the program executes the body of the function while the calling module is temporarily suspended. Only after the called function completes does execution resume in the calling module at the point following the call. 6-19

20 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Calling a Function main is automatically called when the program starts main can call any number of functions A function can call other functions Call a function by its NAME Sum(3,2) … NOT int Sum(3,2); // this is a declaration!! 6-20

21 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Providing Data for a Function Can pass values into a function at time of call c = sqrt(a*a + b*b); Values passed to function are called arguments Variables in function that hold values passed as arguments are parameters Alternate names: –argument: actual argument, actual parameter –parameter: formal argument, formal parameter 6-21

22 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Terminology for Function Calls From inside the calling module: int a=2, b=3, c; c = Sum(4,a*b); Arguments passed are the values 4 and 6. From inside the called function: int Sum(int x, int y){ … } Parameter x has value 4, parameter y has value 6. 6-22

23 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Call Notes A function can have zero or more parameters. Value of each argument is assigned to the corresponding parameter when the function is called. Passed arguments will be promoted or demoted as necessary to match data type of parameters. 6-23

24 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Passing Values to Function – A Visual void evenOrOdd(int) ; //prototype –Merely announces the properties of the function. –a declaration. void evenOrOdd(int num ) // header { … } evenOrOdd(val ); // call 6-24

25 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Passing Arguments to Parameters by Value Example: int val = 5; evenOrOdd(val); evenOrOdd can change parameter num, but it will have no effect on variable val 6-25 5 val argument in calling function 5 num parameter in evenOrOdd function

26 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Passing Data by Value Pass by value: when argument is passed to a function, its value is assigned to the corresponding parameter The function cannot access the original argument Changes to the parameter in the function do not affect the value of the argument in the calling function 6-26

27 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Return Type If a function returns a value –the data type of the value is the first word in the header (or prototype) int main() –The function body must contain a return statement int P(…){ … return int_express;} 6-27

28 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 << "Monthly Sales“ << endl; } 6-28

29 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Return Type Affects How To Call Function If a function returns a value, the function call must be an expression var = Sum(3,x) ; not Sum(a,b); If a function does not returns a value, the function call must be a statement printHeading() ; 6-29

30 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Calling Functions with Multiple Arguments Illustration * displayData(height, weight); // call void displayData(int h, int w)// header { cout << "Height = " << h << endl; cout << "Weight = " << w << endl; } 6-30

31 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 6 - Functions Part 3 (Functions Returning Values, Overloading) 8-31

32 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Functions that Return Values 6-32 int main //yours { float pi = 3.14159, sqrtPI; sqrtPI = sqrt(pi); cout << “square root of PI = “; << sqrtPI << endl; } Using C++ library modules #include #include <iostream int main //yours { int x, y; cin >> x >> y; cout << Sum(x,y) << endl; } Using your own modules #include // others #include … //Compute sum of two integers. int Sum (int a, int b) // yours { return a+b; }

33 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning a Value From a Function return statement can be used to return a value from the function to the calling module Prototype and definition indicate the data type of returned value (not void) The calling function should “catch” the returned value, e.g., –assign it to a variable –send it to an output stream (cout or a file stream) –use it in an expression (arithmetic, relational, logical) –use it as an argument to a function call 6-33

34 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 (crash) of program Without a return statement, the function ends at its last } 6-34

35 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning a Value – the return Statement Format: return expression; expression may be a variable, a literal value, or an expression. expression should be of the same data type as the declared return type of the function (will be converted if not) 6-35

36 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning a Boolean Value Function can return true or false Declare return type in function prototype and header as bool bool Odd(int num) Function body must contain return statement(s) that return true or false The calling function can use return value in a relational or logical expression. 6-36

37 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Boolean return Example * bool isValid(int); // function prototype // Validate val in range [0,100]. bool isValid(int val) // function header { int min=0, max=100; if (val >= min && val <= max) return true; else return false; } // In calling module … cin >> score; if (isValid(score)) // function call 6-37

38 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley An Input Function int ReadNum(); // function prototype int ReadNum() // function header { int v; cout << “Enter whole number: “; cin >> v; return v; } // Calling module … int num; num = ReadNum(); // function call 6-38

39 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Another Input Function // Read string after issuing prompt. string Read(string Prompt)// header { string s; cout << Prompt; getline(cin,s); return s; } // Calling module … string phrase; phrase = Read(“Enter phrase: “); //call 6-39

40 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Overloading Overloaded functions are two or more functions that have the same name, but different parameter lists (number, or data types) Can be used to create functions that perform the same task, but take different parameter types or different number of parameters Compiler will determine which version of function to call based on the argument list. 6-40

41 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Overloaded Functions Example If a program has these overloaded functions, void getDimensions(int); // 1 void getDimensions(int, int); // 2 void getDimensions(int, float); // 3 void getDimensions(double, double);// 4 then the compiler will use them as follows: int length, width; double base, height; getDimensions(length); // 1 getDimensions(length, width); // 2 getDimensions(length, height); // 3 getDimensions(height, base); // 4 6-41

42 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The exit() Function Terminates execution of a program Can be called from any function Passes a value to the operating system to indicate status of program execution Usually used for abnormal termination of program (positive value; zero means error free) Use carefully: NOT the same as return. 6-42

43 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 6 - Functions Part 4 (Parameters and Variables [global, local, static] ) 8-43

44 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Default Parameters Values passed automatically if arguments are missing from the function call Must be a constant declared in prototype void evenOrOdd(int = 0); Call: evenOrOdd(); same as evenOrOdd(0); Multi-parameter functions may have default arguments for some or all of them int getSum(int, int=0, int=0); 6-44

45 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Default Arguments * If not all parameters to a function have default values, the ones without defaults must be declared first in the parameter list int getSum(int, int=0, int=0);// OK int getSum(int, int=0, int); // wrong! When a default argument is omitted from a function call, all arguments after it must also be omitted sum = getSum(num1, num2); // OK sum = getSum(num1,, num3); // wrong! 6-45

46 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Local and Global Variables Local variable: defined within a function or block; accessible only within the function or block Other functions and blocks can define variables with the same name When a function is called, local variables in the calling function are not accessible by name from within the called function 6-46

47 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Local and Global Variables * Global variable: defined outside all functions and blocks; it is accessible to all functions within its scope Easy but dangerous way to share large amounts of data between functions Scope of a global variable is from its point of definition to the program end Use sparingly 6-47

48 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Local Variable Lifetime A local variable only exists while its defining function is executing Local variables are destroyed when the function terminates Data cannot be retained in local variables between calls to the function in which they are defined 6-48

49 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Static Local Variables * Local variables –Only exist while the function is executing –Are redefined/recreated each time function is called –Lose their contents when function terminates static local variable –is defined with key word static static int counter = 0; –is defined and initialized only the first time the function is executed –Retains its value between function calls 6-49

50 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Initializing Local and Global Variables Local variables must be initialized by the programmer Global variables are initialized to 0 (numeric) or NULL (character) when the variable is defined 6-50

51 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Local and Global Variable Names * Local variables can have same names as global variables When a function contains a local variable that has the same name as a global variable, the global variable is unavailable from within the function. The local definition "hides" or “ the global definition. 6-51

52 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Global Variables – Why Use Sparingly? Programs that use global variables are difficult to understand (e.g., what is the global variable used for?) and debug Functions that use global variables cannot easily be re-used in other programs (that may not have the same global variables) 6-52

53 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 6 - Functions Part 5 (Passing Variables as Parameters – call by reference; Menu-Driven Program Pattern) 8-53

54 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Another Input Function * void ReadNum(int & ); // function prototype void ReadNum(int & num) // function header { cout << “Enter whole number: “; cin >> num; } // Calling module … int val = 5; cout << val << endl; // Output is 5. ReadNum(val); // function call; input is 17. cout << val << endl; // Output is 17. 6-54

55 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using Reference Parameters Mechanism that allows a function to access and modify the original variable from the calling module. The parameter is an ALIAS for the variable passed in the function call. The argument in the function call must be a variable. Provides a way for the function to produce multiple results (delivered in the modified variables) 6-55

56 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Reference Parameters A reference parameter is an alias for another variable Defined with an ampersand ( & ) void getDimensions(int&, int&); Changes to a reference parameter are also made to the variable it refers to!! 6-56

57 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pass by Reference – Producing Multiple Results * void SquareCube(float x, float & sqr, float & cube) { sqr = x * x; cube = x * x * x; } 6-57

58 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pass by Reference – I/O Streams * void Read(istream & inF, string & s) { inF >> s; } ifstream myF(“mydata”); // CALLS. Read(myF, name); // Read from file. Read(cin, name); // Read from keyboard. 6-58

59 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Reference Parameter Notes Each reference parameter must contain & Argument passed to reference parameter must be a variable (cannot be an expression or constant) Use only when appropriate, such as when the function must input or change the value of the argument passed to it File stream objects must always be passed by reference 6-59

60 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Testing Functions: Stubs and Drivers Stub: dummy function in place of actual function Usually displays a message indicating it was called. May also display parameters. Place-holder for the real function. Driver: a module that exists to test a function by calling it with arguments and examining the results. Stubs and drivers are useful for testing and debugging program logic and design 6-60

61 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using Functions in a Menu-Driven Program Functions can be used to implement the display of the menu and the input of the user menu choice to implement the central switch for the menu to implement the actions taken to handle a specific menu choice 6-61

62 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Menu-Driven Program Pattern char GetMenuChoice(){ … } void PerformMenuChoice(char choice, … ) { switch ( ) … }//PerformMenuCoice int main() { do { choice = GetMenuChoice(); PerformMenuChoice(choice, … ); } while (choice != QUITCHAR); } 6-62

63 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 6 - Functions 8-63

64 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Revised 2015 EL Jones, FAMU,


Download ppt "Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition."

Similar presentations


Ads by Google