Title: FUNCTIONS I Chapter 5
1FUNCTIONS - IChapter 5
- Functions help us write more complex programs
2SCENARIO 1
- You need to display some lengthy instructions at
several places in your program. The instructions
are identical each time. So you make a function
to handle the display of instructions and use a
simple function call, display_insructions( )
whenever you need to show instructions.
3SCENARIO 2
- You have a complicated formula that you need to
put in several places in your program but its
too messy to copy and paste it everywhere you
need it.
- A function is a way of packaging the formula so
you can just say - cents value(nickels, dimes)V
sphere_volume(R) - cents value(3, 8)V sphere_volume(4.6)
cents 5 nickels 10 dimes
4SCENARIO 2 Continued
- Perhaps a better exampleyou are doing your
taxes. When you get to calculating your tax (by
paper!) you are sent to a table, where you look
up the tax for your income and bring it back into
the line on your main worksheet. - This aspect of jumping to another part of the
program to perform a side calculation is what
functions are all about.
5SCENARIO 3
- You are developing a program to run a banks ATM
machine. Its so complicated you decide to break
the problem up into smaller units. Each unit will
handle a specific task, such as a) let a customer
log in, b) find the balance of a customers
account, 3) deposit money, 4) withdraw money, 5)
view the last 5 transactions. - Each unit is a function, a small "program" that
accomplishes one task that can tested and
verified, and then assembled into a larger
programming structure, the main simulation
program.
6(No Transcript)
7What are functions ?
- Large programs can be modularized into sub
programs which are smaller, accomplish a specific
task and hence are more manageable - These sub programs are called functions
- They can be compiled and tested separately and
reused in different programs
8Things to do today Function Basics
- SCENARIO 1 Simplest
- Void Functions ?
- Void Functions with parameters
- Local variables
- Function Prototypes
- SCENARIO 2 A little more complex
- Functions that return a value
- Standard C library functions
- Test Drivers
- SCENARIO 3is project 2 after midterm
9Remember Lab 1?
- include ltiostreamgt
- using namespace std
- int main()
-
- // This is my first program
- cout ltlt Hello World" ltlt endl
- system("pause")
- return 0
10This does the same thing, using a function
- include ltiostreamgt
- using namespace std
- void message( )
-
- coutltlt"Hello World"ltltendl
-
- int main()
-
- // This is my first function program
- message( )
- system("pause")
- return 0
Function Definition
Function Call
11A little terminology
- A function definition has two parts
- the head and the body
-
- void message( )
-
- coutltlt"Hello World"ltltendl
Function name
Function Head
Function Body
12User-defined functions.. Contd..
- The syntax for the head of a function is
- return-type name(parameter-list)
- In the given example the head of the function is
- void msg()
- return-type name(parameter-list)
- (void means nothing no return value)
- Another example
- double dollar_value (int d, int q)
- // return value of dimes and quarters
13The function body
- The body of a function is the block of code that
follows its head - It is written between the braces following
the function header - It contains the code that performs the functions
action - Note that main() is a function whose body is the
program itself
14Sprechen Sie Deutsches ? Handling multiple
languages
- void message( int choice )
- if (choice 1)
- coutltlt"Hello World"ltltendl
- else coutltlt"hallo Welt"ltltendl
-
- int main()
-
- // This is my first function program
- message(2)
- system("pause")
- return 0
-
15Making your own function, PART 1
- The packaging for a user-defined function is kind
of complicated (you will get used to it) - For the formula
- You would say
- float value(int nickels, int dimes)
-
- float cents 5nickels 10dimes
- return cents
-
cents 5 nickels 10 dimes
This is a function DEFINITION
16Part 2 Where does the function go?
- OPT 1 definition goes before main( )float
value(int nk, int dms) -
- float val 5nk 10dms
- return val
-
- int main( )
- int nickels, dimes, cents
- cout ltlt "Enter num nickels and dimes "
- cin gtgt nickels gtgt dimes cents value (
nickels, dimes) coutltlt"the value is
"ltltcentsltltendl
Function Definition
Function Call
17Part 2 Where does the function go?
- OPT 2 definition goes after main( ),
withfloat value(int nk, int dms)int main( ) - int nickels, dimes, cents
- cout ltlt "Enter num nickels and dimes "
- cin gtgt nickels gtgt dimes cents value (
nickels, dimes) coutltlt"the value is
"ltltcentsltltendlfloat value(int nk, int dms) -
- float val 5nk 10dms
- return val
-
Function Prototype(signature)
Function Call
Function Definition
18Standard C Library
- The Standard C library is a collection of
pre-defined functions which are accessed through
header files - Notice about these pre-defined functions that the
processing step is hidden we do not need to
know what the function does to produce the output
19Example The sqrt() function
- This function returns the square root of a given
positive number - // sqroot.cpp
- include ltiostreamgt
- include ltcmathgt
- using namespace std
- int main()
-
- int x
- x 2
- cout ltlt sqrt(9) ltlt endl
- cout ltlt sqrt (10x 5) ltlt endl
- cout ltlt sqrt(x) ltlt endl
- return 0
-
New library
3 5 1.41421
Calls sqrt()
Method 1, function call in a cout statement
20Invoking a function, method 2
- A function can be invoked or called in a cout
statement as shown in the previous example or by
assigning its value to a variable - Example
- float x25, y
- ysqrt(x)
- coutltlt x ltlt "ltlt y ltlt endl
-
25 5
Method 2, function call in an assignment statement
21Passing by value Whats that ?
- Consider the function sqrt(x)
- The expression x is called the argument or actual
parameter of the function call and we say that it
is passed by value to the function - So when x is 3, the actual value 3 is passed to
the sqrt() function by the call sqrt(x)
22This can be illustrated as
main()
sqrt()
3
float x
3
1.73205
float y
1.73205
Shaded box, Processing hidden
23Check this out!!
- Nesting of function calls
- int main()
-
- float y
- y sqrt(1 2sqrt(3 4sqrt(5)))
- coutltlt yltlt endl
-
24abs(k) works with integers
25(No Transcript)
26Things to do today
- Functions Basics including
- Standard C library functions
- User - defined functions
- Test Drivers
- Function Declarations and Definitions
- Local variables and Functions
- void Functions
27User-defined functions
- A user defined function has two parts
- the head and the body
- Here is a simple example of a user defined
- function
- float cube(float x)
-
- return xxx //returns cube of x
28User-defined functions.. Contd..
- The syntax for the head of a function is
- return-type name(parameter-list)
- In the given example the head of the function is
- float cube(float x)
- return-type name(parameter-list)
- Another example
- double dollar_value (int d, int q)
- // return value of dimes and quarters
29The function body
- The body of a function is the block of code that
follows its head - It is written between the braces following
the function header - It contains the code that performs the functions
action - Note that main() is a function whose body is the
program itself
30In the example
- The function body is
-
- return xxx //returns cube of x
-
- This includes the return statement that specifies
the value that the function sends back to the
place where it was called
31return
- It terminates the execution of the function
- The functions 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
32Things to do today
- Functions Basics including
- Standard C library functions
- User - defined functions
- Test Drivers
- Function Declarations and Definitions
- Local variables and Functions
- void Functions
33Does my function work right ?
- That is the purpose of the test driver
- It is an ad-hoc program(minus all the usual
niceties such as user prompts, output labels and
documentation) written to test a function that we
have created - Remember the cube() function ? Lets write a test
driver for that
34- float cube(float x)
- // returns cube of x
- return xxx
-
- int main()
- // test driver for cube() function
- coutltlt"cube(1) "ltltcube(1)ltltendl
- coutltlt"cube(-5) "ltltcube(-5)ltltendl
- coutltlt"cube(4) "ltltcube(4)ltltendl
-
1 -125 64
35Things to do today
- Functions Basics including
- Standard C library functions
- User - defined functions
- Test Drivers
- Function Declarations and Definitions
- Local variables and Functions
- void Functions
36Two ways for defining functions
- The complete definition of the function is listed
above the main program like - float cube(float x)
- // returns cube of x
- return xxx
-
- int main()
-
- float n5
- coutltlt cube(n) ltlt endl
-
37Another way is
- List only the functions header above the main
program (declaration) like - float cube(float) (or)
- float cube(float x)
- List the functions head and body below the main
program (definition) - declaration is also called a function prototype
- A function declaration is like a variable
declaration
38The previous program can also be written as
- float cube(float x) //declaration
- int main()
-
- float n5
- coutltlt cube(n) ltlt endl
-
- float cube(float x) //definition
- // returns cube of x
- return xxx
-
39Actual Vs. Formal Parameters
- Actual parameters (We use ARGUMENTS)
- Parameters of the function in the function
call - Passed by value
- Formal parameters
- Variables listed in the functions
parameter-list in the function definition - Local to that function
- The Arguments are copied to the Formal Parameters
during function call
40Actual Vs. Formal Parameters
- float cube(float) // function declaration
- int main()
-
- float n1
- while (n gt 0)
- cingtgt n
- coutltlt"cube("ltlt n ltlt") "ltlt cube(n) ltltendl
-
-
- // function definition
- float cube(float x)
- // returns cube of x
- return xxx
-
Actual Parameter n
Formal parameter x
The value of n is copied into x for each function
call
41Things to do today
- Functions Basics including
- Standard C library functions
- User - defined functions
- Test Drivers
- Function Declarations and Definitions
- Local variables and Functions
- void Functions
42Local variables and functions
- A local variable is declared inside a block and
is accessible only from within that block - Similarly a variable declared within a function
is local to that function.. i.e it exists only
when the function is executing - A functions formal parameters (used at that
point where the function is actually defined) are
also regarded as being local to the function
43The variable larger is local to maxonly can
be used inside max
- int max (int a, int b)
-
- int larger
- if (a gt b)
- larger a
- else
- larger b
- return larger
-
- int main()//tests the max() function
- coutltltmax(5, 8) ltltmax(5,8)ltltendl
- coutltltmax(7, 3) ltltmax(7,3)ltltendl
- coutltltmax(7, 7) ltltmax(7,7)ltltendl
-
Parameters a b are like local variables
tooonly work inside max
44In the last example
- The function has three local variables
- a,b and larger
- The parameters a b are local because it is
declared in the functions formal parameter list - The parameter larger is local because it is
declared within the body of the function
45The max function could also be written without a
local variable
- int max(int a, int b)
-
- int larger
- if (a gt b)
- larger a
- else
- larger b
- return larger
int max(int a, int b) if (a gt b)
return a else return b
Hint for Prob 7 min function
Both work the same way
46Whats wrong with this ?
- float cube(float x)
- // returns cube of x
- return xxx
-
- int main()
- // test driver for cube() function
- x cube(1)
- coutltlt"cube(1) "ltlt x ltltendl
- coutltlt"cube(-5) "ltltcube(-5)ltltendl
- coutltlt"cube(4) "ltltcube(4)ltltendl
47This would work !
- float cube(float x)
- // returns cube of x
- return xxx
-
- int main()
- // test driver for cube() function
- float x cube(1)
- coutltlt"cube(1) "ltlt x ltltendl
- coutltlt"cube(-5) "ltltcube(-5)ltltendl
- coutltlt"cube(4) "ltltcube(4)ltltendl
-
But for now, try not to reuse variable names in
functions
48Data Types Must Match!
int main() // test driver for grade() float
x grade(95) coutltltgrade(95) "ltlt x
- char grade (double avg)
-
- if (avg gt 92)
- return 'H'
- else if (avg gt 65)
- return 'P'
- else
- return 'F'
Whats wrong here?
49Data Types Must Match!
int main() // test driver for grade() char
G grade(95) coutltltgrade(95) "ltlt G
- char grade (double avg)
-
- if (avg gt 92)
- return 'H'
- else if (avg gt 65)
- return 'P'
- else
- return 'F'
Hint for Problem 7 grade fn
50Things to do today
- Functions Basics including
- Standard C library functions
- User - defined functions
- Test Drivers
- Function Declarations and Definitions
- Local variables and Functions
- void Functions
51void Functions
- If a function does not return any value its
return-type is void - The void type specifies the empty set
- Think of an example for this type of function
that does not return anything
52This function does not return anything
- void printhello(float x)
-
- for (int i0 iltx i)
-
- coutltlt "Hi There !!!!" ltlt endl
-
-
- int main()
-
- printhello(2)
Also Notice a void function call is just on a
line by itself Dont use in cout or assignment
statements (like float functions)
No return statement
53And now for.
- Global Variables--
- A variable declared above/outside all functions
- Can be accessed by everyone
- Generally not a good idea for beginners
- Global Constants
- A variable declared above/outside all functions
- Can be accessed by everyone
- Works great for things like PI that you use
often
54Summarizing what we did today..
- Standard C library functions
- User - defined functions
- Test Drivers
- Function Declarations and Definitions
- Local variables and Functions
- void functions