Structured Programming
Using C++
Lecture 5 : Function Basics
Dr. Amal Khalifa
Lecture Contents:
Predefined Functions
Those that return a value and those that don’t
Programmer-defined Functions
Defining, Declaring, Calling
Recursive Functions
Scope Rules
Local variables
Introduction to Functions
3
Building Blocks of Programs
Other terminology in other languages:
Procedures, subprograms, methods
In C++: functions
I-P-O
Input – Process – Output
Basic subparts to any program
Use functions for these "pieces"
Dr. Amal Khalifa, 2012
Predefined Functions
Libraries full of functions for our use!
Two types:
Those that return a value
Those that do not (void)
Must "#include" appropriate library
e.g.,
Using Predefined Functions
5
•
Math functions very plentiful
–
Found in library <cmath.h>
–
Most return a value (the "answer")
•
Example:
theRoot = sqrt(9.0);
• I = 9.0 argument/parameter (literal/variable,/expression) • P = sqrt() function call
• O = 3 return value
The call itself can be part of an expression:
bonus = sqrt(sales)/10;
A function call is allowed wherever it’s legal to use an expression of the function’s return type
Dr. Amal Khalifa, 2012
Example :
Predefined Functions (2 of 2)
7 Dr. Amal Khalifa, 2012
More Math Functions
(2 of 2)
Dr. Amal Khalifa, 2012 9
Case study: Random Numbers
Used for simulations, games
rand()
Takes no arguments
Returns a "randomly chosen" value between 0 & RAND_MAX
Scaling:
rand() % 6
Random value between 0 & 5 Squeezes the range
Shifting:
rand() % 6 + 1
Shifts range between 1 & 6 (e.g., die roll)
Use srand(seed_value);
Alter sequence of generated numbers Can use system time in Library <time>
Random Examples
Dr. Amal Khalifa, 2012
11
Random double between 0.0 & 1.0:
(RAND_MAX – rand())/static_cast<double>(RAND_MAX)
Type cast used to force double-precision division
Random int between 1 & 6:
rand() % 6 + 1
"%" is modulus operator (remainder)
Random int between 10 & 20:
rand() % 10 + 10
Predefined void Functions
No returned value
Performs an action, but sends no "answer"
When called, it’s a statement itself
exit(1); // No return value, so not assigned
This call terminates program
void functions can still have arguments
All aspects same as functions that "return a value"
User defined Functions
A detailed look..
Programmer-Defined Functions
Write your own functions!
Building blocks of programs
Divide & Conquer
Readability
Re-use
Your "definition" can go in either:
Same file as main()
Components of Function Use
15
3 Pieces to using functions:
Function Declaration/prototype
Information for compiler to properly interpret calls
Function Definition
Actual implementation/code for what function does
Function Call
Transfer control to function
Dr. Amal Khalifa, 2012
Function Declaration
•
Also called function prototoype
•
Tells compiler how to interpret calls
Return type Function name Parameter list
–
Syntax:
<return_type> FnName(<formal-parameter-list>);
•
Placed before any calls
Function Definition
17
Implementation of function
Placed after function main()
Functions are "equals"; no function is ever "part" of
another
Formal parameters in definition
return statement:
Transfers control back to "calling" function
Typically the LAST statement in function definition
Dr. Amal Khalifa, 2012
Function Call
Just like calling predefined function
<variable> = FnName(<actual-parameter-list>);
Return value??
Arguments??
often called "actual arguments"
Example : the Cost Function
Dr. Amal Khalifa, 2012 19
Write a function that computes the total cost of a
number of items including sales tax. Test the function in
a program.
Hint: assume that the sales tax rate is 5%.
21
Ex
ampl
e
:
t
he
C
ost
Fu
nct
io
n
Alternative Function Declaration
Recall: Function declaration is "information"
for compiler
Compiler only needs to know:
Return type Function name Parameter list
Formal parameter names not needed:
double totalCost(int, double);
Still "should" put in formal parameter names
Example
Dr. Amal Khalifa, 2012 23
Write a function
integerPower(base, exponent)
that
returns the value of:
base
powerFunctions Calling Functions
We’re already doing this!
main() is a function!
One and only one main() exists in a program
Should return "int" or "void" Who is the caller??
Example
Dr. Amal Khalifa, 2012 25
Write a function that rounds a number to the nearest integer
number.
Hint: Use floor(num+0.5)
Boolean Return-Type Functions
Return-type can be any valid type
bool appropriate(int rate); //declaration
bool appropriate (int rate) //definition
{
return (((rate>=10)&&(rate<20))||(rate==0); }
if (appropriate(entered_rate)) //call cout << "Rate is valid\n";
More Examples
Dr. Amal Khalifa, 2012 27
Write a function
isOdd(number)
to determine if a given
number is odd or not.
Write a function
isMultiple ,
for a pair of integers , that
determines whether the second integer is a multiple of the first.
Hint: use the remainder operator (%)
Declaring “void” Functions
Similar to functions returning a value
Return type specified as "void"
Example:
//declaration..
void showResults(double fDegrees, double cDegrees);
//definition...
void showResults(double fDegrees, double cDegrees) {
cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(1);
cout << fDegrees
<< " degrees fahrenheit equals \n" << cDegrees << " degrees celsius.\n";
Example:
use of return in void functions
Dr. Amal Khalifa, 2012 29
Write a function that outputs
the instructions for dividing a
given amount of ice-cream
among people at a table.
Be careful with the case where
there are no people at the table
(division by zero)
Example:
Dr. Amal Khalifa, 2012 31
That’s all for today !!