CS1440 - Lab (4)
Activity 4-1

Goals

The goal is to learn about:
Predefined functions,
Type casting using functions that convert values between types,
Functions that return a value,
Procedural abstraction and the importance of argument ordering,
Scope of variables.

Preparations

Before we begin this lab, please change your directory to 1440 and in that directory, create the Lab4 directory. Change to that
directory and complete all your lab work in that directory. When the lab specifies a name for a file (or a program), you
MUST use that name or risk losing all credit for that part of the lab.

Activity 4-2 - Predefined Functions
A function is a subprogram that is used in a C++ program to perform a particular task such as obtaining data, carrying out
some calculations, displaying some information or messages, or displaying the output data.  In C++, there are many predefined
functions that are written to simplify the computations, but all functions are used in the same way -- by "calling" the function..
This activity introduces you to several predefined functions: pow,sqrt, ceil, floor.

When you use a function in your C++ program, the compiler does some checking to see if you are using the function
correctly.It checks the return type, the number of arguments (or parameters) and, the types of the arguments.The compiler does
this by comparing information in the "call" to information provided by the function "prototype."The prototypes for predefined
functions are located in "header files" that you must #include into your C++ program.

double sqrt(double value)

Prototype in:cmath

Purpose:Computes square root.

Example use:double d=sqrt(100.0);// d gets value 10.0

double pow(double base, double exponent)

Prototype in:cmath

Purpose:Computes base raised to power exponent:base exponent

Example use:double d=pow(3,4);//d gets value 81.0 = 34

double ceil(double value)

Prototype in:cmath

Purpose:Raises value to nearest whole number.

Example use:double d=ceil(3.4);//d gets value 4.0

double floor(double value)

Prototype in:cmath

Purpose:Lowers value to nearest whole number

Example use:doubled= floor(3.7);//d gets value 3.0

For functions that take more than 1 input argument, the order of the arguments is extremely important.For example, consider
the pow( ) function described above.If you wish to compute 34, which is 3*3*3*3 or 81, then you had better be sure to use
pow(3,4).If you get the order of the arguments wrong by using pow(4,3) you'll instead compute 43 which is 4*4*4 or 64, a
quite different value.

Your text describes some other predefined functions.You'll also see others (often without warning!) during the remainder of the
term.

Activity Followup

Write a program that uses each of these predefined functions and one additional function of your choosing that is
mentioned in your text but not in this activity.For each function, your program should ask the user for the inputs they
wish.(So, for sqrt( ) you'll ask for one value (the number whose square root is to be computed), and for pow( ) you'll
ask for the base and exponent values to pow.)

Save this program in a file named:predefined.C

Activity 4-3

Type Changing Functions - Type Casting

We've spoken about integer division and that it discards any "fractional part" of the quotient. This behavior is sometimes a
problem -- sometimes we'd rather not lose that fraction.One way to avoid losing the fractional part is to make sure that one of
the division operands is not an integer.It is easy enough to change an integer constant into a real (double) constant.For example,
just change 2 to 2.0 in your program.But what do you do when both operands of the / are int variables?Consider the following
program fragment:

int val1, val2, num_vals;
cin>>val1>>val2;
num_vals=2;
cout<<(val1 + val2)/num_vals;

The division in the last statement will be integer division.
How can we avoid this?
By changing one of the division operands to be a double value.
How can we do that?

Type changing predefined function to the rescue!!

All of our basic data types (int, char, double, see Chapter again for a more complete list) also have predefined functions to
change other types of data into their type of data, see Type Casting in Section 32.So, if you need a type double value where
you have an int expression, you can use the static_cast<double>(variable) function to tell the compiler to use the type
double version of the int value. Please note that in some C++ book this may have been shown as: <double>(variable), but in
our textbook static_cast<NewType>(variable) is the standard notation used for this purpose.  For example, the code below
tells the compiler to obtain the value of the int variable num_vals, figure out the equivalent type double value, and use that
value as the divisor (in a type double divide):

cout<<(val1 + val2)/static_cast<double>(num_vals);

Activity Followup

Cut and paste the following program into a file called changing.C and compile and run it.Then make some changes to continue
experimenting with combinations of type changing functions and their inputs.Carefully observe what the program execution
results are!

#include<iostream>

int main()
{
int i=37;
char c='a';
float flo= 76.4;
float fhi= 96.8;
double d=116.8;

cout<<"i="<<i<<endl;
cout<<"\t char version of i="<<static_cast<char>(i) << endl;
cout<<"\t float version of i ="<<static_cast<float>(i)<< endl;

cout<<"flo="<< flo << endl;
cout<<"\t char version of flo="<< static_cast<char>(flo)<< endl;
return 0;
}

Not sure what changes you can make?Try adding a bool variable and type changing function.Try other combinations like
static_cast<double>(i) and static_cast<int>(flo).You can't break anything, so EXPERIMENT!By the way, now is a good
time to learn how to cut and paste in Pico if you don't know already! (If you're adventurous, this might be a good time to try
using a more sophisticated editor like vi, vile, or emacs.)

Activity 4-4 - Functions that return a value
We can write our own functions to perform some computations.  The following program from your text will compute the total
cost of purchases made in a store.  In this program, we will use a function that computes the cost plus 5% sales tax of
purchases made.

