Subprograms - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

Subprograms

Description:

float computeAverage(int first, int second, int third) ... float answer = pow(3,4); //answer now contains the value 81 ... printResults(float root1) ... – PowerPoint PPT presentation

Number of Views:47
Avg rating:3.0/5.0
Slides: 27
Provided by: anni65
Category:

less

Transcript and Presenter's Notes

Title: Subprograms


1
Functions
2
Subprograms
  • A program within a program
  • A module
  • code written to define one well-defined subtask
  • Benefits of modularity
  • Easier to test, debug, and correct
  • bottom up testing - independent testing of
    modules
  • Readability
  • Reusability
  • Maintainability

3
Structured Programming
  • Subprograms are an important element in
    structured programming
  • Emphasis is on the flow of control between
    modules and how the modules communicate
  • Easy to distribute work between multiple
    developers
  • This skill can be applied to other languages you
    wish to learn
  • Examples of some other structured programming
    languages C, Java, Lisp, Smalltalk, Visual Basic

4
Functions
  • Subprograms in C
  • 3 components of functions
  • function declaration
  • function call
  • function definition

5
Function Declarations
  • ltreturn typegt ltfunction namegt (ltlist of
    argumentsgt)
  • ltreturn typegt is any valid type
  • this specifies the type of the value returned by
    the function, if any
  • this is also specifies the type of the function
  • ltfunction namegt is any valid identifier
  • make this descriptive
  • remember verbNoun suggestion from Style Guide
    e.g. computeAverage()
  • ltlist of argumentsgt
  • these are called parameters
  • this specifies any values that are needed by the
    function
  • float computeAverage(int first, int second, int
    third)
  • just like variables, functions must be declared
    before they are used

6
Function Call
  • ltreturn variable gt functionName(ltparameter
    listgt)
  • ltreturn variablegt is only appropriate if the
    function is of type other than void
  • int selection getMenuChoice()
  • displayMenu()
  • float sqrt pow(x, 0.5)

7
Function Definition
  • The function heading plus its implementation
  • float computeAverage(int first, int second, int
    third)
  • float retVal 0
  • retVal (first second third) / 3.0
  • return retVal

8
Library Functions
  • Functions that are used so frequently that they
    are provided for you by the compiler
  • To call/invoke a library function
  • functionName(ltparameter listgt)
  • These functions are declared in the appropriate
    header files, e.g. include ltcmathgt
  • there is no need to provide any additional
    declarations for these, it would actually be an
    error
  • Return values
  • float answer pow(3,4) //answer now contains
    the value 81
  • To find out how to use these functions
  • look in the header file where it is defined for
    its function prototype
  • look at the manual pages or online help for that
    function
  • man pow

9
Library Function Examples
  • Mathematics functions
  • pow, sqrt
  • found in cmath
  • Trigonometric functions
  • sin, cos, tan, acos, asin, atan
  • also found in cmath
  • String manipulation functions
  • strcat, strcpy
  • found in cstring

10
User-defined Functions
  • Need for this arises because library functions do
    not provide you with all the functionality you
    desire
  • float cube(float x)
  • return (xxx)
  • float cube(float x)
  • return pow(x,3)
  • Your program has specific needs and functionality

11
Function Components Example
12
Parameters/Arguments
  • Necessary so values can be passed to and from
    functions
  • Passed by value
  • this is the default
  • input only
  • Passed by reference
  • for anyone who knows C, this is something C does
    not have
  • input and output

13
Terms
  • Formal parameter
  • the symbolic name for the parameter used in the
    function definition
  • Actual parameter
  • the symbolic name for the parameter used in the
    function call
  • int area(int length, int width)
  • return length width
  • int result area(x,y)
  • length and width are the formal parameters
  • x and y are the actual parameters
  • Allocate
  • to set aside a chunk of memory
  • this happens every time you declare a variable
  • Deallocate
  • to release a chunk of memory
  • this happens every time you leave a block

