Professional Documents
Culture Documents
FUNCTIONS IN C++
MODULE 2
Introduction
This lab will provide students with an introduction to the fundamentals of user-defined functions
in C++. The focus of this lab is on how to solve simple problems using C++ data types,
variables, and arithmetic operations. At the end of this module, students will
These exercises have two different types of answers. Some questions ask for answers to specific
questions; you should collect these answers in a Microsoft Word document.
Other exercises ask you to write code; for these exercises, structure your storage drive in the
following manner. There should be a palms folder, and within that folder there should be a
LabFunctions folder. All coding exercises (and related folders) for this lesson should be placed
in the LabFunctions folder. Lets begin!
This code uses two functions that C++ provides in the <cmath> standard library. The first line
uses the pow function to compute the result of raising a number to a power (in this case, the value
of side1 raised to the second power). We don't know how the function works, all we know is
that it will do a certain task and give us a result we desire. Likewise, the second line uses sqrt to
compute the square root of a given number (in this case, the value of sum).
When calling a function in C++, the function name is written first, followed by the inputs in
parentheses. For example, suppose the variable sum contained the value 9. The function call or
invocation sqrt(sum) would return the value 3. Similarly, the call sqrt(25) would return the
value 5, and pow(3, 2) would return the value 32 = 9.
A function call can appear anywhere in a C++ expression. When an expression containing a
function call is evaluated, the return value for that call is substituted into the expression.
For example, in the assignment "value = sqrt(4);", the call on the right-hand side would
evaluate to 2, and so the variable value would be assigned the value 2.
In order to use a function effectively, we need to know the type of data that is returned by the
function. We can only use C++ functions in expressions where data of the same type as the
function's return type is needed. For instance, the following code would not make sense:
char my_char;
my_char = sqrt(30);
Because sqrt returns a real number, it does not make sense to try and place that result into a
variable of type character. Watch and listen to the What is a C++ Function? podcast before
proceeding:
We can use this formula to create a C++ program. If converting temperatures was a task that you
were to perform relatively often in other programs, you would spend a lot of time remembering
and retyping this formula. Alternatively, you could encapsulate this computation in a function
and save it in a C++ file. Any time you wanted to convert temperatures, you could then add this
C++ file to your project and call the function. You wouldn't need to remember the formula
anymore, just the name of the function and how to call it.
The following is the definition of a C++ function that performs the temperature conversion. A
description of the key parts of this definition is given below:
The first eight lines are a function header comment, describing the important aspects of
the function (name, inputs, output, and purpose). You should always have comments in
your functions to improve readability.
The next line is the function header. The header specifies that you are defining a
function named fahrToCelsius with one input. The input value is represented by a
variable inside of the parentheses, also known as a parameter This variable name (fahr)
is preceded by the data type of that variable (in this case, double). When the function is
called, the input specified in the function call is assigned to the parameter for use in the
function's computation. For example, for the call fahrToCelsius(212), the parameter
fahr would be assigned the value 212. Thus, the value 212 would be used in the function
code as the value for fahr, resulting in the function returning the value 100.
The actual code that carries out the computation of the function is enclosed in curlybraces and is called the function body. In this example, there is only three C++ code
statements, but functions can contain any number of statements. A return statement is a
special C++ statement that specifies the value that should be returned by the function. It
consists of the keyword return followed by an expression. When a return statement is
executed, the expression is evaluated and the resulting value is returned as the value of
the function call.
In order to make a user-defined function accessible in a C++ program, it must be included in the
C++ project. This can be accomplished in two ways. When the function is specific to that
program only, its definition can be inserted directly into the .cpp file in the project; for instance,
int main()
{
// variable declaration and initialization
double fahr_temp = 0.0;
// variable declaration and initialization
double cel_temp = 0.0;
// prompt the user...
cout << "Enter a reading in fahrenheit degrees : ";
// input the value from the user...
cin >> fahr_temp;
// convert...
cel_temp = fahrToCelsius(fahr_temp);
// output the temperature, in both units...
cout << "You entered " << fahr_temp << " F degrees." << endl
<< "That is " << cel_temp << " C degrees." << endl;
// return success to the Operating System...
return 0;
}
Compile and run the program, and verify that it works as it should.
Next, watch and listen to the Walking Through a Function Call in C++ podcast before
proceeding. This podcast will present a dynamic view of how the above program executes.
If the user inputs an F, the degree reading is in Fahrenheit; your program should
convert the degrees to Celsius and output the result to the screen.
If the user inputs a C, the degree reading is in Celsius; your program should
convert the degrees to Fahrenheit and output the result to the screen.
Hint: You case use a predefined function called toupper to convert a character from
lowercase to uppercase. This may prove useful for your conditional tests. For example,
simplechar = toupper(simplechar); takes the value of simplechar and (if it is an
alphabetic character) returns the uppercase version of the letter. Simply add #include
<cctype> right below #include <iostream> to gain access to the function.
Local Variables
Notice from Exercise 1 that the function fahrToCelsius contains a single variable declaration,
namely
double celsius = 0.0;
The first line in this function is a variable declaration specifying that the new variable celsius
is to be used in the function. Declaring variables in this way signifies that they are local to the
function, meaning they will only exist inside of the function. In this sense, local variables are
similar to parameters. Declaring a local variable tells the C++ compiler that you are going to use
it as temporary storage while computing the function value, and that the storage should go away
i.e. be returned to the pool of available storage when execution of the function is complete.
In all functions, including main, variables have a defined scope, the area(s) and time for which
they are allowed to be used. In the case of C++ functions, this scope is limited to the code
statements within the beginning and ending brackets ({ }). The lifetime of these variables (i.e.
the time from which memory is allocated by the system to the time in which the memory is given
back) is the time for which the function is executing.
Global variables are variables declared outside of any function. Global variables are thus
accessible by any function within the code file. While the C++ language permits this
functionality, it is generally considered poor programming practice to declare variables with
global scope. Do not declare global variables in any program you create in this course.
///////////////////////////////////////////////////////////////////////////
//
//
FUNCTION NAME: main
//
PARAMETERS: None
//
RETURN TYPE: int
//
PURPOSE: Entry point for the application.
//
///////////////////////////////////////////////////////////////////////////
int main()
{
long low = 0, high = 0;
// prompt
// prompt
// input
cout << "\nThe sum from " << low << " to " << high;
cout << " is " << sumNumbers(low, high) << "\n";
// output
// output
return 0;
When the sumNumbers function is called in the main function, the following events occur:
1. Execution shifts to the sumNumbers function.
2. The inputs to the function are evaluated first, with the parameters min and max assuming
the values contained within low and high, respectively.
3. Within the function, new memory cells are allocated for the parameters min and max.
These memory cells are assigned the values of the corresponding arguments from the
call: the values contained within the variables low and high, respectively. Throughout the
function, any references to these parameters will be associated with these memory cells.
4. Memory cells are next allocated (created) for each local variable: counter and sum.
Similarly, any references within the function to these local variable names will be
associated with these memory cells. They are initialized with a zero value.
5. The statements in the function are executed in order, assigning sum the value of the sum
of the integers from min to max.
6. When the return statement is reached, the expression in the statement is evaluated,
yielding the value contained within sum.
7. After computing the return value, the execution of the function is over. Since the local
variables exist only inside the function itself, the memory cells associated with the
variables are de-allocated, i.e., made available for other uses.
8. Similarly, the memory cells associated with parameters are de-allocated.
Exercise #3: Create a new C++ workspace called incomeTax. Your main function should
prompt the user for his/her gross income and itemized deduction (both double values). Construct
a function called incomeTax which computes the tax due using the input values (gross income
and itemized deduction) as follows:
Total tax is determined by multiplying the taxable income by the tax rate (0.17).
Your main function should call your incomeTax function to compute the total tax due, giving it
appropriate arguments. Your incomeTax function should return the total tax due back to your
main function. Finally, your main function should output the tax due to the screen with a
descriptive message.
Please watch and listen to the Techniques for User-Defined Functions in C++ podcast before
proceeding. This podcast will present a description of how to create input,
processing/computation, and output functions. These tips will be used heavily in this course.
Once you have the maximum available power, computing the actual amount of power (not the
maximum) produced by the wind generator is a matter of determining the amount of power
based on the operating efficiency.
Exercise #4: Create a program to compute the amount of power produced by a wind generator.
Your program should take three double precision inputs (see the discussion above) before
performing its calculations. Create two functions other than main in your program. Both of these
functions will return a double value. One function should be called computeArea and should
take one double parameter named radius. The other function should be called
computeMaximumPower and should take two double parameters (named area and wind_speed).
You will need to call these functions from main function.
Your output should include two calculated results the maximum power output and the actual
power output. All numeric amounts should be precise to two decimal places. Remember: a
percentage is really a number between 0 and 1, inclusive. Here are few sample tests you can run
to check if your program is working correctly:
Test Case #1:
Enter the Average Wind Speed (in m/s): 5.0
Enter the Operating Efficiency [0...1]: 0.98
Enter the Blade Radius (in meters): 2.0
Maximum Power = 942.48, Actual Power = 923.63.