EEB 334 - Chapter 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Dr. Sajid M.

Sheikh
Senior Lecturer
Department of Electrical Engineering
University of Botswana

Office No: 248/106


Ext: 4956
Email: sheikhsm@ub.ac.bw

EEB 334: Computer Programming


CHAPTER 4
PROCEDURAL ABSTRACTION AND FUNCTIONS
1. Top-Down Design
• A good plan of attack for designing the algorithm is to break down the task to be
accomplished into a few subtasks, decompose each of these subtasks into smaller
subtasks and so forth
• This method is called top-down design.
• C++ has facilities to include separate subparts inside of a program.
• In C++ these subparts are called functions.
2. Predefined Functions
• Sqrt (square root) is one of the predefined functions. The value of the function
starts out with is called its argument. The value it computes is called the value
returned.
• The syntax for using the function is as follows:

the_root = sqrt (9.0)

• The expression sqrt (9.0) is called a function call.


• Function call
A function call is an expression consisting of the function name
followed by arguments enclosed in parentheses. If there is more than
one argument, the arguments are separated by commas. A function
call is an expression that can be used like any other expression of the
type specified for the value returned by the function.

Syntax:

Function_Name (Argument_list)

Examples
side = sqrt(area)
cout << “2.5 to the power 3.0 is ”
<< pow (2.5, 3.0);
• A function call

//computes the size of a dog house that can be purchased given the
//user’s buget

#include <iostream.h>
#include <math.h>
Int main()
{
const double COST_PER_SQ_FT =10;
double budget, area, length,_side;

cout << “Enter the amount budgeted for your dog house $”;
cin >> budget;

area = budget/COST_PER_SQ_FT;
length_side = sqrt(area);
cout.setf(ios : : fixed);
cout.setf(ios : : showpoint);
cout.precision (2);
cout << “For a price of $” << budget << endl
<< “I can build you a luxurious square dog house\n”
<< “that is ”<< length_side
<< “feet on each side. \n”;

return 0;

}
• Notice that there is another new element in the above program
#include <math.h>
• Such lines are called include directives. The name ending in .h is the name of a
file known as a header file.
• If your program uses a predefined function from some library, then it must
contain a directive that names the header file for that library, such as the
following

#include <math.h>
Some Predefined Function

Name Description Type of Arguments Type of value Library


returned Header

sqrt square root double double math.h


pow powers double double math.h
abs absolute value int int stdlib.h
for int
labs absolute value long long stdlib.h
for long
fabs absolute value double double math.h
for double
ceil ceiling (round up) double double math.h
floor floor double double math.h
(round down)
Type changing functions

• Recall that 9/2 is integer division, and evaluated to 4, not 4.5.


• If you want division to produce an answer of type double, then
at least one of the two numbers in the division must be of type
double.
• In C++ you can tell the computer to convert a value of type int
to a value of type double.
• E.g double (9)
• Using the type name double in this way is called type casting
Programmer – Defined Functions

Function Definition
• You can define your own functions, either in the same file as the
main part of your program or in a separate file so that the
function can be used by several different programs.
• The description of the function is given in two parts that are
called the function prototype and function definition.
• The function prototype describes how the function is called.
• C++ requires that either the complete function definition or the
function prototype appears in the code before the function is
called.

11
• A function Definition
#include <iostream.h>

double total_cost(int number_par, double price_par); //function prototype


//Computes the total cost, including 5% sales tax,
//on number_par items ata cost of price_par each.

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); //FUNCTION CALL


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;
}

double total_cost(int number_par, double price_par)


{
const doubel TAX_RATE = 0.05; //5% sales tax
double subtotal

subtotal = price_par * number_par


return (subtotal + subtotal*TAX_RATE);
}
• The function prototype tells you everything you need to know in order
to write a call to the function. It tell you the name of the function,
how many arguments the function needs and the type of the
arguments.
• To understand functions, keep the following three points in mind
• A function is like a small program and calling the function is the same
thing as running this “small program”
• A function uses formal parameters, rather than cin, for input. The
arguments to the function are the input and they are plugged in for
the formal parameters.
• A function does not send an output to the screen, but it does send a
kind of output back to the program. The function returns a value,
which is like the output for the function.
Alternate forms of function prototypes
• The following two prototypes are equivalent:
double total_cost(int number_par, double price_par);
and
double total_cost(int , double );

• The first form is used so that we can refer to the formal parameters in the
comment that accompanies the function prototype.
Procedural Abstraction

The black Box Analogy


• A person who uses a program should not need to know the
details of how the program is coded.
• A function is like a small program and should be used in a
similar way.
• A programmer who uses a function in a program needs to
know what the function does, but should not need to know
how the function accomplishes its task.
• This is often referred to as treating the function like a black
box.
• Writing and using functions as if they were black boxes is also
called procedural abstraction.
Local Variables

