COMPUTER PROGRAMMING
LECTURE # 6: FUNCTIONS - A
BSE 2A & 2B
Rafia Hassan
1
[email protected]
Department of SE
Bahria University Islamabad
Procedural Abstraction
• The Black Box Analogy
- A black box refers to something that we know how
to use, but the method of operation is unknown
- A person using a program does not need to know
how it is coded
- A person using a program needs to know what the
program does, not how it does it
• Functions and the Black Box Analogy
- A programmer who uses a function needs to know
what the function does, not how it does it
- A programmer needs to know what will be produced
- if the proper arguments are put into the box
2
INFORMATION HIDING
• Designing functions as black boxes is an
example of information hiding
- The function can be used without knowing how
it is coded
- The function body can be “hidden from view”
3
Function Implementations
& The Black Box
• Designing with the black box in mind allows us:
- To change or improve a function definition without
forcing programmers using the function to change
what they have done
- To know how to use a function simply by reading the
function declaration and its comment
4
INTRODUCTION
Divide and conquer
Construct a program from smaller pieces or components
Each piece more manageable than the original program
Modules: functions and classes
Programs use new and “prepackaged” modules
New: programmer-defined functions, classes
Prepackaged: from the standard library
Functions invoked by function call
Function name and information (arguments) it needs
Function definitions
Only written once
Hidden from other functions 5
FUNCTIONS
Functions
Modularize a program
Software reusability
Call function multiple times
Local variables
Known only in the function in which they are defined
All variables declared in function definitions are local
variables
Parameters
Local variables passed to function when called
Provide outside information
6
STANDARD C++ LIBRARY FUNCTIONS
The Standard C++ Library is a
collection of pre-defined
functions and other program
elements which are accessed
through header files. For
example:
• INT_MAX constant defined in
<climits>
• sqrt() function ndefined in
<cmath>
• rand() function defined in
<cstdlib>
• time() function defined in
<ctime>
7
PREDEFINED FUNCTION
C++ comes with libraries of predefined functions
Perform common mathematical calculations
Include the header file <cmath>
Functions called by writing
functionName (argument);
or
functionName(argument1, argument2, …);
Example
cout << sqrt( 900.0 );
sqrt (square root) function The preceding statement would print 30
All functions in math library return a double
8
FUNCTION LIBRARY
Predefined functions are found in libraries
The library must be “included” in a program to make the functions
available
An include directive tells the compiler which library header file to
include.
To include the math library containing sqrt():
#include <cmath>
Newer standard libraries, such as cmath, also require the directive
9
using namespace std;
FUNCTION ARGUMENTS
Function arguments can be
Constants
sqrt( 4 );
Variables
sqrt( x );
Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );
Error-Prevention Tip:
10
Do not call sqrt with a negative argument
FUNCTION CALLS
sqrt(9.0) is a function call
It invokes, or sets in action, the sqrt function
The argument (9), can also be a variable or an expression
A function call can be used like any expression
bonus = sqrt(sales) / 10;
cout << “The side of a square with area “ << area << “ is “<<
sqrt(area);
11
12
OTHER PREDEFINED FUNCTIONS
abs(x) --- int value = abs(-8);
Returns absolute value of argument x
Return value is of type int
Argument is of type x
Found in the library cstdlib
fabs(x) --- double value = fabs(-8.0);
Returns the absolute value of argument x
Return value is of type double
Argument is of type double
Found in the library cmath
13
14
TESTING A TRIGONOMETRY IDENTITY
15
PROGRAMMER DEFINED FUNCTION
Function prototype
Tells compiler argument type and return type of function
int square( int );
Function takes an int and returns an int
Explained in more detail later
Calling/invoking a function
square(x);
Parentheses an operator used to call function
Pass argument x
Function gets its own copy of arguments
After finished, passes back result
16
FUNCTION DEFINITION
Format for function definition
return-value-type function-name( parameter-list )
{
declarations and statements
}
Parameter list
Comma separated list of arguments
Data type needed for each argument
If no arguments, use void or leave blank
Return-value-type
Data type of result returned (use void if nothing returned)
17
FUNCTION PROTOTYPING
Function prototype contains
Function name
Parameters (number and data type)
Return type (void if returns nothing)
Only needed if function definition after function call
Prototype must match function definition
Function prototype
double maximum( double, double, double );
Definition
double maximum( double x, double y, double z )
{
…
}
18
FUNCTION PROTOTYPING
Function signature
Part of prototype with name and parameters
double maximum( double, double, double );
Argument Coercion
Force arguments to be of proper type
Converting int (4) to double (4.0)
cout << sqrt(4)
Conversion rules
Arguments usually converted automatically
Changing from double to int can truncate data
3.4 to 3
19
EXAMPLE FUNCTION
#include <iostream>
int square( int );
int main()
{
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " ";
cout << endl;
return 0;
}
1 4 9 16 25 36 49 64 81 100
int square( int y )
{
return y * y;
}
20
21
SCOPE RULE
Block scope
Begins at declaration, ends at right brace {
Can only be referenced in this range
Global Variables
Local
variables, function parameters
static variables still have block scope
Storage class separate from scope
Function-prototype scope
Parameterlist of prototype
Names in prototype optional
Compiler ignores
In a single prototype, name can be used once 22
LOCAL VARIABLES
Variables declared in a function:
Are local to that function, they cannot be used from outside the
function
Have the function as their scope
Variables declared in the main part of a program:
Are local to the main part of the program, they cannot be used from
outside the main part
Have the main part as their scope
23
GLOBAL CONSTANT
Global Named Constant
Available to more than one function as well as the main part of the
program
Declared outside any function body
Declared outside the main function body
Declared before any function that uses it
Example:
const double PI = 3.14159;
double volume(double);
int main()
{….}
24
PI is available to the main function and to function volume
GLOBAL VARIABLES
Global Variable -- rarely used when more than one function
must use a common variable
Declared just like a global constant except const is not used
Generally make programs more difficult to understand and
maintain
25
EXAMPLE FUNCTION
#include <iostream>
double maximum( double, double, double );
int main()
{
double number1, number2,number3;
cout << "Enter three floating-point numbers: ";
cin >> number1 >> number2 >> number3;
cout << "Maximum is: "<< maximum( number1, number2, number3 ) << endl;
return 0;
}
double maximum( double x, double y, double z )
{ Enter three floating-point numbers: 99.32 37.3
double max = x; 27.1928
if ( y > max ) Maximum is: 99.32
max = y;
Enter three floating-point numbers: 1.1 3.333 2.22
if ( z > max ) Maximum is: 3.333
max = z; 26
return max; Enter threefloating-point numbers: 27.9 14.31 88.99
Maximum is: 88.99
}
TEST DRIVERS
27
VOID FUNCTIONS
A function need not return a value
In other programming languages, such a function is called a procedure or a
subroutine
In C++, such a function is identified simply by placing the keyword void
where the function’s return type would be
A type specifies a set of values
For example, the type short specifies the set of integers from –32,768 to
32,767
The void type specifies the empty set
Consequently, no variable can be declared with void type
A void function is simply one that returns no value
28
EXAMPLE
29
Does this function display February
31,1996?
BOOLEAN FUNCTIONS
In some situations, it is helpful to use a function to evaluate a condition, typically within
an if statement or a while statement. Such functions are called boolean functions
30
31
TASK
Write a program that prompts the user for his/her age and
then returns it. It is “robust” in the sense that it rejects
any unreasonable integer input. It repeatedly requests
input until it receives an integer in the range 0 to 120.
The output of the program should be like:
32
SOLUTION
33