j. p. cohoon and j. w. davidson © 1999 mcgraw-hill, inc. programmer-defined functions development...
Post on 21-Dec-2015
215 views
TRANSCRIPT
J. P. Cohoon and J. W. Davidson© 1999 McGraw-Hill, Inc.
Programmer-defined functions
Development of simple functions using value parameters
Ch 6 / Foil 2
Includes description of the interface and the function body Interface
– Similar to a function prototype, but parameters names are required
Body– Statement list with curly braces that comprises its actions– Return statement to indicate value of invocation
Function Definition
Ch 6 / Foil 3
float CircleArea (float r) {const float Pi = 3.1415;return Pi * r * r;
}
Function Definition
Function bodyReturn statement
Local object definition
Formal parameterReturn type Function name
Ch 6 / Foil 4
Function Invocation
cout << CircleArea(MyRadius) << endl;
Invocation is part of a larger expression. To process the invocation, the function that
contains the insertion statement is suspended and CircleArea() does its job.
The insertion statement is then completed using the value supplied by CircleArea().
Actual parameter
Ch 6 / Foil 5
Simple Programs
Single file Include statements Using statements Function prototypes Function definitions
Functions use value parameter passing Also known as pass by value or call by value
– The actual parameter is evaluated and a copy is given to the invoked function
Ch 6/ Foil 6
#include <iostream>#include <string>using namespace std;float CircleArea(float r);// main(): manage circle computationint main() { cout << "Enter radius: "; float MyRadius; cin >> MyRadius; float Area = CircleArea(MyRadius); cout << "Circle has area " << Area; return 0;}// CircleArea(): compute area of radius r circlefloat CircleArea(float r) { const float Pi = 3.1415; return Pi * r * r;
}
Ch 6 / Foil 7
Value Parameter Passing Rules
Formal parameter is created on function invocation and it is initialized with the value of the actual parameter
Changes to the formal parameter do not affect the actual parameter Whenever a formal parameter is referenced, the value used for the
formal parameter is the one stored in the current activation record for the function
There is a new activation record for each invocation The name of the formal parameter is only known within its function The formal parameter is destroyed when the function invocation
completes Activation record memory is automatically released at completion
Returnvalue
FunctionInput stream
data
Output streamdata
Information to function cancome from parameters or
an input stream
Parameters
Information fromfunction can come
through a returnvalue or an output
stream
Ch 6/ Foil 8
Ch 6 / Foil 9
PromptAndRead()
// PromptAndRead(): prompt and extract next// integerint PromptAndRead() {
cout << "Enter number (integer): ";int Response;cin >> Response;return Response;
}
Ch 6 / Foil 10
Max()
// Max(): return larger of a and bint Max(int a, int b) {
if (a < b) {return b;
}else {
return a;}
}
Ch 6 / Foil 11
Min()
// Min(): return smaller of a and bint Min(int a, int b) {
if (a > b) {return b;
}else {
return a;}
}
Ch 6 / Foil 12
Sum()
// Sum(): compute sum of integers in a ... bint Sum(int a, int b) {
int Total = 0;for (int i = a; i <= b; ++i) {
Total += i;}return Total;
}
Ch 6 / Foil 13
Problem
Definition Input two numbers that represent a range of integers and
display the sum of the integers that lie in that range Design
Prompt user and read the first number Prompt user and read the second number Determine the smaller of the two numbers Determine the larger of the two numbers Calculate the sum of integers in the range smaller...larger by
adding in turn each integer in that range Display the sum
#include <iostream>#include <string>using namespace std;int PromptAndRead();int Min(int a, int b);int Max(int a, int b);int Sum(int a, int b);int main() {
int FirstNumber = PromptAndRead();int SecondNumber = PromptAndRead();int Smaller = Min(FirstNumber, SecondNumber);int Larger = Max(FirstNumber, SecondNumber);int RangeSum = Sum(Smaller, Larger);cout << "The sum from " << Smaller << " to " << Larger << " is " << RangeSum << endl;return 0;
}
Ch 6/ Foil 14
// Min(): return smaller of a and bint Min(int a, int b) {
if (a > b)return b;
elsereturn a;
}// Max(): return larger of a and bint Max(int a, int b) {
if (a < b)return b;
elsereturn a;
}
Ch 6/ Foil 15
// PromptAndRead(): prompt & extract next integerint PromptAndRead() {
cout << "Enter number (integer): ";int Response;cin >> Response;return Response;
}// Sum(): compute sum of integers in a ... bint Sum(int a, int b) {
int Total = 0;for (int i = a; i <= b; ++i) {
Total += i;}return Total;
}
Ch 6/ Foil 16
Ch 6 / Foil 17
Blocks and Local Scope
A block is a list of statements within curly braces Blocks can be put anywhere a statement can be put Blocks within blocks are nested blocks An object name is known only within the block in which it is
defined and in nested blocks of that block A parameter can be considered to be defined at the beginning of
the block corresponding to the function body
Ch 6 / Foil 18
Local Object Manipulation
void f() { int i = 1; cout << i << endl; // insert 1 { int j = 10;
cout << i << j << endl; // insert 1 10 i = 2; cout << i << j << endl // insert 2 10 } cout << i << endl; // insert 2 cout << j << endl; // illegal}
Ch 6 / Foil 19
Name Reuse
If a nested block defines an object with the same name as enclosing block, the new definition is in effect in the nested block
void f() { { int i = 1; cout << i << endl; // insert 1 { cout << i << endl; // insert 1 char i = 'a'; cout << i << endl; // insert a } cout << i << endl; // insert 1 } cout << i << endl; // illegal insert}
Ch 6/ Foil 20
Ch 6 / Foil 21
Global Scope
Objects that are not defined within a block are global objects A global object can be used by any function in the file that is
defined after the global object It is best to avoid programmer-defined global objects
Exceptions tend to be important constants Global objects with appropriate declarations can even be used in
other program files cout, cin, and cerr are global objects that are defined in
by the iostream library Local objects can reuse a global object's name Unary scope operator :: can provide access to global object even
if name reuse has occurred
Ch 6 / Foil 22
Example
int i = 1;int main f() { cout << i << endl; // insert 1 char i = 'a'; cout << i << endl; // insert a ::i = 2; cout << i << endl; // insert a cout << ::i << endl; // insert 2 return 0;}
Ch 6 / Foil 23
Integrating Quadratic Polynomials
A polynomial f(x) of degree n is a function whose value is the sum of n+1 terms where the terms are of the form aixi, 0 i n, with the restriction that an is not 0.
anxn + an–1xn–1 + … + a2x2 + a1x + a0
The area under the curve along the x-axis interval (s, t) for f(x) is
an ( sn +1 - tn+1) + an–1 ( sn - tn) + … + a1 (t2 - s2)/2 + a0 (t - s)
For a quadratic polynomial (degree 2) this equation reduces
a2(t3 - s3)/3 + a1(t2 - s2)/2 +a0(t - s)
Ch 6 / Foil 24
QuadraticArea()
double QuadraticArea(double a2, double a1, double a0, double s, double t) {
double term2 = a2*(t*t*t - s*s*s)/3.0;double term1 = a1*(t*t - s*s)/2.0;double term0 = a0*(t - s);return term2 + term1 + term0;
}
#include <iostream> // program 6.3#include <string>using namespace std; double QuadraticArea(double a2, double a1, double a0, double s, double t);int main() {
cout << "Enter quadratic coefficients (n n n): ";double a2, a1, a0;cin >> a2 >> a1 >> a0;cout << "Enter interval of interest (n n): ";double s, t;cin >> s >> t;double Area = QuadraticArea(a2, a1, a0, s, t);cout << "The area of quadratic polynomial " << a2 << "x*x + " << a1 << "x + " << a0 << " for (" << s << ", " << t << ")" << " is " << QuadraticArea(a2, a1, a0, s, t) <<
endl;}
Ch 6 / Foil 26
Recursion
Recursion is the ability of a function to call itself. Consider the mathematical function n!
n! = n * (n-1) … * 2 * 1
is not mathematically precise because we use an ellipsis (…). Consider the following formal definition
n! = 0, if n = 0 n! = n * (n-1)!, if n > 0
– The factorial function is defined in terms of itself
Ch 6 / Foil 27
Consider
#include <iostream>#include <string>using namespace std;int main() {
cout << "Enter a positive integer: ";int n;cin >> n;cout << n << "! = " << Factorial(n) << endl;return 0;
}
Ch 6 / Foil 28
Using
int Factorial(int n) {if (n == 0) {return 1;
}else {return n * Factorial(n-1);
}} C++ function mirrors the mathematical factorial definition
If the value of n is 0, the value 1 is returned. Otherwise, the product of n and Factorial(n-1) is returned.
Ch 6 / Foil 29
Recursion Visualization
Consider cout << n ! = " << Factorial(3) << endl;
cout << "n! = " << Factorial(3) << endl;
n = 3
n = 2
n = 1
n = 0
Factorial(3) = 3 * Factorial(2) = 3 * 2 = 6
Factorial(2) = 2 * Factorial(1) = 2 * 1 = 2
Factorial(1) = 1 * Factorial(0) = 1 * 1 = 1
Factorial(0) = 1
Activation records
call Factorial(0) return 1
call Factorial(1)
call Factorial(2)
call Factorial(3)
return 1
return 2
return 6