Designing Programs with Functions - PowerPoint PPT Presentation

1 / 31
About This Presentation
Title:

Designing Programs with Functions

Description:

... into smaller subtasks and write a separate block of code fore each subtask. as we think of how to build a program, think of blocks of code as functions to ... – PowerPoint PPT presentation

Number of Views:24
Avg rating:3.0/5.0
Slides: 32
Provided by: jian9
Category:

less

Transcript and Presenter's Notes

Title: Designing Programs with Functions


1
Chapter 5
  • Designing Programs with Functions

2
Outline
  • Predefined C functions - Library
  • writing value-returning functions
  • program design with value-returning functions
  • void functions and program design
  • Function calling other functions
  • Function stubs
  • SKIP section 5.7
  • section 5.8

3
Introduction to Functions
  • A function is a named block of code
  • Top-down (outside-in) design
  • to divide a complicated problem into smaller
    subtasks and write a separate block of code fore
    each subtask
  • as we think of how to build a program, think of
    blocks of code as functions to be implemented in
    detail later
  • Code re-use
  • Write the code once use it as many times as you
    need to
  • Information hiding
  • Without caring about the implementation details
  • Protect data in a function from other functions
    mishandling

4
Predefined functions - cmath Library
  • cmath - Library of Mathematical Functions
  • To use them, we must first include ltcmathgt
  • Example Getting the square root of variable X
  • Y sqrt (X)
  • function call a statement or expression that
    transfers control to a function which performs
    its subtask.
  • Evaluate expression in parentheses (the argument)
  • Pass argument (in this case, Xs value) to
    function sqrt
  • Store the result (return value) of sqrt into
    variable Y
  • Function pow (power) 2 parameters
  • We dont have an exponentiation operator in C
  • cout ltlt pow (2.0, 8.0)
  • Lots of other cmath functions (page 94 of text)

5
Predefined functions - cmath Library
y sqrt(9) is a statement
sqrt (9) is an expression
int x, y x 2 y sqrt(9) cout ltlt y ltlt
endl y sqrt(10x 5) cout ltlt y ltlt endl
  • 3
  • 5
  • 1.41421

function-name (argument1, argument2, . . .)
6
Value returning Functions
7
Writing Value-Returning Functions
  • To write our own functions, we need 1) a
    declaration
  • 2) a definition

8
Writing Value-Returning Functions
  • Function Declaration (prototype)

semicolon
  • MUST be placed BEFORE main function
  • specifies what the function accomplishes
  • 1) parameters (with data type) used to receive
    data
  • 2) the data type of the return value

9
Writing Value-Returning Functions
  • Function Definition (implementation)

NO semicolon
  • specifies how the function performs its subtask
  • 1) Header same as declaration without the
    semicolon
  • 3) Body actual code that carries out the task,
    and returns the value to the point where the
    function was called
  • It must have at least one return statement
  • Of the form return value
  • Causes control to return to caller, passing the
    value back to it

10
Parameters vs. Arguments
parameters are variables that belong to the
function (in declaration and definition header),
used to receive data from the calling statement.
parameters
arguments appear in the function call, hold the
data to be passed to a function
arguments
parameters
11
Parameter and Argument Matching
  • A function call creates a memory cell for each
    parameter and then copies the value of the
    matching argument into that cell
  • Arguments and parameters are matched from left to
    right based on their positions, i.e., the value
    of the first argument is passed (assigned) to the
    first parameter.

IMPORTANT!
The names of the arguments parameters do not
matter for this purpose Theyd better be of
compatible data types
12
Value parameters passing by value
  • What were doing here is passing by value
  • Argument is evaluated
  • Then a copy of that value is passed to the
    corresponding parameter of the called function
  • If a function changes the value of one of its
    parameters, that change will stay local to the
    function
  • it will NOT affect the arguments value back at
    the point of the call

13
Scope of Variables
14
Local Variables
  • Variables declared within a function
  • accessible only by statements within the function

