You are on page 1of 66

Topic 7

More on Functions

1
Functions with Parameters
 Remember that a function performs some tasks when it
is called with a functio n call.

 Before a function can be called, it must be declared with a


functio n proto type .

 The operation a function performs is defined with a


functio n de finitio n .

 We may or may not pass data to a function through its


parame te rs .
2
Functions with Parameters and Result
 A function may re turn or g ive back a re s ult just like the
function sqrt in the cmath library.
function sqrt
square root of
parameter
square root parameter value
value passed
computation returned as
to function
result

 A function gives back its result by executing a return


statement in the function body.

3
Functions with Parameters and Result
 Example: function that computes and returns area of circle:

/*
Computes area of a circle with radius r.
*/
double compute_area(double r)
{
return (PI * pow(r,2));
}
The function requires one formal
parameter of type double which
4 represents the radius of a circle.
Functions with Parameters and Result
 Example: function that computes and returns area of circle:

/*
Computes area of a circle with radius r.
*/
double compute_area(double r)
{
return (PI * pow(r,2));
}

The function returns a value of type double as the result. This


is the area of the circle with the given radius.
5
Functions with Parameters and Result
 Example: function that computes and returns area of circle:

/*
Computes area of a circle with radius r.
*/
double compute_area(double r)
{
return (PI * pow(r,2));
}

The expression in the return statement is evaluated and


the value is returned as the function result.
6
Functions with Parameters and Result
 When the function is called, we specify the actual
parameter.
 We also specify the variable where we want to store the
result.
 Example:
double radius = 10.0;

/* Call to function compute_area */


double area = compute_area(radius);

The variable where the The actual


result is stored. parameter.
7
Functions with Parameters and Result
double radius = 10.0;
double area = compute_area(radius);

r gets value of radius


that is 10.0

double compute_area(double r)
{
return (PI * pow(r,2));
}

8
Functions with Parameters and Result
double radius = 10.0;
double area = compute_area(radius);

double compute_area(double r)
{
return (PI * pow(r,2));
}

The expression is
evaluated to give the
value 314.159.
9
Functions with Parameters and Result
double =
radius radius
10.0;= 10.0;
area = area
double compute_area(radius);
= compute_area(radius);

The result
314.159 is
returned and double compute_area(double r)
replaces the {
function call return (PI * pow(r,2));
}

10
Functions with Parameters and Result
double radius = 10.0;
double area = compute_area(radius);
314.159 is
assigned to
area
double compute_area(double r)
{
return (PI * pow(r,2));
}

11
Functions with Parameters and Result
 We can also use the result in a object cout.

 Example:

// Call to function compute_area


cout << "Area = " << compute_area(10.0) << endl;

12
Functions with Parameters and Result

cout << "Area = " << compute_area(10.0) << endl;

r gets value 10.0

double compute_area(double r)
{
return (PI * pow(r,2));
}

13
Functions with Parameters and Result

cout
printf("Area=%lf\n",
<< "Area = " << compute_area(10.0)
find_area(10.0)); << endl;

double compute_area(double r)
{
return (PI * pow(r,2));
}

The expression is
evaluated to give the
value 314.159.
14
Functions with Parameters and Result

cout << "Area = " << compute_area(10.0) << endl;

The result
314.159 is double compute_area(double r)
returned and {
replaces the return (PI * pow(r,2));
function call }

15
Functions with Parameters and Result

cout << "Area = " << compute_area(10.0) << endl;

The result is displayed as follows:


Area = 314.159
double compute_area(double r)
{
return (PI * pow(r,2));
}

16
Local Variables
 A function may use variables just like the function main.

 All variables used in a function must be declared for


storing and retrieving values.

 These variables are called local variables because they


are defined or created only during the execution of the
function.

17
Local Variables
 Example: The local
variable are a is
double compute_area(double r)
used to store
{
the result of the
double area;
computation
which is then
area = PI * pow(r, 2);
returned as the
result of the
return area;
function.
}

18
Functions with Result but no Parameters
 We may have a function which returns a value but does
