Lec5.ppt

advertisement
FUNCTIONS - I
Chapter 5
Functions help us write more
complex programs
1
Agenda
Introducing Functions
Tell me a story– void Functions
Parameters and Arguments
Random numbers
Do the Math– value returning Functions
Return statement
Prototypes and file layout
It’s Logical—bool Functions
2
Functions are building blocks…
Each box is a
“mini-program”
of 5-20 lines of
code
3
We use functions…
When a task (sequence of code) gets routine
and needs to be repeated several times in a
program.
When we want to hide details of a
complicated calculation from the main flow
of the program
As a tool to break down complicated
problems into easily solvable pieces
4
A Simple Function
(to begin a story)
Function definition
Function calls
5
A function call is a “controlled jump”
Program execution always begins in main( )
A function call tells computer to jump into
another part of the file (where the definition
is)
When finished, the computer returns to the
line following the function call and
continues on thru the program
6
Controlled Jump
Illustration
Console Output
Once upon a time,
Once upon a time,
Start
7
Function Syntax Rules
The function call has the same name as the
function definition
The function definition must appear before
the function call in it’s own separate block
of code
Curly braces mark the beginning and end of
a function definition
A function definition cannot be put inside
another function definition
8
What the heck is “void”?
The first line of a function definition is called the function
head or header:
void opening( )
The syntax for the function header is:
return-type function-name ( parameters )
The word void indicates the function does not
return any data when it finishes
Part 2 deals with non-void or value-returning functions
Notice int main( )? This allows main( ) to return a 0
when it completes successfully.
Also, right now, we are not using any parameters
9
Correct Program Layout
These are
the
“building
blocks” of
code
Main( ) is
also a
function
definition!!
Do not
overlap the
blocks
10
Incorrect Program Layout
These
Function
Blocks are
Nested—
Syntax Error!!
11
Parameters and Arguments
Information can be given to a function during the
function call
This allows a variety of function behaviors
Makes functions more useful
Information is passed
from an argument in the function call
to a parameter in the definition
We’ll modify our program to show this:
• opening( )  opening(2); // where 2 is an argument
• We’ll also have to modify the function definition 
12
Passing information into a function
m is the parameter
No matter what
argument is
given,
parameter m
get’s a copy of it
2 is the argument
Console Output
This morning,
13
Other Argument Possibilities
Console Output
This morning,
Once upon a time,
Once upon a time,
This morning,
This morning,
Each function call demonstrates
a different argument passed to
parameter m in opening( )
14
What is a parameter again?
The parameter m receives
whatever argument is given in
the function call.
When the argument is a variable,
the value of the variable is given
to m
Here m in main( ) is different
from m in opening( ). Since they
live in different functions, they are
like separate variables.
15
The story continues…
In the lab, you will
get to write your
own functions to
tell a story
And you’ll be able
to select a variety
of components
using a random
number generator
16
Random Numbers!!
Sometimes we need the computer to pick a
number “at random”
Very common in video games and computer
simulations
Requires a different kind of function…one that
returns a value so we can use it later.
int x;
x = rand( );
Notice: This function call is in an
assignment statement
x now holds a “pseudo” random number
between +/-2 billion, for example: 230923,
102912009, 1942390439, -2039329, etc
17
+/- 2 billion?
The output of rand( ) is not very useful
Too broad a range
To make useable, we use modulus (%) to chop it
down:
Example:
• 25678%10 = ?
• 23042309%10 = ?
• -32098098%10 = ?
Using %10 gives us a random value between 0 and 9
18
To Randomize…
Problem:
rand( ) by itself always gives the same random number.
Solution:
Start your program with a call to srand(time(NULL));
This starts the math formula in rand( ) off with a unique #,
• The number of seconds past Jan 1, 1950 (or so)
Plug x in here and now the random
number selects the opening
19
Start your creative juices…
Finish Lab4Function1.cpp
Next: Part 2, Value Returning functions
20
Before starting Part 2…
a) Function Call _______
b) Function Definition_______
c) Parameter_______
d) Argument_______
e) Local Variable_______
f) Return Type_______
21
Part2 Value Returning Functions
Useful in math and other operations
These functions compute a result and return it
For standard math, #include<cmath>
We know that 24= 2*2*2*2 = 16
In C++ we could say pow(2.0, 4);
But nothing will be displayed!!!
22
Show your Result
Unlike for void functions, when a math
function returns, the original function call is
replaced with the result.
pow(2.0, 4);
16
To show the result you must either cout or
store it in a variable:
A) cout<<pow(2.0, 4) ;
B) z = pow(2.0, 4);
cout<<z ;
Notice, 2 arguments
23
BUT Don’t cout a void function: cout<<opening( ); ERROR
For the Math Whiz…
24
Standard C++ Library
The Standard C++ library is a collection
of pre-defined functions which are
accessed through header files (such as
<cmath>, <iostream> etc..)
Notice that these pre-defined functions
don’t show the processing step (function
definition): we do not need to know how
the function works, just what it does.
25
Making your own VRFs
When the Standard Library doesn’t have what
you need, you can make your own. A value
returning function is very similar to a void
function with only two small changes:
1. Instead of void before the function name, we put
the data type of the return value.
2. At the end of the function definition, we put a
return statement to return the result.
26
EXAMPLE—Dollar Value
Remember Lab 2?
We can use a function call to calculate dollars:
dollars = dollarValue( nickels, dimes);
We are now going to write the definition of the
function. But first…
27
Use the
Function Definition Checklist
When you are given an example function call,
there are a few steps to follow before writing the
function definition to make sure your code works.
dollarValue
1. What is the name of the function? ________
2. What are the parameters it needs (and their type)?
Number of nickels and dimes, both integers
__________________________
3. What is the return-type of the function (the type of the result it
The variable dollar gets the result and it’s float
computes)?___________________
4. Write the function header __________________
float dollarValue( int n, int d )
All of the answers can be determined from the previous slide!!!
28
Now we can write the definition
return-type
value is a “local variable”
Type of return value
Consistent with return-type
29
return…
It terminates the execution of the function
The function’s return-type specifies the
data type of the values that it would return to
the calling program
Its syntax is :
return expression ;
where the data-type of the expression
value = function's return-type
30
Let’s try another!
Define a function named calcSize; the function is
passed a character argument representing a size
code and the function returns the size in inches
(an integer) according to the following chart and
sample function calls:
31
Function Definition Checklist
1. What is the name of the function? ________
2. What are the parameters it needs (and their type)?
__________________________
3. What is the return-type of the function (the type of the result it
computes)?___________________
4. Write the function header __________________
All of the answers can be determined from the previous slide!!!
32
Now Write the Function Definition
33
And another!
Write a function that takes arguments for a user’s
height and weight, and then computes their hat
size according the the following formula:
Hat size = 2.9 times the weight in pounds divided by
height in inches
Here is an example function call:
hsize = hat(weight, height);
Here is some example test data:
weight=150, height=70  hsize=6.2
34
Function Definition Checklist
1. What is the name of the function? ________
2. What are the parameters it needs (and their type)?
__________________________
3. What is the return-type of the function (the type of the result it
computes)?___________________
4. Write the function header __________________
All of the answers can be determined from the previous slide!!!
35
Now Write the Function Definition
36
Bool Functions for Logic
A bool function is a special type of VRF
bool data type has only two values: true, false
This means a function that returns a bool value
can be used in an if-statement 
37
A bool function example
Suppose you want to check if n is between 0
and 100. You could say
Or you could put the condition in a bool
function:
And use that function instead of the boolean
logic
38
Time to explore on your own…
Finish Lab4Function2.cpp
Practice will help you master this topic
Recommend you solve one more
function from the Assignment 4 handout
39
Download