Copyright © 2012 Pearson Education, Inc.
Chapter 6
Modular Programming
with Functions
Outline
Objectives
1. Modularity
2. Programmer-Defined Functions
3. Pass By Value Functions
4. Pass By Reference Functions
5. Random Numbers Generating Function
6. Defining Class Methods
Copyright © 2012 Pearson Education, Inc.
Modules
• A C++ source program can be thought of as
an ordered collection of executable tasks:
•input data
•analyze data
•output results
• In C++ these tasks can be performed using
programmer defined functions and types.
Copyright © 2012 Pearson Education, Inc.
Modular Programming Advantages
• Modular, object-oriented programs have
significant advantages over writing the entire
solution in main():
– Multiple programmers can contribute
– Easy testing, debugging and maintaining
– Duplication of code reduced
Copyright © 2012 Pearson Education, Inc.
Abstraction
• Involves the use of functions, objects,
procedures, etc., whose details of operation
are not known.
• The inputs, outputs, and external (public)
behaviors of these ‘black boxes’ is all that is
needed to use them effectively.
Copyright © 2012 Pearson Education, Inc.
Abstraction via Modularity
• Useful in reducing the development
time of software while increasing quality.
– Modules may be tested and written separately.
– Modules may be reused many times in a problem
solution.
– Once tested, modules do not need to be retested
before being reused in other problem solutions.
– Tend to yield shorter programs
Copyright © 2012 Pearson Education, Inc.
Functions
• Functions, or modules, are independent statement
blocks that are written to perform a specialized
task.
• A problem solution contains numerous
functions.
main() is a programmer defined function.
main() often call (invokes) functions defined in one of
the standard libraries.
main() can also call programmer defined functions.
Copyright © 2012 Pearson Education, Inc.
Calling Pre-defined Function
Example 1
Copyright © 2012 Pearson Education, Inc.
Function Terminology
• Function Definition
– function header
– statement block
• Formal Parameters
– Variables defined in the function header and used in definition
to access the function’s parameters.
– Formal parameters must agree with arguments in order, number
and data type.
• Function Prototype
– describes the interface of a function. Names of the formal
parameters are optional.
• Function Call
– references and invokes (i.e. causes execution of) a function
• Function Arguments
– Expressions provided as parameters to function call
Copyright © 2012 Pearson Education, Inc.
Function Terminology Illustrated
Formal Parameters vs. Arguments
Copyright © 2012 Pearson Education, Inc.
Function Prototype
• In C++, identifiers (including function names) must be
defined before they may be referenced.
• For main() to be able to call other functions, function
definitions must appear above main().
• However, we usually like to have main() to appear
near the beginning of the program.
• By writing a function prototype which provides
sufficient information for the compiler to process
references to the function, function definitions may
appear below main() or in a separate source file.
Copyright © 2012 Pearson Education, Inc.
Example 2
Copyright © 2012 Pearson Education, Inc.
Function Prototype
Syntax:
return-type function_name ( [parameter_list] );
Examples
Valid References
double sinc(double);
double sinc(double x);
double y(-5.7); sinc("hello");
x = sinc(y);
sinc(‘0’);
z = sinc(1.5); sinc(cout);
w = sinc(10);
u = sinc(0.0);
void clear(ostream&);
clear(cout);
Copyright © 2012 Pearson Education, Inc.
Invalid References
clear(cin);
Functions
• Can be defined to:
– return a single value to the calling function.
•Example: double fun1(double x)
– perform a data independent task.
•Example: void fun2(double x, double y)
– modify data in calling context via the parameter
list (pass by reference.)
•Example: void fun3(int& x, int& y) modifies
the first and second arguments in the calling function.
Copyright © 2012 Pearson Education, Inc.
Parameter Passing
• C++ supports two forms of parameter
passing:
– Pass by value.
– Pass by reference.
Copyright © 2012 Pearson Education, Inc.
Pass by Value
– Pass by value is the default in C++ (except when passing
arrays).
– The argument is an expression that is evaluated when the
function is called to determine the value of the formal
parameter.
– The formal parameter is a distinct variable initialized with a
copy of the value of the argument. Changes to the formal
parameter do not affect the argument.
– Formal parameters are local to the function. They can not
be referenced outside the function. Their storage class is
auto by default, but can be made static.
Copyright © 2012 Pearson Education, Inc.
Value Returning Functions
• A value returning function returns a
single value to the calling program.
• The function header declares the type of
value to be returned.
• A return statement is required in the
statement block.
Copyright © 2012 Pearson Education, Inc.
Finding Number of Odd Numbers
Example 3
Right angle Triangle
Example 4
Finding the Minimum of Three Number
Example 5
|x+1| Calculation
Example 6
Factorial Calculation
• In math:
– n! = n*(n-1)*(n-2)*…*1
– n is a positive integer
– 0! is 1 by definition
Copyright © 2012 Pearson Education, Inc.
Factorial Calculation
Example 7
Copyright © 2012 Pearson Education, Inc.
exp(x) Calculation
Example 8
Copyright © 2012 Pearson Education, Inc.
The rand( ) Function
• rand() generates a random integer between 0 and RAND_MAX which is
defined in <cstdlib>
• We use rand()%(n+1) to generate a random integer between 0 and n; for
example to generates a random number between 0 and 10 we use
y = rand()%11;
• To generate integers between a and b, use
rand()%(b‒a+1) + a
Example: To generate a random integer between −25 and 25, use
rand()%(25‒ (-25)+1) + (-25)
y = rand()%51 - 25;
• To generate a random double between a and b, use
(b‒a) * ((double)rand()/RAND_MAX) + a;
Example: To generate a random double between 20.0 and 200.0, use
y = 180.0 * ((double)rand()/RAND_MAX) + 20;
Copyright © 2012 Pearson Education, Inc.
Random Numbers
• Numbers generated with particular
properties.
– Minimum and maximum values, likelihoods of
particular values, etc.
• Often required in solving engineering problems!
• Computers generate psuedo-random number
sequences.
– Random number seed used to alter the
generators current point in the sequence.
Copyright © 2012 Pearson Education, Inc.
srand( ) and time( )
• The seed function srand(unsigned int);
– sets the seed of the Random Number Generator
– If an srand() function is not used before rand(), the
computer assumes that the seed value is 1.
– It accepts only positive integers as arguments.
• The time() function defined in <ctime> can be used
as an argument for the srand() function to
generate different seed for different runs.
Copyright © 2012 Pearson Education, Inc.
Using rand( )
Example 9
Copyright © 2012 Pearson Education, Inc.
Calling srand( ) before rand( )
Example 10
Copyright © 2012 Pearson Education, Inc.
Using time( ) to Generate Seed
Example 11
Copyright © 2012 Pearson Education, Inc.
Random double Numbers
Example 12
void Type of Functions
• A void function declares void as a return type.
• A return statement is optional.
• If a return statement is used, it has the following
form
return ;
Copyright © 2012 Pearson Education, Inc.
void Type of Functions
Example 13
References
• Example 14
• A reference is not an
object. It defines an
alternative name (alias)
for an object/variable
• A reference must be
initialized. Once
initialized, it can not be
bound to a different
object/variable.
• A reference to type
must be declared as
type&.
Pass by Reference Functions
• Pass by reference allows modification of a function
argument.
• Must append an & to the parameter data type in
both the function prototype and function header
void getDate(int& day, int& mo, int& year)
• Formal parameter becomes an alias for the
argument.
– The argument must be a variable of a compatible type.
• Any changes to the formal parameter directly
change the value of the argument.
Copyright © 2012 Pearson Education, Inc.
swap(double& x, double& y)
Copyright © 2012 Pearson Education, Inc.
swap() Definition
Example 15
Copyright © 2012 Pearson Education, Inc.
Pass by Reference
Example 16
Pass by Ref. vs. Pass by Value
Example 17
Copyright © 2012 Pearson Education, Inc.
One Function and Multiple Output Values
• When you need a one function that has a number of formal
parameters and need to calculate two or more values and
return them to main( ), you must store those values in a pass
by reference parameters (with optional return statement).
Example: a function that accepts two arguments and
computes their sum and their product separately my be fined
as:
– If you do not use the method in the above example, you
will need two pass by value functions (one that returns
the sum to main( ) and the other returns the product).
Pass by Reference
Example 18
(Compare to Example 7)
Storage Class and Scope
• Scope refers to the portion of the
program in which it is valid to reference a
function or a variable
• Storage class relates to the lifetime of a
variable
Copyright © 2012 Pearson Education, Inc.
Scope
• Local scope - a local variable is defined within
a function or a block and can be accessed
only within the function or block that
defines it
• Global scope - a global variable is defined
outside the main() function and can be
accessed by any function within the program
file.
Copyright © 2012 Pearson Education, Inc.
Storage Class – 4 Types
• automatic - key word auto - default for local variables
– Memory set aside for local variables is not reserved when
the block in which the local variable was defined is exited.
• static - key word static
– Requests that memory for a local variable be reserved
throughout the execution life of the program. The static
storage class does not affect the scope of the variable.
• external - key word extern - default for global variables
– Memory is reserved for a global variable throughout the
execution life of the program.
• register - key word register
– Requests that a variable should be placed in a high speed
memory register.
Copyright © 2012 Pearson Education, Inc.
Local Variables with static Storage
Example 19
Copyright © 2012 Pearson Education, Inc.
Encapsulation
• The public interface of a well-defined
data type provides a complete set of public
methods for interacting with the object while
hiding the implementation details of the data
type.
• Typically, attributes of an object are hidden
(private or protected) and the public interface
includes support for those attributes through
accessor and mutator methods.
Copyright © 2012 Pearson Education, Inc.
Accessor Methods
• Value-returning methods usually with
no parameters.
• Purpose is to return the value of an
attribute.
– Read-only access.
• ‘get’ methods by convention.
Copyright © 2012 Pearson Education, Inc.
Mutator Methods
• void methods usually with one or
more input parameters.
• Purpose is to change (mutate) the value of
an attribute.
– Write-only access.
• ‘set’ methods by convention.
Copyright © 2012 Pearson Education, Inc.