Ch 5 User Defined Functions - PowerPoint PPT Presentation

1 / 41
About This Presentation
Title:

Ch 5 User Defined Functions

Description:

5.3 Functions with Output and Input/Output Parameters. 5.4 Overloaded Functions. 9/30/09 ... cout 'The number rounded up is ' ceil(number) endl; ... – PowerPoint PPT presentation

Number of Views:49
Avg rating:3.0/5.0
Slides: 42
Provided by: socratist
Category:
Tags: ceil | defined | functions | user

less

Transcript and Presenter's Notes

Title: Ch 5 User Defined Functions


1
Ch 5 User Defined Functions
  • 5.1 Single-Result Functions
  • 5.2 void Functions
  • 5.3 Functions with Output and Input/Output
    Parameters
  • 5.4 Overloaded Functions

2
5.1 Single-Result FunctionsBuilt-In Functions
  • Built-in functions provided by C in libraries.
  • Used to perform some task/calculation and return
    a value to the calling function.
  • Can take one or more parameters.
  • Using a predefined function
  • Include the appropriate library.
  • Call/invoke the function

The c in cmath stands for C standard library,
rather than C standard library. Most references
in the online help are to header files, i.e.
ltmath.hgt, so to use the corresponding library,
simply drop the .h. If the library conforms to
the C standard, place a c in front of it. Since
it is hard to remember all libraries conforming
to the C standard, simply drop the .h, compile
and if you get an error, then add the c.
function library
include ltcmathgt using namespace std ... double
root sqrt(16.0)
function call
3
5.1 Single-Result FunctionsBuilt-In Functions
Continued
  • What can I do with the return value?
  • Assign it to a variable.
  • Use it in an expression.
  • Use it as an argument to a function call.

root sqrt(val)
cout ltlt "the root is " ltlt sqrt(val)
root sqrt( sqrt(val) )
4
5.1 Single-Result FunctionsExample
include ltiostreamgt include ltcmathgt using
namespace std int main() double root
double number cout ltlt "Please enter a
number, and I will find " ltlt "its square
root " cin gtgt number root
sqrt(number)
5
5.1 Single-Result FunctionsExample Continued
cout.setf(iosfixed) cout.precision(1)
cout ltlt "The square root of " ltlt number ltlt " is
" ltlt root ltlt endl ltlt endl
cout ltlt "Please enter another number " cin
gtgt number cout ltlt "The number rounded up is
" ltlt ceil(number) ltlt endl cout ltlt
"The number rounded down is " ltlt floor(number)
ltlt endl ltlt endl return (0)
6
5.1 Single-Result FunctionsExample Continued
7
5.1 Single-Result Functions Three Requirements
  • C allows a programmer to define their own
    functions.
  • Defining a function requires three things
  • a prototype (aka as function declaration) before
    main()
  • a function call (function invocation)
  • a function definition (how the function does it)
    after main()

int add2(int n1, int n2)
cout ltlt add2(num1, num2)
int add2(int n1, int n2) return (n1
n2)
8
5.1 Single-Result Functions Three Requirements
Continued
  • Prototype
  • Basically the function declaration.
  • Specifies the function name, along with the
    number and type of arguments if present.
  • Function call
  • Invokes the function.
  • Function definition
  • Describes how the function carries out its task.
    Includes the header and body.

9
5.1 Single-Result Functions Example
include ltiostreamgt using namespace std int
add2(int n1, int n2) int main() int num1
5 int num2 6 cout ltlt num1 ltlt " " ltlt
num2 ltlt " " ltlt add2(num1, num2)
ltlt endl return (0) int add2(int n1, int
n2) return (n1 n2)
function prototype
function call
10
5.1 Single-Result Functions Design Hints
  • Things to remember when designing functions.
  • What does the function calculate? This
    determines whether you are to return a single
    value or use the parameter list to pass back
    multiple calculated values. This step basically
    defines the reason for the function's existence.
  • What information does the function need to carry
    out its task? The function may require input
    values that must be supplied through the
    parameter list. The parameter list is how your
    functions communicate. (Their information highway
    so to speak)
  • Should I design the function specifically for the
    problem at hand?Design the function to be as
    general as possible. Remember, the idea is to
    write once and use many times.

