Chapter 16 - User_Defined Functions

advertisement
16 Programming in C/C++ - User Defined
Functions
Sections
16.1 Function Prototypes and Function Signatures
16.2 Some Example Problems
16.3 Some Guidelines
16.4 Scope
16.5 Style
Objectives
After completing this chapter you should:
1. Understand the basic structure of a function as used in C/C++
2. Be able to identify a function prototype and understand the meaning of each of the
components
3. Understand the difference between a function prototype and a function signature
4. Understand the elements of style common to well written C/C++ programs and be
able to incorporate them into your code
Introduction
Both Matlab and C/C++ allow the programmer to create reusable functions. In Matlab
the functions usually exist in function M-files. (Recall that Matlab supports a number of
different types of functions.) Function M-files are called by the script M-file program as
needed. In C/C++ functions are defined outside of the main function, but are included in
the same .cpp file. They can only be used by that program.
16.1 Function Prototypes and Function Signatures
When we use a function from a C/C++ library, we alert the program that we’ll need that
library by specifying a preprocessor directive. For example, when we want to use the log
function, we must specify the math library, using
#include <math>
To use a user-defined function we must also tell the program where to find it – since it
won’t be in any of the specified libraries. We do this using a function prototype, which
specifies the return type, function name, and a parameter list. For example suppose we
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
1
want to create a function called my_function, which requires a double precision input,
and returns a double precision result. The function prototype might be:
double my_function(double my_input);
The first double tells us that the output is a double precision floating point number,
my_function is the function name, and the double my_input inside the parentheses tells
us that the function requires a double precision floating point input argument. You
actually do not need to specify variable names for the input arguments – just the variable
type is sufficient ( for example double or int). Here’s an alternative way to define
my_function .
double my_function(double);
The function prototype is usually positioned after the namespace directive statement and
before the main function. The actual function can be defined either before or after the
main function – however placing it after the main function is the preferred approach as a
matter of style. The user defined function has the same format as the main function. It
starts with a function signature which is the same as the function prototype but without
the semicolon. (However, the variable names are required in the function signature.) The
function definition is inside curly braces immediately following the function signature.
An example outline of a program with a user defined function is shown in Figure 16.1
#include statements
using namespace std;
double my_function(double my_input);
int main()
{
main body of the program – my_function(my_input) is used in the program
somewhere
}
//************Add a comment line to separate the code sections **********
double my_function(double my_input)
{
function definition statements
}
Figure 16.1 – Outline of a C/C++ function
Although in this example the function returned a double and required a double as input,
any of the data types allowed in C/C++ could be used. If a function does not return
anything, use the data type void.
void f(double x);
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
2
16.2
Some example problems
Let’s write and test an example function to calculate the area of a triangle. The function
will need two inputs; the length of the base and the height of the triangle. It will return a
single value for the area. The function prototype might be:
double triangle_area(double base, double height);
Remember that we are only required to specify the data type of the input arguments in the
function prototype, but specifying the names is a useful style convention because it helps
us keep track of the variables. The function name must follow the standard naming
conventions.
The function itself might be:
double triangle_area(double base, double height)
{
double area;
area = 0.5 * base * height;
return area;
}
Notice that we did not need to define base and height inside the function as doubles – the
function signature did that for us. However, we did need to define area as a double.
Now we can use this function in a program such as the one shown in Figure 16.2 A
comment line of stars (*) is added between the main function and the user defined
function as a matter of style. This makes it easier to find the different sections of the
program. In this example the lines of code directly related to the function are shown in
red, to make them easier to identify.
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
3
#include <iostream>
using namespace std;
double triangle_area(double base, double height);
int main()
{
double b, h, a;
cout<<"Enter a value for the base: ";
cin>>b;
cout<<"Enter a value for the height: ";
cin>>h;
a = triangle_area(b,h); // The function is called here
cout<<"The area is: "<<a<<endl;
return EXIT_SUCCESS;
}
//********************************************************
double triangle_area(double base, double height)
{
double area;
area = 0.5 * base * height;
return area;
}
Figure 16.2 A simple program containing a function
The functions you create in C/C++ can be as simple as the example problem, or can
include selection structures (if statements) and repetition structures (loops). For example,
create and test a function to evaluate the sinc of x.
Recall from previous chapters in Matlab for Engineers that
sinc(x) = sin(x)/x
However, when x is equal to zero this expression is undefined. (sin(0) = 0, so sin(0)/0 is
undefined.) When L’Hopital’s rule is invoked, we can show that sinc(0) is equal to 1.
(Remember that most computer programs, including C/C++ require the input to
trigonometric functions in radians).
To do this we’ll have to use a selection structure. When x is equal to 0 the function
should return a value of 1. When x is any other value we should evaluate sin(x)/x. In the
program shown in Figure 16.3 the user is prompted to enter a value of x . The main
function then calls the sinc function and uses it to find the value of sinc(x), and sends the
result to the screen.
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
4
#include <iostream>
#include <math>
using namespace std;
double sinc(double x);
int main()
{
double a;
cout<<"Enter a value of x: ";
cin>>a;
cout<<"The sinc of "<<a<<" is: "<<sinc(a)<<endl;
return EXIT_SUCCESS;
}
//********************************************************************
double sinc(double x)
{
double answer;
if(x==0)
answer = 1;
else
answer = sin(x)/x;
return answer;
}
Figure 16.3 A program containing a more complicated function that uses an if structure
C/C++ functions can be used by any other function in the program. For example, we
could use the sinc function inside either the main function, as we did in Figure 16.3, or
we could used it in a second user defined function.
For example, a common calculation made when analyzing electrical circuits involves
determining the power associated with an electrical device. Power is a measure of the
rate electrical energy is being delivered from an electrical source to an electrical load, and
is often measured in Watts – which is the same as Joules/second. For a simple resistive
load of R Ohms, the power delivered to the resistor when a voltage v volts is applied is:
p
v2
R
Mathematically it is more correct to express this equation as
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
5
p (t ) 
v 2 (t )
R
since power changes with time, and voltage changes with time.
If we let v(t) = sinc(t), we can call our sinc function from within an new function written
to calculate p(t). (Remember, the syntax v(t) means that the voltage varies with t)
Using our previously defined sinc function, let’s create a new function that calculates the
power at any time t delivered to a resistive load when a voltage equal to sinc(t) is applied.
Then we’ll test our results in a complete C/C++ program.
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
6
#include <iostream>
#include <math>
using namespace std;
double sinc(double x);
double sincPower(double t, double R);
int main()
{
double time, Resistance;
cout<<"Enter a value of time: ";
cin>>time;
cout<<"Enter a value of resistance, R: ";
cin>>Resistance;
cout<<" Value of power is "<< sincPower (time, Resistance)<<endl;
return EXIT_SUCCESS;
}
//******************************
double sinc(double x)
{
double answer;
if(x==0)
answer = 1;
else
answer = sin(x)/x;
return answer;
}
//*******************************
double sincPower(double t, double R)
{
double power;
power = pow(sinc(t),2) / R;
return power;
}
Figure 16.4 – A program where a user defined function calls another user defined
function
Notice that two user-defined functions were specified in the program. However the main
function only called one of them – sincPower. The other function (sinc) was called from
the sincPower function.
We can expand this example program one more time to create a table of time values and
the corresponding power levels. This requires that we use a loop in the main program
and call sincPower each time through the loop.
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
7
#include <iostream>
#include <math>
using namespace std;
double sinc(double x);
double sincPower(double t, double R);
int main()
{
double time, Resistance;
cout<<"Enter a value of resistance, R: ";
cin>>Resistance;
cout<<" time
power"<<endl;
for(double time=0; time<=100; time=time+10)
cout<<time<<"
"<<sincPower (time, Resistance)<<endl;
return EXIT_SUCCESS;
}
//******************************
double sinc(double x)
{
double answer;
if(x==0)
answer = 1;
else
answer = sin(x)/x;
return answer;
}
//*******************************
double sincPower(double t, double R)
{
double power;
power = pow(sinc(t),2) / R;
return power;
}
Figure 16.5 – A program that uses a loop in the main function to call a user-defined
function
You can see the results in Figure 16.6.
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
8
Figure 16.6 - Results from the program in Figure 16.5.
Practice Exercise 16.1
Create and test a function to convert temperature in 0C to 0F. The equation is
Tf = Tc *9/5 + 32
In your program, use the function prototype
double C_to_F(double C);
Your program should prompt the user for a value in degrees C, then report the
answer in degrees F. Remember, the logic to perform the conversion must be in the
function, but the interaction with the user should be in the main part of the program.
Practice Exercise 16.2
The ideal gas law
PV = nRT
requires that the temperatures used in the equation be absolute. That means that if we are
using SI units, temperature must be in K, not 0C. Create a program to find the pressure in
a container, assuming we know:
V - the volume of the container in m3
n - the number of moles of gas in the container
T – the temperature
R is the universal gas constant and is equal to 8.314 kPa m3/mole K
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
9
The program should prompt the user for
V – volume in meters
n – the number of moles
T – the temperature --- in 0C
It should use the following two functions :
double C_to_K(double Temp_C); which converts the temperature from C to K
double pressure(double V, double n, double T); which calculates the pressure
– assuming the temperature T in the input arguments is in degrees C.
Test the program with a temperature of 35 0C, a volume of 1 m3 and 1 mole of gas.
16.3
Some Guidelines
Although it is possible to create functions that use all of the C/C++ language
functionality, it isn’t necessarily a good idea.
16.3.1 Input/Output
The only way you should communicate with a function is through the input arguments.
The only way you should get results from a function is through the return statement at the
end of the function. This means that you should not use cin or cout statements in the
function.
16.3.2 Return
It is possible to craft code with multiple return statements. For example, in the function
shown in Figures 16.3, 16.4 and 16.5 we could have used the following syntax.
double sinc(double x)
{
double answer;
if(x==0)
return = 1;
else
return = sin(x)/x;
}
This would have worked just fine. However, it is preferable to have a single return from
a function. It makes the function easier to understand and debug.
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
10
16.4
Scope
As you write more complicated programs it is natural to divide the code into sections.
We’ve already done this when we added loops. The curly brackets that identify the
beginning and end of the loop are the dividers that create the small section of code.
When variables are created in a program they only apply to the section of code where
they are defined.
To better understand this, consider how the American legal system works. Laws enacted
by congress apply to the entire country. They have a national “scope”.
Apply to all
the states
National Laws
However, the United States is divided into sections called states, and each state can enact
its own laws.
Laws enacted in Utah only apply to Utah. They
don’t apply for example in Montana. The
“scope” of the law is limited to the state where
it is enacted. However, these laws do apply to
all the cities in the state. Similarly cities can
enact regulations that apply to that city, but not
to other cities. There scope is even more limited.
Consider this outline of a piece of C/C++ code
{
Top level
…. miscellaneous code
double x;
{
…. miscellaneous code
double y;
}
Sub Section
of code
}
The variable x is defined in the top level of code, so it applies to everything inside the
outer brackets, including what is in the inner brackets. The variable y on the other hand
is defined inside the inner brackets, and therefore only applies in that section of code. If
we tried to use y outside the small sub section where it is defined an error would be
generated.
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
11
Why is this important to us? If you define a variable inside a loop for example, it only
exists inside the loop. If you try to use it someplace else an error results. This means that
you need to define variables at the highest level that includes all the locations where the
variable will be used.
Consider this code snippet used to calculate 5 factorial. (Recall that 5 factorial is
1*2*3*4*5 and is shown in math texts as 5!)
double product=1;
for(int k=1; k<=5; k++)
{
product = product*k;
}
cout<<product<<endl;
The variable product exists throughout the entire piece of code. The variable k,
however, is defined inside the for loop, and only exists between the curly brackets. If we
try to use k outside the loop an error occurs. In this case this is an advantage, not a
problem because we can use k again in another for loop without worrying that there may
be unforeseen interactions between the loops.
So how does this apply to user-defined functions? Variables are local only to the
function where they are defined – so a variable defined in the main function does not
exist in the user-defined function. You may have noticed that we used different variable
names in the main portion of the programs written in this chapter than were used in the
user-defined functions. This is a style issue, intended to help the programmer keep the
variables straight. When a variable is defined it only has meaning in the section of the
program where it was defined, so we could have reused variable names in both the main
and user-defined functions – but they wouldn’t affect each other!
Here’s an example. Suppose we want to create a function to find the force applied to a
mass due to gravity. The equation is simple
F = mg
where F is force
m is mass and
g is the acceleration due to gravity. This is a constant on the earth equal to 9.8
2
m/s . If we use SI units mass is measured in kg and force is measured in N (Newtons).
Figure 16.7 shows a simple program that prompts the user to enter a mass, and uses a
function to calculate the force due to gravity.
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
12
#include <iostream>
using namespace std;
double force(double mass);
int main()
{
double m;
cout<<"Enter a value of mass in kg:";
cin>>m;
cout<<"That corresponds to a force due to gravity of "<<force(m)<<" N"<<endl;
}
//**********************************************************************************
double force(double mass)
{
const double g = 9.8;
return mass*g;
}
Figure 16.7 A program to calculate the force due to gravity using a function.
Notice that g was defined inside the function. If it had been defined in the main function
this program would not have worked.
Also notice that in the main function m is the symbol used for mass. The function
“knows” that the value of m should be used for the variable mass because it is the input
argument to the function.
16.5
Style
At this point in our study of C/C++ it would be a good idea to step back, and think for a
minute about what constitutes good programming style. We know how to do a lot of
things, but good style makes it easier to read and debug your code.
When we say style in programming, we are essentially referring to the
readability of the source code file to humans. There are several components
of style in programming
Before we discuss some basic components of good programming style, let's see a few
examples of POOR style. In 1984, a unique contest was created to ironically show the
importance of programming style. This contest is called the Obfuscated C programming
contest. Take a few moments to look at last year's winners. One of the more confusing
ones is an entry in 2001 from herrmann1. Notice how difficult it is to figure out what the
program does--it almost looks like gibberish!
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
13
Poor programming style can dramatically impact a program for the worse. Take this
program for example. (Figure 16.8) Although it compiles and runs as designed, can you
figure out what it does? (Copy and paste it into your C/C++ compiler and try it out)
#include <iostream>
using namespace std;
int main()
{ double q1,q2=0,c,ch=0.0;char g;cin>>g>>ch;switch(g){case
'a':q1+=4*ch;break;case 'b':q1+= 3*ch;break;case
'c':q1+=2*ch;break;case'd':q1+=1*ch;break;}q2+=4*ch;c=(q1/q2)*4;cout<<q1<<"
" << q2<<" " <<c<< endl;return 0; }
Figure 16.8 – An example of poor programming style
Elements of good style can be grouped into the following categories:





Program header
Variable naming
Documentation
White space
Code reuse
Let's examine each of these topics.
16.5.1 Program header
The program header is a multi-line header that goes at the beginning (first lines of code in
your source code) of the program to describe the author, date and program purpose. For
our class, each of your programs should start with a header like this:
/***************************************************************
Your name
Date
Brief project description
*************************************************************** */
16.5.2 Variable naming
Variables play such a critical role in our programs, it is important for us to give them
meaningful names. C++ allows us to name our variables with up to 255 characters! As
such, there is really no reason to abbreviate our variable names, since they may not be
clear to others who view the program.
To make variable names more readable, we will follow a modified Hungarian notation.
This means that the first letter of each new word in the variable name gets capitalized,
like this: taxRate, totalCreditHours, countyTaxRate. (David prefers this approach.)
An alternative is to use an underscore between words in the name; tax_rate,
total_credit_hours, county_tax_rate. (Holly uses this approach)
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
14
In addition to naming, we should declare all variables used in a particular block of code
at the TOP of each block. For the simple programs we have done so far, this means
declaring the variables immediately following int main():
/* ********************************************
David Moss
CS 1050
CGPA demo program
*********************************************** */
#include <iostream>
using namespace std;
int main()
{
// variable declarations
double qualityPointsEarned, totalQualityPoints = 0.0;
char gradeLetter;
double cgpa, creditHours = 0.0;
...
}
Figure 16.9 Example of a program with better style
16.5.3 Documentation
Documentation consists of several parts: documenting methods, "steps" of code, complex
lines of code and end of code blocks.
At the beginning of each method (or function), we should put a brief method header that
describes the purpose of the method, any necessary input, and the output. A sample
method header could be:
/* *****************************************
The calculateTax method determines the amount of sales tax
to be paid for any given subtotal.
Input: subtotal - a currency amount representing the subtotal for the purchase
Returns: the total amount of sales tax to be paid
******************************************* */
double calculateTax(double subtotal)
{
...
}
Figure 16.10 – Example of a method header
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
15
In the body of our code, we should place a single line comment before each "step" of
code. Each "step" could be a complex line, or it could consist of several lines of code:
// calculate cgpa
cgpa = qualityPointsEarned / totalQualityPoints * 4;
// display results
cout << "Quality points earned: " << qualityPointsEarned << endl;
cout << "Possible quality points: " << totalQualityPoints << endl;
cout << "Your CGPA would be " << cgpa << endl;
Figure 16.11 – Comments identify each step in the code
It is also helpful to place a comment at the end of each code block (so you know how to
match up the } in your programs.
16.5.4 White space
White space refers to indentation, blank lines between "steps" and spacing on individual
lines. Notice the difference in readability between:
cgpa=qualityPointsEarned/totalQualityPoints*4;
and
cgpa = qualityPointsEarned / totalQualityPoints * 4;
In addition to placing white space on individual lines, you should to put a blank line
between each "step" in your program to make it more readable:
// calculate cgpa
cgpa = qualityPointsEarned / totalQualityPoints * 4;
// display results
cout << "Quality points earned: " << qualityPointsEarned << endl;
cout << "Possible quality points: " << totalQualityPoints << endl;
cout << "Your CGPA would be " << cgpa << endl;
The last component of white space is indentation. For each new block of code that we
start, we need to indent each line in that block one tab stop. A few examples may help to
illustrate:
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
16
if (score >= 90 && score <=100)
cout << "You have earned an A." << endl;
switch (gradeLetter)
{
case 'A' :
case 'a' : qualityPointsEarned += 4 * creditHours;
break;
case 'B':
case 'b' : qualityPointsEarned += 3 * creditHours;
break;
case 'C':
case 'c' : qualityPointsEarned += 2 * creditHours;
break;
case 'D':
case'd' : qualityPointsEarned += 1 * creditHours;
break;
case 'E':
case 'e' : break; // really, nothing to do here!
default : cout << "Invalid grade entered!" << endl;
break;
} // switch
Figure 16.12 – White space makes your code easier to read
16.5.5 Code reuse
Code reuse is an important issue in designing your program. In the cgpa example, we
can see (to an extent) code reuse since we are calculating the totalQualityPoints
OUTSIDE of the switch statement (rather than putting it in each case statement). Also,
our switch statement is checking for both upper and lowercase grade letters without
duplicating any code.
A general rule of thumb is if you find yourself writing similar lines of code 3 times or
more, you need to redesign your program (rewriting your block of code, creating a
method, etc.).
16.5.6 Conclusion
In conclusion, take a look at the cgpa.cpp file that contains each of the style elements we
have discussed.
/* ********************************************
David Moss
CS 1400
CGPA demo program
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
17
*********************************************** */
#include <iostream>
using namespace std;
int main()
{
// variable declarations
double qualityPointsEarned, totalQualityPoints = 0.0;
char gradeLetter;
double cgpa, creditHours = 0.0;
// initial input
do
{
cout << "Enter the grade you received (A-E, q to quit): ";
cin >> gradeLetter;
if (gradeLetter != 'q')
{
cout << "Enter the number of credit hours for the class: ";
cin >> creditHours;
// calculate quality points for the grade given
switch (gradeLetter)
{
case 'A' :
case 'a' : qualityPointsEarned += 4 * creditHours;
break;
case 'B':
case 'b' : qualityPointsEarned += 3 * creditHours;
break;
case 'C':
case 'c' : qualityPointsEarned += 2 * creditHours;
break;
case 'D':
case'd' : qualityPointsEarned += 1 * creditHours;
break;
case 'E':
case 'e' : break; // really, nothing to do here!
default : cout << "Invalid grade entered!" << endl;
break;
} // switch
// calculate total possible quality points
totalQualityPoints += 4 * creditHours;
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
18
} // if
} while (gradeLetter != 'q');
// calculate cgpa; assuming a 4 point grade scale
cgpa = qualityPointsEarned / totalQualityPoints * 4;
// display results
cout << "Quality points earned: " << qualityPointsEarned << endl;
cout << "Possible quality points: " << totalQualityPoints << endl;
cout << "Your CGPA would be " << cgpa << endl;
// pause to display results
cout << "Press enter to continue...";
cin >> gradeLetter;
return 0;
} // main
Figure 16.13 – An example of all the elements of style discussed
Homework
Use the elements of good style described in section 16.5 as you create programs to solve
these homework problems. The most common problems we’ve seen students have with
these problems are:



forgetting that there is no caret operator in C/C++. To raise a number to a
power use the pow function.
defining constants in the main function, and then trying to use them in user
defined functions. Don’t forget that C/C++ uses local variables, whose scope
is limited to the function where they are defined.
never use cin or cout statements inside a user-defined function. The only
communication to the function should be through the input arguments and the
return statement.
16.1 As described in example 6.2, metals are actually crystalline materials. Metal
crystals are called grains. When the average grain size is small, the metal is strong; when
it is large the metal is weaker. Since every crystal in a particular sample of metal is a
different size, it isn’t obvious how we should describe the average crystal size. The
American Society for Testing and Materials (ASTM) has developed a correlation for
standardizing grain size measurements.
N = 2n-1
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
19
The ASTM grain size (n) is determined by looking at a metal sample under a
microscope at a magnification of 100x (100 power). The number of grains in a 1
square inch area (actual dimensions of 0.01 in x 0.01 inch) is estimated (N) and
used in the equation above to find the ASTM grain size.
Write a C/C++ function called num_grains to find the number of grains in a 1
square inch area (N) at 100x magnification, when the ASTM grain size is known.
The function prototype should be
double num_grains(double grain_size);
Test your function in a program that prompts the user for the grain size.
16.2 Perhaps the most famous equation in physics is:
E=mc2
which relates energy (E) and mass (m). The speed of light in a vacuum, c, is the
property that links the two together. The speed of light in a vacuum is
2.9979 x 108 m/s.
Create a function called energy to find the energy corresponding to a given mass
in kg. Your result will be in Joules, since a kg m2/s2 is equal to a Joule. The
function prototype should be:
double energy(double m);
Don’t forget to specify the speed of light inside the function.
16.3 In freshman Chemistry the relationship between moles and mass is introduced
n= m/MW
where n is the number of moles
m is the mass and
MW is the molecular weight (molar mass).
a. Create a function called nmoles that requires two inputs, the mass and
molecular weight, and that returns the corresponding number of moles.
The function prototype should be:
double nmoles(double mass, double Mol_Weight);
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
20
b. Test your function in a program, for the compounds shown in the table,
each with a mass of 10 grams. You’ll need to call the function 3 times,
once for each of the compounds.
Compound
Benzene
Ethyl Alcohol
Refrigerant R134a
(tetraflouroethane)
Molecular Weight (Molar Mass)
78.115 g/mol
46.07 g/mol
102.3 g/mol
16.4 Create and test a function to solve the following problem .
You decide to start a college savings plan now for your child, hoping to have enough in
18 years to pay the sharply rising cost of an education. Assume a well off friend gives
you some amount of money to get started, and that each month you can contribute a
given amount Also assume the interest rate is constant and is compounded monthly,
which is equivalent to (yearly rate)/ 12 per month.
Each month your balance will increase because of interest payments and your
contribution.
New Balance = Old Balance + interest + your contribution.
Use a for loop in the function to find the amount in the savings account at the end of a
specified number of years. Use the following variable names
inv
cont
rate
years
initial investment
monthly contribution
monthly interest rate
years in the plan
The function prototype should be:
double savings_plan(double inv, double cont, double rate, double years);
Test your function by assuming the following inputs
inv
cont
rate
years
$1000
$100
0.5%
18
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
21
16.5 Chemical reaction rates depend upon a number of factors, including the
concentration of reactants, and the temperature at which the reaction occurs. For the
simplest case
rate = k*[A]
where k is the reaction rate constant, and [A] is the concentration of a reactant in
moles/liter.
The reaction rate constant varies with temperature and activation energy.
k  k0 e(  Q / RT )
Where
k0 is a constant that is characteristic of the reaction
Q is the activation energy for the reaction
R is the ideal gas constant, 1.987 cal/mole K
T is the temperature in Kelvins
Create a function to find the reaction rate constant, k, which accepts values of k0, Q
and T as input, and returns the value of k. The function prototype should be:
double rate_constant(double k0, double Q, double T);
Create a second function that uses the rate_constant function to find the reaction rate.
It should accept four inputs, k0, Q, T and the concentration of A. The function
prototype should be:
double reaction_rate(double k0, double Q, double T, double conc_A);
Test your functions in a program that prompts the user for the appropriate inputs.
This problem is very similar to the one solved in Figure 16.4.
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
22
Solution to the Practice Exercise
/* ******************
Practice Exercise 16.1
Holly’s solution
June, 2006
****************** */
#include <iostream>
using namespace std;
double C_to_F(double C);
int main()
{
// define variables
double F, C;
// prompt the user for input
cout<<"Enter a value of temperature in degrees C: ";
cin>>C;
//perform calculations using a function
F= C_to_F(C);
//display results
cout<<C<<" degrees C equals "<<F<<" degrees F"<<endl;
return EXIT_SUCCESS;
} // main
//********************************
double C_to_F(double C)
{
/* *************************************************
Holly Moore
June 2006
A function to convert degrees Celsius to degrees Fahrenheit
************************************************** */
return C*9.0/5.0 + 32;
}
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
23
/* *******************************
Practice Exercise 16.2
Holly's solution
December, 2006
******************************** */
#include <iostream>
using namespace std;
double C_to_K(double Temp_C);
double pressure(double V, double n, double T);
int main()
{
double vol, moles, C;
cout<<"Enter the temperature in degrees C: ";
cin>> C;
cout<<"Enter the volume in cubic meters: ";
cin>> vol;
cout<<"Enter the number of moles in the container: ";
cin>> moles;
cout<<"The pressure is: "<<pressure(vol, moles, C)<<" kPa"<<endl;
return EXIT_SUCCESS;
}
// ***************************************
double C_to_K(double Temp_C)
{
return Temp_C + 273.15;
}
// ***************************************
double pressure(double V, double n, double T)
{
const double R = 8.314;
double K;
K = C_to_K(T); // Convert C to K using the function
return n*R*K/V;
}
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
24
Results from Practice Exercise 16.2
Chapter 16 – Matlab for Engineers – Introduction to C++ - User Defined Functions
25
Download