not have any parameters.

 A common use of such a function is to get some input


from the user and return the input value.

19
Functions with Result but no Parameters
 Example:
/*
Reads the radius of a circle.
*/ No parameter.
double get_radius(void)
{
double radius; // local variable

cout << "Enter radius: ";


cin >> radius;

return radius;
}
20
Functions with Result but no Parameters
 When the function is called, we specify the variable
where we want to store the result.
 Example:

// Call to function get_radius


double radius = get_radius();

The variable where the Empty parentheses


result is stored. because no parameters.

21
Functions with Result but no Parameters
double radius = get_radius();

No value passed

double get_radius(void)
{
double radius;

cout << "Enter radius: ";


cin >> radius;

return radius;
}
22
Functions with Result but no Parameters
double radius = get_radius();

The input value


double get_radius(void)
stored in the
{
local variable
double radius;
radius is
returned
cout << "Enter radius: ";
cin >> radius;

return radius;
}
23
Functions with Result but no Parameters
double radius = get_radius();
The value is
assigned to
radius
double get_radius(void)
{
double radius;

cout << "Enter radius: ";


cin >> radius;

return radius;
}
24
Complete Program
/*
Finds area of circle
*/
#include <iostream>
#include <cmath> // for pow function
using namespace std;

#define PI 3.14159

// function prototypes
double get_radius(void);
double compute_area(double r);
void display_area(double a);
25
Complete Program
int main(void)
{
double radius = get_radius();

double area = compute_area(radius);

display_area(area);

return 0;
}

26
Complete Program
/*
Reads the radius of a circle.
*/
double get_radius(void)
{
double radius; // local variable

cout << "Enter radius: ";


cin >> radius;

return radius;

}
27
Complete Program
/*
Computes area of a circle with radius r.
*/
double compute_area(double r)
{
return (PI * pow(r,2));
}

/*
Displays area of a circle.
*/
void display_area(double a)
{
cout << "Area is " << a << endl;
}
28
Structure Charts with Data Flow
 A structure chart can show data flow into and out of a
function

function1

Data in Data out

function2

29
Structure Charts with Data Flow

main

radius radius area area

get_radius compute_area display_area

30
Functions with Multiple Parameters
 A function may have more than one parameter.
 Example:
/*
Multiplies its first parameter by the power
of 10 specified by its second parameter.
*/
double scale(double x, int n)
{
double scale_factor; // local variable

scale_factor = pow(10, (double)n);

return x * scale_factor; casting


}
31
Complete Program
/*
Tests function scale
*/
#include <iostream>
#include <cmath>

using namespace std;

// Function prototype
double get_number();
int get_scale();
double scale(double x, int n);

32
Complete Program
int main(void)
{
// Get values for num1 and num2
double num1 = get_number();
int num2 = get_scale();

// Call function scale and display the result


cout << "Result of call to function scale "
<< "is " << scale(num1, num2) << endl;

return 0;
}

33
Complete Program
/*
Reads a real number.
*/
double get_number()
{
double num; // local variable

cout << "Enter a real number: ";


cin >> num;

return num;
}

34
Complete Program
/*
Reads the scale number.
*/
int get_scale()
{
int num; // local variable

cout << "Enter the scale number: ";


cin >> num;

return num;
}

35
Complete Program
/*
Multiplies its first parameter by the power
of 10 specified by its second parameter.
*/
double scale(double x, int n)
{
double scale_factor; // local variable

scale_factor = pow(10, (double)n);

return x * scale_factor;
}

36
Functions with Multiple Parameters
actual parameters
cout << "Result of call to function scale "
<< "is " << scale(num1, num2) << endl;

formal parameters information flow


double scale(double x, int n)
{
double scale_factor; // local variable

scale_factor = pow(10, (double)n);

return x * scale_factor;
}
37
Rules for parameter list correspondence
▪ The number of actual parameters in the function call and
formal parameters in the function prototype must match.

▪ The order of formal parameters and actual parameters


