1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.

Slides:



Advertisements
Similar presentations
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Starting Out with Java: From Control Structures through Objects Fourth.
Advertisements

Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Chapter 6: Functions.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
1 Chapter 9 Scope, Lifetime, and More on Functions.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 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.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 1 © 2006 Pearson Education. All Rights Reserved Midterm Wednesday (Oct. 16, 2013) Class room.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Lecture 5 – Function (Part 2) FTMK, UTeM – Sem /2014.
Computer Programming II Lecture 4. Functions - In C++ we use modules to divide the program into smaller and manageable code. These modules are called.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
Chapter 7: User-Defined Functions II
Lecture 3 C & C++ programming.
CSCI 161: Introduction to Programming Function
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 9 Scope, Lifetime, and More on Functions
6.12 Default Arguments.
Chapter 6: Functions Starting Out with C++ Early Objects Ninth Edition
Chapter 4 void Functions
Functions.
6 Chapter Functions.
Chapter 6: Functions Starting Out with C++ Early Objects Ninth Edition
Chapter 2: Introduction to C++.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Instructor: Hidayah Elias Course: COMPUTER PROGRAMMING (BFC 2042)
Standard Version of Starting Out with C++, 4th Edition
Corresponds with Chapter 5
Presentation transcript:

1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions

2 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 Using Functions in a Menu-Driven Program 6.7 The return Statement 6.8 Returning a Value from a Function

3 Topics 6.9 Returning a Boolean Value 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

4 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection of statements to perform a task Motivation for modular programming: Improves maintainability of programs Simplifies the process of writing programs

5 6.2 Defining and Calling Functions Function call: statement causes a function to execute Function definition: statements that make up a function

6 Function Definition Definition includes: return type: data type of the value that function returns to the part of the program that called it 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 {} 1.The first character must be one of the letters a through z, A through Z, or an underscore character _. 2.After the first character you may use the letters a through z or A through Z, the digits 0 through 9, or underscores. 3.Uppercase and lowercase characters are distinct.

7 Function Definition -Example function name return type parameter list int main ( ) { function body cout << “Hello World\n”; return 0; } Function head

8 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"; }

9 Calling a Function A function is executed when it is called: Function main is called automatically when a program starts All other functions must executed by function call To call a function, use the function name followed by () and ; printHeading(); When called, program executes the body of the called function After the function terminates, execution resumes in the calling function at point of call.

10 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 Example: prog 6-1prog 6-1

11 Calling Functions-Example void displayMessage() { cout << "Hello from the function displayMessage.\n"; } int main() { cout << "Hello from main.\n"; displayMessage(); cout << "Back in function main again.\n"; return 0; }

12 Calling Functions-More Examples Example: prog 6-2prog 6-2 Example: prog 6-3prog 6-3 Example: prog 6-4prog 6-4

13 Function Documentation Function definition should be preceded by comments that indicate Purpose of the function How it works, what it does Input values that it expects, if any Output that it produces, if any Values that it returns, if any

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 without the body Header: void printHeading() Prototype: void printHeading(); Example: prog 6-5prog 6-5

15 Prototype Notes Place prototypes near top of program Program must include either prototype or full function definition before any call to the function – compiler error otherwise When using prototypes, can place function definitions in any order in source file

Sending Data into a Function When a function is called, the program may pass values into a function: result+pow(2,4); Values passed to function are arguments Variables in function that hold values passed as arguments are parameters Example: prog 6-6prog 6-6

17 Other Parameter Terminology A parameter can also be called a formal parameter or a formal argument An argument can also be called an actual parameter or an actual argument

18 Parameters, Prototypes, and Function Headings For each function argument, the prototype must include the data type of each parameter in its () the header must include a declaration for each parameter in its () void evenOrOdd(int); //prototype void evenOrOdd(int num) //header evenOrOdd(val); //call

19 Function Call Notes Value of argument is copied into parameter when the function is called A parameter’s scope is the function which uses it Function can have > 1 parameter There must be a data type listed in the prototype () and an argument declaration in the function header () for each parameter Arguments will be promoted/demoted as necessary to match parameters

20 Calling Functions with Multiple Arguments When calling a function with multiple arguments: the number of arguments in the call must match the prototype and definition the first argument will be used to initialize the first parameter, the second argument to initialize the second parameter, etc.

21 Calling Functions with Multiple Arguments Illustration displayData(height, weight); // call void displayData(int h, int w)// heading { cout << “Height = “ << h << endl; cout << “Weight = “ << w << endl; } Example: Prog 6-7Prog 6-7

Passing Data by Value Pass by value: when argument is passed to a function, a copy of its value is placed in the parameter Parameter cannot access the original argument Changes to the parameter in the function do not affect the value of the argument back in the calling function