Local Variables
• Variables that are declared within the body of a function
definition are said to be local to that function or to have that
function as their scope.
• Variables that are defined within the main body of the
program are said to be local to the main part of the program or
to have the main part of the program as their scope.
• Such variables are said to be local variables
Global Constants and Global variables
• It can happen that more than one function uses a named
constant. In this case, you place the declaration for naming a
constant at the beginning of your program, outside of the body
of all the functions and outside the body of the main part of
your program. The named constant is then said to be a global
named constant and it can be used in any function definition
that follows the constant declaration
• It is possible to declare ordinary variables as global variables,
which are accessible to all function definitions in the file.
Overloading a function name

• If you have two or more function definitions for the same function name, that is
called overloading.
• When you overload a function name, the function definitions must have different
numbers of formal parameters or some formal parameters of different types.
• When there is a function call, the compiler used the function definition whose
number of formal parameters and types of formal parameters match the
arguments in the function call.
Overloading a Function Name
//Illustrates overloading the function name ave.
#include <iostream.h>

double ave(double n1, double n2)


//returns the average of the two number n1 and n2

double ave(double n1, double n2, double n3)


//returns the average of the three number n1, n2 and n3

int main()
{
cout << “the average of 2.0, 2.5 and 3.0 is”
<< ave(2.0, 2.5, 3.0) << endl;

cout << “the average of 4.5 and 5.5 is”


<< ave(4.5, 5.5) << endl;

return 0
}
double ave(double n1, double n2)
{
return ((n1+n2)/2.0);
}

double ave(double n1, double n2, double n3)


{
return ((n1+n2+n3)/3.0);
}

• The use of the same function name to mean different things is


called polymorphism. Overloading is our first example of
polymorphism
Local Variables
//Computes the average yield on an experimental pea growing patch.
#include <iostream.h>

double est_total(int min_peas, int max_peas, int pod_count);


//Returns an estimate of the total number of peas harvested.
//The formal parameter pod_count is thenumber of pods.
//The formal parameters min_peas and max_peas are the minimum
//and maximum number of peas in a pod.

int main()
This variable named average_pea is local to the main part of the program
{ int max_count, min_count, pod_count;
double average_pea, yield;
cout << “Enter minimum and maximum number of peas in a
pod: ”;
cin >> min_count >> max_count;
cout << “Enter the number of pods: ”;
cin >> pod_count;
cout << “Enter the weight of an average pea (n ounces): ”;
cin >> average_pea;

yield = est_total(min_count, max_count,


pod_count)*average_pea;

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(3);
cout << “Min number of peas per pod = ” << min_count
<< endl
<< “Max number of peas per pod =” << max_count <<
endl
<< “Pod count = ” << pod_count << endl
<<”Average pea weight = ”
<< average_pea << “ ounces” << endl
<< “Estimated average yield = ” << yield << “ ounces”
<< endl;

return 0;
}
double est_total(int min_peas, int max_peas, int pod_count)
This variable named average_pea is local to the function est_total.
{ double average_pea;

average_pea = (max_peas + min_peas)/2.0;


return(pod_count*average_pea);
}

Sample Dialogue
Enter minimum and maximum number of peas in a pod: 4 6
Enter the number of pods: 10
Enter the weight of a average pea (in ounces): 0.5
Min number of peas per pod = 4
Max number of peas per pod = 6
Pod count = 10
Average pea weight = 0.500 ounces
Estimated average yield = 25.000 ounces
A Global Named Constant
//Computes the area of a circle and the volume of a sphere.
/Uses the same radius for both calculations.
#include <iostream.h>
#include <math.h>
const double PI = 3.14159;
double area(double radius);
//Returns the radius of a circle with the specified radius.
double volume(double radius);
//Returns the volume of a sphere with the specified radius.
int main()
{
double radius_of_both, area_of_circle, volume_of_sphere;

cout << “Enter a radius to use for both a circle\n” << “and a
sphere (in inches): ”;
cin >> radius_of_both;
area_of_circle = area(radius_of_both);
volume_of_sphere = volume(radius_of_both);

cout << “Radius = ” << radius_of_both << “ inches\n”


<< “Area of circle = ” << area_of_circle << “square inches\n”
<< “Vol. of sphere = ” << volume_of_sphere << “ cubic inches\n”;
return 0;
}

double area(double radius)


{
return (PI*pow(radius, 2));
}
double volume(double radius)
{
return ((4.0/3.0)*PI*pow(radius, 3));
}
Sample Dialogue
Enter a radius to use for both a circle
and a sphere (in inches): 2
Radius = 2 inches
Area of circle = 12.5664 square inches
Vol of sphere = 33.5103 cubic inches

You might also like