/* P44.CThis program computes the total cost of purchases made */
#include <iostream>

// (1) Function prototype
//      total cost includes 5% sales tax,
//       on number_par items at a cost of price_par each.
double total_cost(int number_par, double price_par);

int main( )
{
double price,bill;
int number;

cout<<"Enter the number of items purchased: ";
cin>>number;
cout<<"Enter the price per item \$";
cin>>price;

bill= total_cost(number,price);// (2) Function call

/* The following three lines are used for formatting numbers.
Since a precision of 2 is set, then all type double numbers
will be displayed with two decimal places.  When the
numbers are money that is the way it should be.
More on this in a couple of weeks.
*/
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

cout << number << " items at "
<< "\$" << price << " each.\n"
<< "Final bill, including tax, is \$" << bill
<< endl;

return 0;
}

// (3) Function definition
double total_cost(int number_par,double price_par) /* Function heading */
{// Function body begins here
const double TAX_RATE = 0.05; //5% sales tax
double subtotal;

subtotal = price_par * number_par;
return (subtotal + subtotal*TAX_RATE);
}// Function body ends here

As you can see, we have used a function called total_cost to compute the cost plus 5% tax.  Note that this function has
computed the total cost and has returned a single value at
return (subtotal + subtotal*TAX_RATE);
The returned value is of type double.

Remarks
There are 3 things that you must remember when you work with functions.

1) A function must have a name. In the above program name was total_cost.
2) A function must have a type. The type for the above function is double.
3) A function must have correct parameter definitions.  This means that the parameters, if any, must have consistent types
and correct ordering at the a) function prototype, b) function call, and c) function definition.

Violation of any of these three will result in syntax or logical (run-time) errors.

Please note that the function used in the above program is of type double.  Thus, it returns a value of type double and in the
main function, that value was received by a variable of type double at:
bill = total_cost(number, price);

where bill is defined as double in the main function.

Activity Followup

Cut and paste the above program into a file named P44.Cand compile and run it.Then change the program to do the
following:

·Replace the final cout statement with a programmer (YOU!) defined function.
Note that this function will require 3 input arguments.Also, the function does not need to return a value so the
return type must be "void".

·Be sure to add a prototype for your new function.

Activity 4-5

Scope of a variable
Scope of a variable refers to the set of statements that can properly make explicit use of that variable -- the statements in
which you can correctly write a use of that variable. The scope of a variable declared inside a function is the body of that
function.  For example, in the above program, the variable bill is declared inside the body of the main function.  Thus, bill can
be used in the main function, but it is unknown in the total_cost function.  If we attempt to use bill without declaring it in the
function total_cost, we will get a syntax error that bill is undeclared.  If we put a declaration for bill in the function total_cost,
that variable bill will be a different variable from the one declared in the main function. Similarly, variable subtotal is unknown
to the main function, because it is a variable defined in the total_cost function and its scope is the body of the total_cost
function only.  These kinds of variables are referred to as local variables.  They are local to the function in which they are
declared.

There is, however, a method to define a variable such that it is known to all functions.  These types of variables are defined at
the top of the program right after the #include directives.  Any variable defined this way is known as a global variable.You
should use "const" with global variables.

The parameters passed to a function are also local to the function within which they are defined.  Thus, if the body of a function
contains statements that change the value of one of the formal parameters of the function, those changes cannot be "seen" by
the code that called the function. The function is working on a private copy of the value supplied in the call; it is not wrking with
the actual thing in the call. This is referred to as call_by_value. The following example will help you understand all these
definitions.
// scope.C
// This program illustrates the ideas of variable scopes
// and of call-by-value.

#include <iostream>
const int GLOBAL = 314 ;
// Here is a global variable
void myfunc(int local); // Function prototype
int main( )
{
int local, variable;
variable=7;
local=5;
cout << "Inside main BEFORE call to myfunc:" << endl;
cout << "\t GLOBAL = " << GLOBAL << endl;
cout << "\t local = " << local << endl;
cout << "\t variable = " << variable << endl;

myfunc(variable);

cout << "Inside main AFTER call to myfunc:" << endl;
cout << "\t GLOBAL = " << GLOBAL << endl;
cout << "\t local = " << local << endl;
cout << "\t variable = " << variable << endl;

return 0;
}

void myfunc(int local)
{
int variable;
variable=112;
local=113;
cout<< "Inside myfunc:" << endl;
cout<< "\t GLOBAL = " << GLOBAL << endl;
cout<< "\t local = " << local << endl;
cout<< "\t variable = " << variable << endl;
return ;
}

Cut and paste the program above into a file named scope.C and compile and run it.Convince yourself that you
understand why the output is NOT:

Inside main BEFORE call to myfunc:
GLOBAL = 314
local = 5
variable = 7
Inside myfunc:
GLOBAL = 314
local = 113
variable = 112
Inside main AFTER call to myfunc:
GLOBAL = 314
local = 113
variable = 112

Post Lab Exercise

1.Do Programming Project #1 on pages 170 of your text.Put the program in a file named mpg.C. Turn in a program listing
(harcopy).

2.Do Programming Project #8 on pages 172-3 of your text.Put the program in a file named clothes.C.Turn in a program
listing (harcopy).