11
5.1 Single-Result Functions Pre,Post Conditions
  • Precondition
  • What is assumed to be true before the function is
    called.
  • Postcondition
  • What is asserted to be true after the function is
    called.
  • Use each postcondition as a way to enhance the
    function contract.
  • Announce what is assumed and what is to be
    expected. It is a form of a user's guide if you
    will. Follow the rules, and you shall succeed,
    disregard them and you shall fail.

12
5.1 Single-Result Functions Pre,Post Conditions
void read(int num1, int num2) //
precondition the value of both num1 and num2 is
undefined. // postcondition num1 and num2
contain two integer values
double updateSum(double sum, double num) //
precondition sum and num contain valid values.
// postcondition the total of sum and num is
returned.
double calcAve(double sum, int numCount) //
precondition sum and numCount contain valid
values. // postcondition the quotient of sum
over numCount is // returned.
13
5.2 void Functions
  • Some functions are meant to perform a task and
    return some result to the calling function, while
    others simply perform a task.
  • Functions that do not return a value are called
    subroutines in other programming languages.
  • Functions that do not return a value should be
    declared as void.
  • Good candidates are display functions.

void display(void)
void display(void) cout ltlt "Hello, I do
not do anything."
14
5.2 void Functions What not How
  • Do you need to know how a car engine operates in
    order to drive?
  • Of course not, otherwise we would all be walking
    instead.
  • One need NOT know how a program works in order to
    use it.
  • One however should know what a program does in
    order to use it properly.
  • A function can also be treated this way, like a
    black box.
  • know what the function does, but not necessarily
    how it does it.
  • this black box analogy is referred to as
    information hiding

15
5.2 void Functions What not How Continued
  • Suppose we need to display a given character to
    the screen 15 times, and the following functions
    are available
  • Now, which of the two functions does what we
    need?
  • If you answered the first one, then you are
    right. You do not need to know how the character
    is displayed, but rather that the function
    actually displays your character the number of
    times you want it to.
  • That is procedural abstraction in all its glory.

void displayChar(char c, int times) // displays
the character c, a specified number of
times void displayChar(char c) // displays the
character c, 10 times
16
5.2 void Functions Examples
  • Try these out
  • Ex 1. Write a non-void function that determines
    if its only integer parameter is odd. If it is it
    returns true, else false.
  • Ex 2. Write a non_void function that returns the
    minimum value among its three integer parameters.
  • Ex 3. Write a void function that displays a
    message to the screen based on the value in its
    only parameter.

17
5.3 Functions with Output and Input/Output
ParametersBasics
  • Argument v. Parameter
  • Argument
  • the expression, constant or variable supplied in
    a function call
  • Parameter
  • the variable in the function definition that
    receives the argument's value

cout ltlt add2(n1, n2) // function call
int add2(int n1, int n2) return (n1
n2)
18
5.3 Functions with Output and Input/Output
ParametersPass by Value
  • The argument (variable) is unaffected by changes
    made to the parameter
  • The argument's value is copied into the parameter
  • If the function has more than one argument, each
    value is copied to its respective parameter,
    based on its position in the parameter list
  • When passing by value you are protecting the
    value of the argument itself from changes that
    could occur to the parameter within the function

19
5.3 Functions with Output and Input/Output
ParametersExample
include ltiostreamgt using namespace std void
byValue(int num) int main() int n 10
cout ltlt n ltlt endl byValue(n) cout ltlt n ltlt
endl return (0) void byValue(int num)
num 100 cout ltlt num ltlt endl
20
5.3 Functions with Output and Input/Output
ParametersPass by Value Continued
  • How does it actually work?
  • int main(void)
  • int n 10
  • cout ltlt n ltlt endl
  • byValue(n)
  • cout ltlt n ltlt endl
  • return (0)
  • void byValue(int num)
  • num 100
  • cout ltlt num ltlt endl