Parameters are actually local variables
pre-filled with copied values from arguments
15
Local variables
16
Scope of variables
  • The scope of a variable is the portion of the
    program in which statements can use them
  • Scope for local variables and value parameters is
    limited to the body of that function
  • Scope of (local) variables defined in main is
    limited to the body of main
  • Global variables and constants are defined before
    main and can be used in all functions
  • Read Section 9.4

include ltiostreamgt const double RATE
5.00 double function (int iHours)int main(
) double salary int hours salary
function(hours) double function(int
iHours) doulbe dSalary dSalary iHours
RATE return dSalary
17
Program design with value-returning functions
18
Program design with value-returning functions
  • Two rules when designing a program
  • Simplify the body of main in a way it calls
    functions to perform subtasks
  • Modularize the program so that each piece of
    program corresponding to difference subtasks
    handled by separate functions
  • Each section of assignment 2 can be organized as
  • int main ( )
  • double result
  • // input subtask
  • result function ( ) // calculation
    subtask
  • // output subtask
  • double function ( )

19
Program design with value-returning functions
  • int main ( )
  • const int R_RATE 100, N_RATE 200
  • int iResTuition, iNResTuition,
  • int iNumCred
  • char chResStatus
  • // input subtask
  • // calculation subtask
  • if (chResStatus R)
  • iResTuition CalTuition(iNumCred, R_RATE)
  • else
  • iNResTuition CalTuition(iNumCred, N_RATE)
  • // output subtask
  • return 0

20
void Functions
21
void (Non-Value Returning) Functions
  • A non-value returning function has return type
    void
  • void print_value(int d, int q)
  • used for calculation and output the results
  • It can (optional) have return statements, but not
    with a value attached
  • Of the form return
  • Causes control to return to caller, but without a
    value

22
void (Non-Value Returning) Functions
declare a void function
call a void function
define a void function
23
Parameterless Functions
  • It could be a void function like
  • void output( ) // declaration
  • output( ) // call
  • It could be a value-returning function like
  • int calculate( ) // declaration
  • result calculate( ) // call

Youve defined one before int main ()
return 0 main Is Just Another Function
called by the operating system Most programs
have lots of functions where to start? OS
starts executing a program by calling its main
function
24
Functions Calling Other Functions
25
Functions calling other functions
  • Month Day Year Display
  • 5 6 1998 05/06/1998
  • 12 2 2000 12/06/2000

26
Function Stubs
  • A Tool For Use During Development
  • Stub a function that has the correct interface,
    but doesnt do all the things its supposed to
  • So you can easily write something to develop
    test other functions that call this one
  • The stub functions return a phony value for
    testing

27
Function Stubs
28
  • double payment (double A, double r, int m)
  • double num, den
  • num r A / 12
  • den 1 pow (1 r/12, -m)
  • return num/den

29
  • void decide_load (double payment, double
    ann_income)
  • if ( ann_income / 12 gt payment)
  • cout ltlt LOAN APPROVED! ltlt endl
  • cout ltlt The monthly payment is ltlt payment
    ltlt endl
  • else
  • cout ltlt LOADN DENIED ltlt endl
  • cout ltlt Have a nice day. ltlt endl

30
Saving and Reusing Functions
  • Modifying a library
  • Creating your own library
  • Using header (.h) files to contain all the
    function declarations (prototypes) for a library
  • Compiled code for librarys functions gets
    included into the executable program by the
    linker

31
Using Other Library Functions
  • In library cctype
  • Character classification manipulation
  • isalpha (Char) isdigit (Char)
  • toupper (Char) tolower (Char)
  • In library stdlib
  • Pseudo-random number generation
  • Pseudo because computers are deterministic
  • Function declaration int rand ()
  • Generates a pseudorandom number between 0
    INT_MAX
Write a Comment
User Comments (0)
About PowerShow.com