1
FUNCTIONS - IChapter 5
Functions help us write more complex programs
Agenda
Introducing Functions
Tell me a story– void FunctionsParameters and Arguments
Random numbers
Do the Math– value returning FunctionsReturn statement
Prototypes and file layout
It’s Logical—bool Functions
2
3
Functions are building blocks…
Each box is a
“mini-program” of 5-20 lines of
code
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)
5
Function calls
Function definition
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
7
Start
Once upon a time,
Once upon a time,
Console Output
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 finishesPart 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 parameters9
Correct Program Layout
10
These are the
“building blocks” of
code
Do not overlap the
blocks
Main( ) is also a
function definition!!
Incorrect Program Layout
11
These
Function
Blocks are
Nested—
Syntax Error!!
Parameters and ArgumentsInformation 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
13
2 is the argument
m is the parameter
No matter what argument is
given, parameter m
get’s a copy of it
This morning,Console Output
Other Argument Possibilities
14
This morning,
Once upon a time,Once upon a time,This morning,
This morning,
Console Output
Each function call demonstrates a different argument passed to
parameter m in opening( )
What is a parameter again?
15
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.
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 simulationsRequires a different kind of function…one that returns a value so we can use it later.
int x; x = rand( );
x now holds a “pseudo” random number between +/-2 billion, for example: 230923, 102912009, 1942390439, -2039329, etc
17
Notice: This function call is in an assignment statement
+/- 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)
19
Plug x in here and now the random number selects the opening
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
22
Part2 Value Returning Functions
Useful in math and other operationsThese 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!!!
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);
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 ;
23
16
Notice, 2 arguments
BUT Don’t cout a void function: cout<<opening( ); ERROR
For the Math Whiz…
24
25
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.
Making your own VRFsWhen 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
27
EXAMPLE—Dollar ValueRemember 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…
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.
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!!!
28
float dollarValue( int n, int d )
dollarValue
Number of nickels and dimes, both integers
The variable dollar gets the result and it’s float
Now we can write the definition
29
Type of return value
Consistent with return-type
value is a “local variable”return-type
30
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
31
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:
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
34
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
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 LogicA 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 exampleSuppose 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
39
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