Memory
main n10
Memory
main n10
byValue num10
Memory
main n10
byValue num100
Memory
main n10
Memory
21
5.3 Functions with Output and Input/Output
ParametersPass by Reference
  • The argument (variable) is changed if the
    parameter is changed
  • The address of the argument is copied into the
    parameter
  • If the function has more than one argument, each
    argument's address is copied to its respective
    parameter, based on its position within the
    parameter list
  • To indicate pass by reference, add an after the
    data type in the prototype and function header.

void changeMe(int num)
22
5.3 Functions with Output and Input/Output
ParametersExample
include ltiostreamgt using namespace std void
byRef(int num) int main() int n 10
cout ltlt n ltlt endl byRef(n) cout ltlt n ltlt
endl return (0) void byRef(int num)
num 100 cout ltlt num ltlt endl
23
5.3 Functions with Output and Input/Output
ParametersPass by Reference Continued
  • How does it actually work?
  • int main(void)
  • int n 10
  • cout ltlt n ltlt endl
  • byRef(n)
  • cout ltlt n ltlt endl
  • return (0)
  • void byRef(int num)
  • num 100
  • cout ltlt num ltlt endl

Memory
main n10
Memory
main n10
byValue numn
Memory
main n100
byValue numn
Memory
main n100
Memory
24
5.3 Functions with Output and Input/Output
ParametersPass by Reference Continued
  • Passing by reference allows a function to pass
    back more than one value to the calling function.
  • Good candidates
  • input functions
  • functions that calculate more than one result

void stats(int n1, int n2, int sum, double
ave)
25
5.3 Functions with Output and Input/Output
ParametersExample
include ltiostreamgt using namespace std void
read(int num1, int num2) int main(void)
int num1, num2 read(num1, num2) cout ltlt
"Your input was " ltlt num1 ltlt " and " ltlt
num2 ltlt endl ltlt endl return (0) void
read(int num1, int num2) cout ltlt "Enter
two numbers " cin gtgt num1 gtgt num2
26
5.3 Functions with Output and Input/Output
ParametersExample
int readList(double sum, double ave) int
numCount 0 double num sum 0
cout ltlt "Enter number, or -1 to quit " cin
gtgt num while (num ! -1)
numCount sum num cout ltlt
"Enter number, or -1 to quit " cin gtgt
num ave sum / double(numCount)
return (numCount)
27
5.3 Functions with Output and Input/Output
ParametersContinued
  • A function may call another function.
  • A function definition may not be placed within
    another function definition. Nesting of function
    definitions in other words in a NO NO.
  • Note do not call main() from any function you
    define (weird things may happen).
  • Let's revisit our readList function. In version 1
    of that function we asked the function to do
    quite a lot. Read, sum, and calculate the
    average. This time we shall delegate, yes
    delegate, as we should.

28
5.3 Functions with Output and Input/Output
ParametersExample Continued
  • int readList(double sum, double ave)
  • int numCount 0
  • double num
  • sum 0
  • cout ltlt "Enter number, or -1 to quit "
  • cin gtgt num while (num ! -1)
  • numCount
  • sum updateSum(sum, num)
  • cout ltlt "Enter number, or -1 to quit "
  • cin gtgt num
  • ave calcAve(sum, numCount)
  • return (numCount)

29
5.3 Functions with Output and Input/Output
ParametersExample Continued
double updateSum(double sum, double num)
return (sum num) double
calcAve(double sum, int numCount) return (
(numCount)? sum/double(numCount) 0 )
30
5.3 Functions with Output and Input/Output
ParametersInput, Output, Input/Output Parameters
  • Input Parameter
  • the parameter's value is supplied by the argument
  • the function simply refers (uses) the parameter,
    i.e. cout ltlt par
  • Output Parameter
  • the parameter's value is provided from within the
    function
  • the function assigns a value to the parameter,
    i.e. par value
  • Input/Output Parameter
  • the parameter's initial value is supplied by the
    argument and changed by the function
  • the function refers and also updates the
    parameter, i.e. par par val

