copyright © 2012 pearson education, inc. chapter 6 modular programming with functions
Post on 27-Dec-2015
218 Views
Preview:
TRANSCRIPT
Copyright © 2012 Pearson Education, Inc.
Chapter 6
Modular Programming with Functions
Copyright © 2012 Pearson Education, Inc.
OutlineObjectives
1. Modularity
2. Programmer-Defined Functions
3. Parameter Passing
4. Problem Solving Applied: Calculating a Center of Gravity
5. Random Numbers
6. Problem Solving Applied: Instrumentation Reliability
7. Defining Class Methods
8. Problem Solving Applied: Design of Composite Materials
9. Numerical Technique: Roots of Polynomials*
10.Problem Solving Applied: System Stability*
11.Numerical Technique: Integration*
Copyright © 2012 Pearson Education, Inc.
ObjectivesDevelop problem solutions in C++ containing:
• Functions from the standard C++ library.
• Programmer-defined functions.
• Functions that generate random numbers
• Simulation Techniques.
• Techniques for finding real roots to polynomials.
• Numerical integration techniques.
Modularity
Copyright © 2012 Pearson Education, Inc.
Modularity
• A problem solution contains numerousfunctions.– main() is a programmer defined function.– main() often references functions defined in one of
the standard libraries.– main() can also call other programmer defined
functions.
• Functions, or modules, are independent statement blocks that are written to perform a specialized task.
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.
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.– E.g. many people know how to use cell phones while
being blissfully ignorant of Maxwell’s equations or the protocols used by the phone companies to complete phone calls.
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.• Also in other problem solutions.
– 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.
Modular Problem Solutions
• Complex problems can be broken down into sub tasks performed on and/or by objects, making it easier to implement in C++.
• Modular, object-oriented programs have significant advantages over writing the entire solution in main():– Multiple programmers– Testing/Debugging/Maintaining– Reduce duplication of codeCopyright © 2012 Pearson Education, Inc.
Functions
• Pre-defined– standard libraries– Other libraries (including your own!)
• User defined
Copyright © 2012 Pearson Education, Inc.
Pre-defined Function(Example)
#include <iostream>#include <cmath>using namespace std;int main() { double angle; cout << “input angle in radians: “; cin >> angle; cout << “\nthe sine of the angle is “
<< sin(angle) << endl; return 0;}//end main
Copyright © 2012 Pearson Education, Inc.
Programmer-Defined Functions
Copyright © 2012 Pearson Education, Inc.
Function Terminology• Function Prototype
– describes how a function is called• Function Call
– references and invokes (i.e. causes execution of) a function• Function Arguments
– Expressions provided as parameters to function call• 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.
Copyright © 2012 Pearson Education, Inc.
Functions
• Can be defined to:– return a single value to the calling function. – perform a data independent task. – modify data in calling context via the
parameter list (pass by reference.)
Copyright © 2012 Pearson Education, Inc.
Function Definitions
Copyright © 2012 Pearson Education, Inc.
Syntax:return-type function_name ( [parameter_list] ) {
//statements}
Examplesint main() { cout << “Hello World!” << endl; return 0;}
void drawBlock(ostream& out, int size) { for (int height = 0; height < size; height++) { for (int width = 0; width < size; width++) out << “*”; out << endl; }}
Function Prototype• In C++, identifiers must be defined
before they may be referenced.• Since the main function is the entry point for the
application, we like to have it appear near the beginning of the program.– But for it to be able to call functions, defining all the
functions it calls first is a problem.
• A function prototype provides sufficient information for the compiler to process references to the function.– The definition may then be provided later in the code.
Copyright © 2012 Pearson Education, Inc.
Function Prototype
Copyright © 2012 Pearson Education, Inc.
Syntax:return-type function_name ( [parameter_list] );
Examples Valid References Invalid References
double sinc(double);double sinc(double x);
double y(-5);sinc(y)sinc(1.5)sinc(10)sinc(0.0)
sinc(“hello”)sinc(‘0’)sinc(cout)
void clear(ostream&); clear(cout); cout << clear(cout);
Value Returning Functions
• A value returning function returns asingle 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.
Example - Factorial
• In math:– n! = n*(n-1)*(n-2)*…*1
– n is a positive integer
– 0! is 1 by definition
Copyright © 2012 Pearson Education, Inc.
Example - Factorial//function definition: n! = n*(n-1)*(n-2)*…*1 // 0! is 1 by definition//Function factorial returns n! //Function factorial assumes n is non-negative int
int factorial(int n) //function header{ int nfactorial = 1; while (n>1) { nfactorial = nfactorial * n;
n--; } //end while block return nfactorial;} //end factorial
Copyright © 2012 Pearson Education, Inc.
Example –Calling Factorial Function
int factorial(int); //function prototype
int main() { int n; cin >> n; if (n>=0) cout << n << "! is “ << factorial(n) << endl;
//n is the argument of the//factorial function call
else cout <<"not defined for negative numbers"
<< endl; return 0;} //end main
Copyright © 2012 Pearson Education, Inc.
Void 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.
Example//scale data//alters a data set by applying a scale factor//to each member of the data set.
void scaleData(vector<double>& n, double sf) { for (int i = 0; I < data.size(); i++) data[i] *= sf; return; // return statement is optional…} //end scaleData
Copyright © 2012 Pearson Education, Inc.
Parameter Passing
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 as arguments to functions).
– The formal parameter is a distinct variable initialized with the value of the argument.
• The argument is an expression that is evaluated when the function is called to determine the value of the formal parameter.
– Changes to the formal parameter do not affect the argument.
Copyright © 2012 Pearson Education, Inc.
//Function Definitionint fact(int num) //4{ int nfact = 1; //5 while(num>1) { nfact = nfact*num; num--; } return(nfact); //6} //end fact
int fact(int);int main(){ int n, factorial; //1 cin >> n; //2 if(n>=0) { factorial = fact(n); //3 cout << n <<"! is " << factorial << endl;//7 } //end ifreturn 0;} //end main
Example
Memory Snapshot:main()
1-> int n
3 ->
4-> int num
6->
5-> int nfact
?
32 ->
3 1
int factorial ?
7 -> 3 6
fact()
1 6
?
call fact()return nfact
Note: value of n in main has not changed.
int fact(int);int main(){ int n, factorial; //1 cin >> n; //2 if(n>=0) { factorial = fact(n); //3 cout << n <<"! is " << factorial << endl;//7 } //end ifreturn 0;} //end main
//Function Definitionint fact(int num) //4{ int nfact = 1; //5 while(num>1) { nfact = nfact*num; num--; } return(nfact); //6} //end fact
Pass by Reference
• Pass by reference allows modification of a function argument.
• Must append an & to the parameter data type in both the function prototype and function headervoid 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.
Example#include <iostream>using namespace std;
void swap(double&, double&); //function prototypeint main(){ double x=5, y=10; swap(x,y); //function call; x y are
arguments cout >> “x = “ << x << ‘,’ << “ y= “ << y <<
endl; return 0;} //end main
Output is:x = 10, y = 5
Copyright © 2012 Pearson Education, Inc.
Example//Function swap interchanges the values of//two variables void swap(double& x, double& y){
double temp; //local variable temptemp = x;x=y;y=temp;return; //optional return statement
} //end swap
Copyright © 2012 Pearson Education, Inc.
//Function Definitionvoid swap(double& x, double& y){
double temp;//temp = x;x=y;y=temp;return; //optional
}//end swap
Program Trace: pass by reference#include <iostream>using namespace std;
void swap(double&, double&); //prototypeint main(){ double x=5, y=10; swap(x,y); //x y are arguments cout << "x = " << x << ',' << " y= " << y << endl; return 0;} //end main
Memory Snapshot:main()
double x
double x double y
5
double y 10
swap()?double
temp5
call swap()
//Function Definitionvoid swap(double& x, double& y){
double temp;//temp = x;x=y;y=temp;return; //optional
}//end swap
Program Trace: pass by reference#include <iostream>using namespace std;
void swap(double&, double&); //prototypeint main(){ double x=5, y=10; swap(x,y); //x y are arguments cout << "x = " << x << ',' << " y= " << y << endl; return 0;} //end main
Memory Snapshot:main()
double x
double x double y
10
double y 10
swap()?double
temp5
//Function Definitionvoid swap(double& x, double& y){
double temp;//temp = x;x=y;y=temp;return; //optional
}//end swap
Program Trace: pass by reference#include <iostream>using namespace std;
void swap(double&, double&); //prototypeint main(){ double x=5, y=10; swap(x,y); //x y are arguments cout << "x = " << x << ',' << " y= " << y << endl; return 0;} //end main
Memory Snapshot:main()
double x
double x double y
10
double y 5
swap()?double
temp5
return;
//Function Definitionvoid swap(double& x, double& y){
double temp;//temp = x;x=y;y=temp;return; //optional
}//end swap
Program Trace: pass by reference#include <iostream>using namespace std;
void swap(double&, double&); //prototypeint main(){ double x=5, y=10; swap(x,y); //x y are arguments cout << "x = " << x << ',' << " y= " << y << endl; return 0;} //end main
Memory Snapshot:main() double x
10
double y 5
Arguments have been modified
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 relatesto 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.
• external - key word extern - default for global variables– Memory is reserved for a global variable throughout the
execution life of the program.• 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.
• register - key word register – Requests that a variable should be placed in a high
speed memory register. Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Calculating the Center
of Gravity
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Calculating the Center
of Gravity
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Calculating the Center
of Gravity
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Calculating the Center
of Gravity
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Calculating the Center
of Gravity
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Calculating the Center
of Gravity
Copyright © 2012 Pearson Education, Inc.
Random Numbers
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.
Random Integers
• C++ rand() function – Generates a random integer between 0 and
RAND_MAX (which is defined in <cstdlib>).• To generate integers between 0 and b, use
rand()%(b+1)• To generate integers between a and b, use
rand()%(b-a+1) + a
– Uniformly distributed.• All values in the range equally likely.
• void srand(unsigned int); – sets the seed of the Random Number Generator
Copyright © 2012 Pearson Education, Inc.
Example Function
/*-----------------------------------------* This function generates a random integer * between specified limits a and b (a<b).*----------------------------------------*/int rand_int(int a, int b) { return rand()%(b-a+1) + a;}
Copyright © 2012 Pearson Education, Inc.
Example Function
/*-----------------------------------------* This function generates a random double* between specified limits a and b (a<b).*----------------------------------------*/double rand_double(double a, double b) { return ((double)rand()/RAND_MAX)*(b-a)
+ a;}
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Instrumentation
Reliability
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Instrumentation
Reliability
• In series, all three components must work for the system to work.– If each component works properly 80% of the
time, then the system will work properly 0.83 = 51.2% of the time.
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Instrumentation
Reliability• In parallel, at least one
component must work for the system to work.– If each component works
properly 80% of the time, then the system will work properly 1-(0.2)3 = 99.2% of the time.
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Instrumentation
Reliability
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Instrumentation
Reliability
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Instrumentation
Reliability
Copyright © 2012 Pearson Education, Inc.
Defining Class Methods
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 ormore input parameters.
• Purpose is to change (mutate) the value of an attribute.– Write-only access.
• ‘set’ methods by convention.
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Design of Composite
Materials
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Design of Composite
Materials
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Design of Composite
Materials
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Design of Composite
Materials
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Design of Composite
Materials
Copyright © 2012 Pearson Education, Inc.
Numerical Technique: Roots of Polynomials*
Copyright © 2012 Pearson Education, Inc.
Roots of Polynomials
• A polynomial is generally expressedin the form:
• Find values of x such that f(x) = 0
• Degree of the polynomial is N
• N roots (may be real or complex)
• Easy to find roots if polynomial is factored into linear terms.
Copyright © 2012 Pearson Education, Inc.
Incremental Search
• Search for roots in polynomial over aninterval by breaking the interval into smaller subintervals such that function is negative on one end and positive on the other end.– Thus there is at least 1 real root– This is always an odd number of real roots– Keep decreasing the interval size to ‘narrow
in’ on one root.Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.
Newton-Raphson Method
• Popular root-finding method using afunction and its first derivative.
• Iteratively estimates a root from the function and its derivative.
• Usually requires fewer iterations.
Copyright © 2012 Pearson Education, Inc.
Numerical Technique: Integration*
Copyright © 2012 Pearson Education, Inc.
Numerical Integration
• Integration of a function over aninterval computes the area under the graph of the function.– Important relationships in engineering (e.g.
distance, velocity, acceleration).
• Computable through several techniques.
Copyright © 2012 Pearson Education, Inc.
Trapezoidal Rule
• Approximate integral by breaking integration interval into subintervals and estimating area under the graph in each by a trapezoid.
Copyright © 2012 Pearson Education, Inc.
top related