must match.
▪ The first actual parameter corresponds to the first formal
parameter, the second actual parameter to the second
formal parameter, and so on.

▪ The type of formal parameters and actual parameters


must match.

38
General Format for Function Header
 The general format for a function header is:
re turn-type functio n-name ( formal-parame te r lis t
)
 The general format for a function prototype is:
re turn-type functio n-name ( formal-parame te r lis t
);

 If the function does not return any result, write void for
the return type.
 If the function does not require any parameters, write void
for the formal parameter list
 No te : the parame te r name for the functio n pro totype is
optio nal.
39
The Function Data Area
 Each time a function call is executed, an area of memory
is allocated for storing the function’s data.

 This includes memory cells for any formal parameters


and local variables declared in the function.

 The function data is lost when the function terminates its


execution.

 It is recreated when the function is called again.

40
The Function Data Area
 After function main executes these statements:
double num1 = get_number();
int num2 = get_scale();

41
The Function Data Area
 After function main executes these statements:
double num1 = get_number();
int num2 = get_scale();

Data Area for Assume 2.5 and 2 entered by user


Function main

2.5 num1

2 num2

42
The Function Data Area

cout << "Result of call to function scale "


<< "is " << scale(num1, num2) << endl;

Data Area for Data Area for


Function main Function scale

2.5 num1 2.5 x


2 num2 2 n

? scale_factor
43
The Function Data Area
 After function scale executes this statement:
scale_factor = pow(10, (double)n);

Data Area for Data Area for


Function main Function scale

2.5 num1 2.5 x

2 num2 2 n

100 scale_factor
44
The Function Data Area
 After function scale executes this statement:
return x * scale_factor;

Data Area for


Function main

2.5 num1

2 num2

45
The Function Data Area
 This statement in main function continues to run:
cout << "Result of call to function scale "
<< "is " << scale(num1, num2) << endl;

The function result


Data Area for 250.0 will replace the
Function main function call.

2.5 num1

2 num2

46
Scope
 Scope determines the re g io n of the pro g ram in which an
object is visible – that is, the part of the program where
you can use the object’s name.

 The object may be a variable, a parameter, or a function


prototype.

47
Scope
 For a variable or parameter declared in a function, its
scope extends from its declaration to the end of the
function.
 This is called local scope.

 The area outside functions is called the global area.


 A function prototype is placed in this area. Its scope
extends from the prototype statement to the end of the
program.
 This is called global scope.

48
Scope
 The concept of scope allows functions to have same names
for variables or parameters.

49
Scope Example

50
Scope Example

Scope of a, b, y is from its


declaration until the end of
function main.

Scope of i, j, a, and y is from its


declaration until the end of
function fun.

51
Function Documentation
 The documentation for a function should include the
following:
▪ What the function does
▪ The condition that must be true befo re the function is
called – this is called the precondition
▪ The condition that must be true afte r the function
completes execution - this is called the
postcondition

The postcondition is normally already stated in what


the function does and is usually not necessary.
52
Function Documentation
 Example:
/*
Computes the area of a circle with radius r.
Pre: r is defined and is > 0.
PI is a defined constant representing an
approximation of pi.
Library cmath is included.
*/
double compute_area(double r)
{
return (PI * pow(r, 2));
}

53
Case Study 1
 Problem:
A hardware company manufactures washer rims. To
estimate shipping costs, the company needs a program
that computes the weight of a specified quantity of
washer rims.

54
Case Study 1
 Unde rs tand the pro ble m :
 A washer rim looks like a donut.
d1
 To compute its weight, you need the: d2
 rim area
 thickness
 density of the material used

 The rim area is computed from its inner(d1) and outer


(d2) diameters

55
Case Study 1
 Data requirements:
Problem constant
PI is 3.14159
Problem inputs
double hole_diameter; // diameter of hole
double edge_diameter; // diameter of edge
double thickness; // thickness of washer rim
double density; // density of material
double quantity; // number of washer rims made
Problem outputs
double weight; // weight of washer rims made
56
Case Study 1
Program variables
double rim_area; // area of washer rim
double unit_weight; // weight of one washer rim
Relevant Formulas
are a of a circle = π x radius 2
radius of a circle = diame te r / 2
rim are a = are a of oute r circle – are a of ho le
unit weig ht = rim are a x thickne s s x de ns ity