14
Value Parameters
  • The actual value of the parameter is copied and
    used in the function
  • What does this mean?
  • A new chunk of memory is allocated(created) for
    the size of the parameter
  • The value of the parameter is copied into this
    chunk of memory
  • this is called the local copy
  • Any changes that you make to the local copy will
    be lost when the function is exited unless you
    return the value
  • the memory is deallocated(destroyed)
  • Use value parameters when you do not intend to
    modify the values of the parameters in the
    function

15
Reference Parameters
  • A reference to the value of the parameter is used
    by the function
  • Whats a reference?
  • A pointer to the chunk of memory where the value
    is located
  • Whats the effect?
  • Any changes that you make to the parameter will
    still be visible after the function is exited
  • No copying takes place
  • Memory is allocated for a pointer
  • Use reference parameters when your function needs
    to modify the values
  • Use if you need to return more than one value

16
More on Reference Parameters
  • Uses the symbol
  • // Function getData
  • void getData(int length, int width)
  • cout ltlt Enter a value for the length
  • cin gtgt length
  • cout ltlt Enter a value for the width
  • cin gtgt width
  • Oftentimes, functions using reference parameters
    have type void

17
Functions without Parameters
  • Has a void parameter list
  • Does work without requiring input
  • void displayHeader(void)
  • Requires no input, but returns a single value
  • int getSingleInput(void)

18
Functions without Returned Values
  • Return type of void
  • Does some work and doesnt need to return
    anything
  • void displayResults(int numStudents,
  • float average)
  • Needs to return multiple values
  • void getInput(int first, int second,
  • int third)

19
Program Design Using Functions
  • int main(void)
  • getData()
  • resultType result computeResults()
  • displayResults(result)
  • return 0

20
Errors with Functions
  • Redeclaration of a function
  • void printResults(float root1, float root2)
  • void printResults(float input1, float input2)
  • Parameter mismatches
  • void printResults(float root1)
  • printResults(root1, root2)
  • Forgetting to return a value if a return value is
    required
  • int printResults(float root1, float root2)
  • cout ltlt I should be printing out results ltlt
    endl
  • Passing by value when reference is necessary
  • run time error
  • void getData(float a, float b, float c)

21
Function Miscellany
  • Interface
  • how functions communicate with main and with
    other functions
  • a function signature tells other functions,
    including main, how to interface with it
  • You may use a boolean function call to determine
    whether to enter a block
  • if (isLeapYear(year))
  • cout ltlt Its a leap year! ltlt endl
  • You may cout the results of a function
  • cout ltlt pow(2,8)
  • You may nest function calls within function calls
  • result pow(3, pow(3,3)) // tower function

22
Function Overloading
You can use the same function name to support
varying functionality. This is called function
overloading. For example //compute area of
rectangle double area(double len, double
wid) return len wid // compute area of
circle double area(double radius) return M_PI
radius radius
23
Both functions are computing an area, but the
formula for area varies depending on the
shape. int main() double length, width,
radius cout ltlt Enter dimensions of rectangle
cin gtgt length gtgt width cout ltlt Area of
rectange ltlt area(length, width) cout ltlt
Enter radius of circle cin gtgt
radius cout ltlt Area of circle ltlt
area(radius) return 0 The first call to
area calls the area function that takes 2
arguments. The second call to area calls the
area function that takes 1 argument.
24
In addition to overloading functions by the
number of arguments, you can also overload the
function based on the types of arguments. For
example //compute area of rectangle with
doubles double area(double len, double
wid) return len wid // compute area of
rectangle with ints int area(int len, int
wid) return len wid
25
int main() double length, width cout ltlt
Enter floatingpt dimensions of rectangle
cin gtgt length gtgt width cout ltlt Area of
rectange1 ltlt area(length, width) int len,
wid cout ltlt Enter integral dimensions of
rectangle cin gtgt len gtgt wid cout ltlt Area
of rectangle2 ltlt area(len, wid) return
0 The first call to area calls the area
function that takes 2 double arguments. The
second call to area calls the area function that
takes 2 int arguments.
26
Overloading Rules
  • In summary, a function can be overloaded based
    on
  • The number of arguments
  • The types of arguments
  • NOT based on the return type.
Write a Comment
User Comments (0)
About PowerShow.com