31
5.3 Functions with Output and Input/Output
ParametersExamples
  • Try these out
  • Ex 1. Write a function that doubles each of its
    three integer arguments
  • Ex 2. Write a function that reads in a list of
    characters from the keyboard and counts the
    number of vowels and consonants entered. Both
    counts are output parameters.

32
5.4 Overloaded Functions
  • Function names may be overloaded (reused).
  • Declare the same name function more than once.
  • Each declaration must be unique. Must have
    different type arguments and/or different number
    of arguments.
  • Only need to remember one function name instead
    of multiple names. (That is a good thing)

int multBy2(int arg) long multBy2(long
arg) float multBy2(float arg)
33
5.4 Overloaded FunctionsExample
include ltiostreamgt using namespace std void
display(char c, int times) void display(int i,
int times) void display(void) void main(void)
display('', 25) cout ltlt endl
display(1, 10) cout ltlt endl display()
cout ltlt endl ltlt endl
34
5.4 Overloaded FunctionsExample Continued
void display(char c, int times) for (int cnt
1 cnt lt times cnt) cout ltlt c
void display(int i, int times) for (int
cnt 1 cnt lt times cnt) cout ltlt
i void display(void) for (int cnt
1 cnt lt 20 cnt) cout ltlt '-'
35
5.5 Introduction to Scope of NamesVariable Scope
  • Scope or visibility
  • Variable scope or visibility, determines the
    section of code in which a variable is directly
    accessible.
  • Local scope
  • Saying a variable has local scope, means it is
    only locally accessible. In other words, the
    variable is a local variable.
  • Local variable
  • Accessible only from within the block its defined
    in. A block is any code surrounded by a pair of
    braces ().

36
5.5 Introduction to Scope of NamesVariable Scope
  • Functions communicate through the use of
    parameters.
  • Argument
  • The variable or value supplied in the function
    call.
  • Parameter
  • The variable declared in the function's header.
  • The parameters are actually local variables to
    the function definition.

37
5.5 Introduction to Scope of NamesVariable Scope
Continued
  • In which block(s) is the variable age accessible?
  • You did say, only A, right?

// Block A int age ...
// Block B ...
// Block C ...
38
5.5 Introduction to Scope of NamesExample
include ltiostreamgt using namespace std int
multBy2(int arg) void main(void) int arg
5 cout ltlt "the number doubled is "
ltlt multBy2(arg) ltlt endl ltlt endl int
multBy2(int arg) return (arg 2)
arg local to main()
arg local to multBy2()
39
5.5 Introduction to Scope of NamesExample
include ltiostreamgt using namespace std double
tax(double taxableAmount, double
taxRatePercent) void main(void) double
taxableAmount double taxRatePercent cout
ltlt "Enter total cost " cin gtgt
taxableAmount cout ltlt "Enter tax rate
percent xx.xx " cin gtgt taxRatePercent
40
5.5 Introduction to Scope of NamesExample
Continued
cout.setf(iosfixed) cout.precision(2)
cout ltlt "Your tax liability on that amount is
" ltlt tax(taxableAmount,
taxRatePercent) ltlt endl ltlt
endl double tax(double taxableAmount, double
taxRatePercent) return (taxableAmount
taxRatePercent / 100.0)
41
5.5 Introduction to Scope of NamesGlobals
  • Global variable
  • defined outside any function. Accessed by all
    functions following its definition.
  • Avoid using global variables - easy to introduce
    bugs in your code.
  • May use global const variables though.

include ltiostreamgt using namespace std int
x int main(void) ...
Write a Comment
User Comments (0)
About PowerShow.com