57
Case Study 1
 Design the solution:
Algorithm:
1. Get the washer rim’s inner and outer diameters.
2. Get the washer rim’s thickness and material density .
3. Get the quantity of washer rims made.
4. Compute the washer rim area.
5. Compute the weight of one washer rim.
6. Compute the weight of the batch of washer rims.
7. Display the weight of the batch of washer rims.

58
Case Study 1
Refined algorithm:
1. Get the washer rim’s inner and outer diameters.
2. Get the washer rim’s thickness and material density .
3. Get the quantity of washer rims made.
4. Compute the washer rim area.
4.1 Compute outer circle radius and hole radius.
4.2 rim area is outer circle area – hole area.
5. Compute the weight of one washer rim.
6. Compute the weight of the batch of washer rims.
7. Display the weight of the batch of washer rims.

59
Case Study 1 - Complete Program
/*
* Computes the weight of a batch of washer rims
*/
#include <iostream>
#include <iomanip> // for setprecision()
#include <cmath> // for pow()
using namespace std;

#define PI 3.14159

// function prototypes
double compute_rim_area(double h_d, double e_d);
double compute_area(double r);
double compute_unit_weight(double r_a, double t, double d);
double compute_total_weight(double u_w, double q);
void print_weight(double t_w);

60
Case Study 1 - Complete Program
// main function
int main(void)
{
// input data
double hole_diameter; // diameter of hole
double edge_diameter; // diameter of edge

double thickness; // thickness of washer rim


double density; // density of material
double quantity; // number of washer rims made

// output results
double weight; // weight of washer rims made

// program variables
double rim_area; // area of washer rim
double unit_weight; // weight of one washer rim
61
Case Study 1 - Complete Program
// Get inner and outer diameters
cout << "Inner diameter in cm: ";
cin >> hole_diameter;

cout << "Outer diameter in cm: ";


cin >> edge_diameter;

// Get thickness and density


cout << "Thickness in cm: ";
cin >> thickness;

cout << "Density in grams per cubic cm: ";


cin >> density;

// Get quantity made


cout << "Quantity in batch: ";
cin >> quantity;
62
Case Study 1 - Complete Program
// Compute washer rim area
rim_area = compute_rim_area(hole_diameter, edge_diameter);

// Compute weight of one washer rim


unit_weight = compute_unit_weight(rim_area, thickness,
density);

// Compute weight of batch of washer rims


weight = compute_total_weight(unit_weight, quantity);

// Display weight of batch of washer rims


print_weight(weight);

return 0;
} // end of main function

63
Case Study 1 - Complete Program
// function definitions
/*
Finds area of a washer rim with
inner diameter h_d and outer diameter e_d
*/
double compute_rim_area(double h_d, double e_d)
{
// local variables
double hole_radius; // radius of hole
double edge_radius; // radius of edge

hole_radius = h_d / 2.0;


edge_radius = e_d / 2.0;
return compute_area(edge_radius) -
compute_area(hole_radius);
}

64
Case Study 1 - Complete Program
/*
Finds area of a circle with radius r.
*/
double compute_area(double r)
{
return (PI * pow(r, 2));
}

/*
Finds weight of one washer rim with rim area r_a
thickness t and density d.
*/
double compute_unit_weight(double r_a, double t, double d)
{
return r_a * t * d;
}

65
Case Study 1 - Complete Program
/*
Finds weight of batch of washer rims with
weight of one washer rim u_w and quantity q.
*/
double compute_total_weight(double u_w, double q)
{
return u_w * q;
}

/*
Displays weight of batch of washer rims
*/
void print_weight(double t_w)
{
cout << "\nThe expected weight of the batch is "
<< fixed << setprecision(2) << t_w << " grams.\n";
}
66

You might also like