Passing Data by Value Example: prog 6-8prog 6-8 Example: int val=5; evenOrOdd(val); evenOrOdd can change variable num, but it will have no effect on variable val 5 val argument in calling function 5 num parameter in evenOrOdd function

Using Reference Variables as Parameters When used as parameters, reference variables allow a function to access the parameter’s original argument. Changes to the parameter are also made to the argument. Mechanism that allows a function to work with the original argument from the function call, not a copy of the argument Allows the function to modify values stored in the calling environment Provides a way for the function to ‘return’ > 1 value

25 Passing by Reference A reference variable is an alias for another variable Defined with an ampersand ( & ) void getDimensions(int&, int&); Changes to a reference variable are made to the variable it refers to Use reference variables to implement passing parameters by reference

26 Reference Variable Notes Each reference parameter must contain & Space between type and & is unimportant Must use & in both prototype and header Argument passed to reference parameter must be a variable – cannot be an expression or constant Use when appropriate – don’t use when argument should not be changed by function, or if function needs to return only 1 value Examples: Prog 6-22, Prog 6-23Prog 6-22Prog 6-23

Using Functions in Menu-Driven Programs Functions can be used to implement user choices from menu to implement general-purpose tasks: Higher-level functions can call general- purpose functions, minimizing the total number of functions and speeding program development time Example: prog 6-9prog 6-9

The return Statement The return statement causes a function to end immediately 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 } Example: Prog 6-10Prog 6-10

Returning a Value From a Function A function may send a value back to the part of the program that called the function return statement can be used to return a value from function to the point of call Prototype and definition must indicate data type of return value (not void ) Calling function should use return value: assign it to a variable send it to cout use it in an expression

30 Returning a Value From a Function Example: prog 6-11prog 6-11 Example: prog 6-12prog 6-12 Function arguments Return value

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 Example: prog 6-13prog 6-13

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 within the called function Example: prog 6-14prog 6-14

33 Local and Global Variables global variable: defined outside all functions, accessible to all functions within its scope Easy way to share large amounts of data between functions Scope of a global variable: program from point of definition to the end Use sparingly Example: Prog 6-15Prog 6-15

34 Initializing Local and Global Variables Local variables must be initialized by programmer Global variables are initialized to 0 (numeric) or NULL (character) when variable is defined

35 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” the global definition Example: Prog 6-18Prog 6-18

Static Local Variables Variables are destroyed when the function terminates and are then re-created when the function starts again Local variables only exist while function is executing. When function terminates, contents of local variables are lost static local variables retain their contents between function calls static local variables are defined and initialized only the first time the function is executed. 0 is default initialization Example: prog 6-19, prog 6-20prog 6-19prog 6-20

Default Arguments Default argument is passed automatically to a function if argument is missing on the function call Must be a constant declared in prototype: void evenOrOdd(int = 0); Can be declared in header if no prototype Multi-parameter functions may have default arguments for some or all of them: int getSum(int, int=0, int=0);

38 Default Arguments If not all parameters to a function have default values, the defaultless ones are declared first in the parameter list: int getSum(int, int=0, int=0);// OK int getSum(int, int=0, int); // NO When an argument is omitted from a function call, all arguments after it must also be omitted: sum = getSum(num1, num2); // OK sum = getSum(num1,, num3); // NO The default arguments are only used when the actual arguments are omitted from the function call

39 Default Arguments Summary about default arguments: The value of a default argument must be a literal value or a named constant When an argument is left out of a function call (because it has a default value), all the arguments that come after it must be left out too When a function has a mixture of parameters both with and without default arguments, the parameters with default arguments must be declared last. Example: Prog 6-21Prog 6-21

Overloading Functions Overloaded functions have the same name but different parameter lists Can be used to create functions that perform the same task but take different parameter types or different number of parameters In a C++ function call, the function name and the parameter list are both used to identify the function Compiler will determine which version of function to call by argument and parameter lists

41 Function Overloading Examples Using these overloaded functions, void getDimensions(int); // 1 void getDimensions(int, int); // 2 void getDimensions(int, float); // 3 void getDimensions(float, float);// 4 the compiler will use them as follows: int length, width; float base, height; getDimensions(length); // 1 getDimensions(length, width); // 2 getDimensions(length, height); // 3 getDimensions(height, base); // 4

42 Function Overloading- More Examples Example: Prog 6-24Prog 6-24 Example: Prog 6-25Prog 6-25

The exit() Function Terminates execution of a program Can be called from any function Can pass an int value to operating system to indicate status of program termination Usually used for abnormal termination of program Requires cstdlib header file Example: prog 6-26prog 6-26

Stubs and Drivers Stub: dummy function in place of actual function Usually displays a message indicating it was called. May also display parameters Driver: function that tests a function by calling it Useful for testing and debugging program and function logic and design Example: Prog 6.27Prog 6.27