Вы находитесь на странице: 1из 99

Objectives

In this week/classes, you will:


 Learn about standard (predefined) functions
and discover how to use them in a program
 Learn about user-defined functions
 Examine value-returning functions, including
actual and formal parameters
 Explore how to construct and use a value-
returning, user-defined function in a program
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
Introduction

 Boss to worker analogy


 A boss (the calling function or caller) asks a worker (the
called function) to perform a task and return (i.e., report
back) the results when the task is done.
Introduction
 Functions are like building blocks
 They allow complicated programs to be
divided into manageable pieces
 Some advantages of functions:
 A programmer can focus on just that part of the
program and construct it, debug it, and perfect it
 Different people can work on different
functions simultaneously
 Can be re-used (even in different programs)
 Enhance program readability
Introduction (cont'd.)

 Functions
 Called modules
 Like miniature programs
 Can be put together to form a larger program
Predefined Functions
 In algebra, a function is defined as a rule or
correspondence between values, called the function’s
arguments, and the unique value of the function
associated with the arguments
 If f(x) = 2x + 5, then f(1) = 7, f(2) = 9,
and f(3) = 11
 1, 2, and 3 are arguments
 7, 9, and 11 are the corresponding values
Predefined Functions (cont'd.)
 Some of the predefined mathematical functions
are:
 sqrt(x)
 sqrt( 4 );
 sqrt( 3 - 6x );
 pow(x, y)
 floor(x)
 Predefined functions are organized into separate
libraries
 I/O functions are in iostream header
 Math functions are in cmath/math header
Predefined Functions (cont'd.)
 pow(x,y) calculates xy
 pow(2, 3) = 8.0
 Returns a value of type double
 x and y are the parameters (or arguments)
 The function has two parameters
 sqrt(x) calculates the nonnegative square root of x,
for x >= 0.0
 sqrt(2.25) is 1.5
 Type double
Predefined Functions (cont'd.)
 The floor function floor(x) calculates largest
whole number not greater than x
 floor(48.79) is 48.0
 Type double
 Has only one parameter
Predefined Functions (cont'd.)
Predefined Functions (cont'd.)
Predefined Functions (cont'd.)
Predefined Functions (cont'd.)

 Example 6-1 sample run:


User-Defined Functions
 Value-returning functions: have a return type
 Return a value of a specific data type using the
return statement
 Void functions: do not have a return type
 Do not use a return statement to return a value
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";
}
Defining and Calling Functions

• Function call: statement that causes a function to


execute
• Function definition: statements that make up a
function
Function Definition

 Definition includes
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: statements that perform the function’s task
Function Header
• The function header consists of
 the function return type
 the function name
 the function parameter list
• Example:
 int main()
Calling a Function
• To call a function, use the function name followed
by () and ;
printHeading();
• When a function is called, the program executes
the body of the function
• After the function terminates, execution resumes in
the calling function at the point of call

• main is automatically called when the program starts


• main can call any number of functions
• Functions can call other functions
Function Call
Function Call Notes
• Value of argument is copied into parameter when the
function is called
• Function can have > 1 parameter
• There must be a data type listed in the prototype ()
and an argument declaration in the function heading ()
for each parameter
• Arguments will be promoted/demoted as necessary to
match parameters
Calling Functions with Multiple Arguments

 When calling a function with multiple arguments:


 the number of arguments in the call must match the
function prototype and definition
 the first argument will be copied into the first
parameter, the second argument into the second
parameter, etc.
Calling Functions with Multiple Arguments –
an Illustration

 displayData(height, weight); // call

 void displayData(int h, int w)//heading


{
 cout << "Height = " << h << endl;
 cout << "Weight = " << w << endl;
}
Value-Returning Functions -- Example
return Statement
 Once a value-returning function computes the value,
the function returns this value via the return
statement
 It passes this value outside the function via the return
statement
Syntax: return Statement
 The return statement has the following syntax:

 In C++, return is a reserved word


 When a return statement executes
 Function immediately terminates
 Control goes back to the caller
 When a return statement executes in the
function main, the program terminates
Returning a Value From a Function

• return statement can be used to return a value from


the function to the module that made the function
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 arithmetic computation
 use it in a relational expression
Syntax: return Statement (cont’d.)
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
Boolean return Example

 bool isValid(int); //
prototype
 bool isValid(int val) // heading
 { int min = 0, max = 100;
 if (val >= min && val <= max)
 return true;
 else
 return false;
}
 if (isValid(score)) // call
 …
Value-Returning Functions: Some Peculiarity
Value-Returning Functions: Some Peculiarity
(cont'd.)
Value-Returning Functions: Some Peculiarity (cont'd.)
Flow of Execution

 Execution always begins at the first statement in


the function main
 Other functions are executed only when they are
called
 Function prototypes appear before any function
definition
 The compiler translates these first
 The compiler can then correctly translate a
function call
Conti…

C++ Programming: Program Design Including Data Structures, Fifth Edition 36


Flow of Execution (cont'd.)
 A function call results in transfer of control
to the first statement in the body of the
called function
 After the last statement of a function is
executed, control is passed back to the point
immediately following the function call
 A value-returning function returns a value
 After executing the function the returned value
replaces the function call statement
Function Prototypes

 The compiler must know the following about a


function before it is called
 name
 return type
 number of parameters
 data type of each parameter
Function Prototype
 Function prototype: function heading without the
body of the function
 Syntax:

 It is not necessary to specify the variable name in


the parameter list
 The data type of each parameter must be specified
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,
main is placed first.
 Use a function prototype (similar to the heading of the
function
 Heading: void printHeading()
 Prototype: void printHeading();
Function Prototype (Illustration)
Function Prototype (Illustration cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition 43
Example Program I
1 // C++ Program
2 // Creating and using a programmer-defined function.
3 #include <iostream>
4
5 using std::cout; Function prototype: specifies data
6 using std::endl; types of arguments and return
values. square expects and int,
7 and returns an int.
8 int square( int ); // function prototype
9
10 int main()
11 {
12 // loop 10 times and calculate and output
Parentheses () cause
13 // square of x each time function to be called. When
14 for ( int x = 1; x <= 10; x++ ) done, it returns the result.
15 cout << square( x ) << " "; // function call
 16
 17 cout << endl;
 18
 19 return 0; // indicates successful termination
 20
 21 } // end main
 22
 23 // square function definition returns square of an integer
 24 int square( int y ) // y is a copy of argument to function
 25 {
 26 return y * y; // returns square of y as an int
 27
 28 } // end function square Definition of square. y is a
copy of the argument passed.
Returns y * y, or y squared.
 1 4 9 16 25 36 49 64 81 100
Example Program II

 1 // C ++ Program
 2 // Finding the maximum of three floating-point numbers.
 3 #include <iostream>
 4
 5 using std::cout;
 6 using std::cin;
 7 using std::endl;
 8
 9 double maximum( double, double, double ); // function prototype
 10
 11 int main()
 12 { Function maximum takes 3
 13 double number1; arguments (all double) and
 14 double number2; returns a double.

 15 double number3;
 16
17 cout << "Enter three floating-point numbers: ";
18 cin >> number1 >> number2 >> number3;
19
20 // number1, number2 and number3 are arguments to
21 // the maximum function call
22 cout << "Maximum is: "
23 << maximum( number1, number2, number3 ) << endl;
24
25 return 0; // indicates successful termination
26
27 } // end main
28
Comma separated list for
 29 // function maximum definition; multiple parameters.
 30 // x, y and z are parameters
 31 double maximum( double x, double y, double z )
 32 {
 33 double max = x; // assume x is largest
 34
 35 if ( y > max ) // if y is larger,
 36 max = y; // assign y to max
 37
 38 if ( z > max ) // if z is larger,
 39 max = z; // assign z to max
 40
 41 return max; // max is largest value
 42
 43 } // end function maximum
Enter three floating-point numbers: 99.32
37.3 27.1928
Maximum is: 99.32

Enter three floating-point numbers: 1.1


3.333 2.22
Maximum is: 3.333

Enter three floating-point numbers: 27.9


14.31 88.99
Maximum is: 88.99
Void Functions
 Void functions and value-returning functions have
similar structures
 Both have a heading part and a statement part
 User-defined void functions can be placed either
before or after the function main
 If user-defined void functions are placed after the
function main
 The function prototype must be placed before the
function main

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 51
51
Void Functions (cont'd.)
 A void function does not have a return type
 return statement without any value is typically used to
exit the function early
 Formal parameters are optional
 A call to a void function is a stand-alone statement

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 52
52
Void Functions (cont'd.)
 Function definition syntax:

 Formal parameter list syntax:

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 53
53
Void Functions (cont'd.)
 Function call syntax:

 Actual parameter list syntax:

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 54
54
Void Functions (cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 55
55
Void Functions (cont'd.)
 Value parameter: a formal parameter that receives a
copy of the content of corresponding actual parameter
 Reference parameter: a formal parameter that receives
the location (memory address) of the corresponding
actual parameter

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 56
56
Void Functions (cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 57
57
Value Parameters
 If a formal parameter is a value parameter
 The value of the corresponding actual parameter is
copied into it
 The value parameter has its own copy of the data
 During program execution
 The value parameter manipulates the data stored in its
own memory space

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 58
58
Reference Variables as Parameters
 If a formal parameter is a reference parameter
 It receives the memory address of the
corresponding actual parameter
 A reference parameter stores the address of the
corresponding actual parameter
 During program execution to manipulate data
 The address stored in the reference parameter directs
it to the memory space of the corresponding actual
parameter

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 59
59
Reference Variables as Parameters
(cont'd.)
 Reference parameters can:
 Pass one or more values from a function
 Change the value of the actual parameter
 Reference parameters are useful in three situations:
 Returning more than one value
 Changing the actual parameter
 When passing the address would save memory space
and time

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 60
60
Reference Variables as Parameters
 If a formal parameter is a reference parameter
 It receives the memory address of the corresponding
actual parameter
 A reference parameter stores the address of the
corresponding actual parameter
 During program execution to manipulate data
 The address stored in the reference parameter directs
it to the memory space of the corresponding actual
parameter

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 61
61
Reference Variables as Parameters
(cont'd.)
 Reference parameters can:
 Pass one or more values from a function
 Change the value of the actual parameter
 Reference parameters are useful in three situations:
 Returning more than one value
 Changing the actual parameter
 When passing the address would save memory space
and time

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 62
62
Example 7-5: Calculate Grade

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 63
63
Example 7-5: Calculate Grade
(cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 64
64
Example 7-5: Calculate Grade (cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 65
65
Value and Reference Parameters
and Memory Allocation
 When a function is called
 Memory for its formal parameters and variables declared
in the body of the function (called local variables) is
allocated in the function data area
 In the case of a value parameter
 The value of the actual parameter is copied into the
memory cell of its corresponding formal parameter

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 66
66
Value and Reference Parameters
and Memory Allocation (cont'd.)
 In the case of a reference parameter
 The address of the actual parameter passes to the formal
parameter
 Content of formal parameter is an address
 During execution, changes made by the formal
parameter permanently change the value of the
actual parameter
 Stream variables (e.g., ifstream) should be passed
by reference to a function

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 67
67
Value and Reference Parameters
and Memory Allocation (cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 68
68
Value and Reference Parameters
and Memory Allocation (cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 69
69
Value and Reference Parameters
and Memory Allocation (cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 70
70
Value and Reference Parameters
and Memory Allocation (cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 71
71
Value and Reference Parameters
and Memory Allocation (cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 72
72
Value and Reference Parameters
and Memory Allocation (cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 73
73
Value and Reference Parameters
and Memory Allocation (cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 74
74
Value and Reference Parameters
and Memory Allocation (cont'd.)

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 75
75
Reference Parameters and Value-
Returning Functions
 You can also use reference parameters in a value-
returning function
 Not recommended
 By definition, a value-returning function returns a
single value
 This value is returned via the return statement
 If a function needs to return more than one value, you
should change it to a void function and use the
appropriate reference parameters to return the values

C++ Programming: Program Design Including


C++ Programming: Program Design Including Data Structures,
Data Structures, FifthFifth Edition
Edition 76
76
Using Functions in a Menu-Driven Program

 Functions can be used:


• to implement user choices from menu
• to implement general-purpose tasks
- Higher-level functions can call general-purpose
functions
- This minimizes the total number of functions and
speeds program development time
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 from within the called
function
Local and Global Variables
• global variable: a variable defined outside all
functions; it is accessible to all functions within its
scope
• Easy 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
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 defined
in a function between calls to the function
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
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 "shadows" the global definition.
Static Local Variables
• Local variables
 Only exist while the function is executing
 Are redefined each time function is called
 Lose their contents when function terminates
• static local variables
 Are defined with key word static
static int counter;
 Are defined and initialized only the first time the function
is executed
 Retain their contents between function calls
Default Arguments
• Values passed automatically if arguments are missing
from the function call
• Must be a constant declared in prototype
void evenOrOdd(int = 0);
• Multi-parameter functions may have default
arguments for some or all of them
int getSum(int, int=0, int=0);
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 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); // wrong!
Overloading Functions
• Overloaded functions are two or more functions
that 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
• Compiler will determine which version of function
to call by argument and parameter list
Overloaded Functions - Examples
 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

 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
The exit() Function
• Terminates execution of a program
• Can be called from any function
• Can pass a value to operating system to indicate status
of program execution
• Usually used for abnormal termination of program
• Requires cstdlib header file
Largest Number & Palindrome
Programming Example: Largest Number

 The function larger is used to determine the largest


number from a set of numbers
 Program determines the largest number from a set of
10 numbers
 Input: a set of 10 numbers
 Output: the largest of 10 numbers
Palindrome Number

 A nonnegative integer is a palindrome if it reads


forward and backward in the same way
 Examples: 5, 44, 789656987
Palindrome Number (cont’d.)
Programming Example – Max of List of Numbers:
Program Analysis

 Suppose that the input data is:


15 20 7 8 28 21 43 12 35 3
 Read the first number of the data set
 Because this is the only number read to this point, you
may assume that it is the largest number so far and call it
max
 Read the second number and call it num
 Compare max and num, and store the larger number into
max
Programming Example: Program Analysis (cont'd.)

 Now max contains the larger of the first two


numbers
 Read the third number and compare it with
max and store the larger number into max
 max contains the largest of the first three numbers
 Read the next number, compare it with max,
and store the larger into max
 Repeat this process for each remaining
number in the data set
Programming Example: Algorithm Design
 Read the first number
 Because this is the only number that you have read, it is
the largest number so far
 Save it in a variable called max
 For each remaining number in the list
 Read the next number
 Store it in a variable called num
 Compare num and max
Programming Example: Algorithm Design (cont'd.)

 For each remaining number in the list (cont'd.)


 If max < num
 num is the new largest number
 update the value of max by copying num into max
 If max >= num, discard num; that is, do nothing
 Because max now contains the largest number, print it
Summary
 Functions (modules) are miniature programs
 Divide a program into manageable tasks
 C++ provides the standard functions
 Two types of user-defined functions: value-
returning functions and void functions
 Variables defined in a function heading are
called formal parameters
 Expressions, variables, or constant values in a
function call are called actual parameters
Summary (cont'd.)
 In a function call, the number of actual
parameters and their types must match with
the formal parameters in the order given
 To call a function, use its name together with
the actual parameter list
 Function heading and the body of the function
are called the definition of the function
 A value-returning function returns its value via
the return statement
Summary (cont'd.)
 A prototype is the function heading without the body
of the function; prototypes end with the semicolon
 Prototypes are placed before every function definition,
including main
 User-defined functions execute only when they are
called
 In a call statement, specify only the actual parameters,
not their data types

Вам также может понравиться