Engineering 2420 Structured Programming - PowerPoint PPT Presentation

1 / 35
About This Presentation
Title:

Engineering 2420 Structured Programming

Description:

Engineering 2420 Structured Programming --- Introduction to C ... ceil (x) cmath Absolute value of its integer argument. int. int. abs (x) cstdlib Result ... – PowerPoint PPT presentation

Number of Views:17
Avg rating:3.0/5.0
Slides: 36
Provided by: lich2
Category:

less

Transcript and Presenter's Notes

Title: Engineering 2420 Structured Programming


1
Engineering 2420 Structured Programming
Cheng Li licheng_at_engr.mun.ca http//www.engr.mun.c
a/licheng/2420 EN-4012, 737-8972
Winter 2005
Lecture 12
2
Value returning functions
  • Value returning functions
  • Used when there is only one result returned
  • Often, function call used as part of an
    expression
  • Some built-in function sqrt(), abs(), pow(),
  • Example root1( -b sqrt(b b 4 a c)) /
    (2 a)
  • Value returning function definition
  • Form ReturnType Identifier (
    ParameterList )     
    Statements
  • Example double distance (double v, double t)
  • //code to compute distance d v t
  • return d

3
Void (non-value returning) functions
  • Void (non-value returning) functions
  • Do not return values to the calling program
  • Normally accomplishes some other tasks such as
    input, output or passes results through
    parameters or global variables
  • Non-value returning function definition
  • Form void Identifier ( ParameterList
    )      Statements
  • return
  • Example void printInt (int i)
  • cout ltlt The value for i is ltlt i

4
Difference Between Two Types
  • Main difference the way in which they are called
    or invoked
  • Void Function a call is a complete statement
  • printResult (averageStride, distance)
  • Value Returning Function a call occurs when the
    function appears in an expression or an
    assignment statement
  • cube pow (number, 3)
  • or area PI square (radius)

5
Function Arguments
  • Arguments are used to carry information into the
    function from (main, or other functions), or
    return multiple results computed by a function
    sub-program. Important!
  • The argument might be variable, an expression or
    simply a value
  • Arguments data type must match!

6
Program Structure Using Functions
  • For both types of functions, we have
  • (1) Function declarations without the body of the
  • function
  • -- Also known as Function declarations
  • (2) Inside Main function Function calls
  • (3) Function declarations with the body of the
    function
  • -- Also known as Function definitions
  • -- It is OUTSIDE of the main function

7
Function Definition
  • Void function
  • void Identifier (ParameterList)
  • Local declarations
  • Executable statements
  • return // Return Statement
  • Causes execution to jump back to the point of the
    function call
  • The return statement can be omitted

8
Definition for printComplex ( )
  • The void in front of the function name means that
    the function does not return any value at all.
  • No return statement is required since nothing
    returned
  • The paramater list allows us to pass inputs
    (called arguments) into functions (re and im
    (both doubles) in the example)
  • Function body appears between the block operators
  • Like main, it is consisted of a number of
    statements that are executed sequentially.
  • In general, if parameters have been passed into
    the function, the statement will do something
    with the data passed in.

9
Void Function Example
  • In printComplex, whatever values for re and im
    are passed in when the function is called will be
    printed out in standard complex notation.
  • Output the result of the Arnies jogging
  • void printResults (float averageStride, float
    distance)
  • cout ltlt The estimated average stride rate is
  • ltlt averageStride ltlt \nThe total
    distance is ltlt distance ltlt endl

10
Function Calling
  • Syntax of a function call
  • Form variable Identifier (
    ParameterList )
  • Example y sqrt(2x)
  • Interpretation the square root of 2x will be
    computed by the function and the result is
    assigned to variable y
  • ArgumentList is zero or more expressions,
    separated by commas.
  • Argument values are assigned to the parameters in
    the order that they appear.
  • If the function is value-returning, then function
    call is an expression.
  • If the function is void, then function call is a
    statement.
  • printComplex function is called in four separate
    places
  • fundamental principle of functions (and more
    generally program modules) gt use often?
    implement once !

11
Function Call Control Flow
  • Control flows from one instruction to the next in
    a step-like sequence.
  • Function calls alter the normal flow of control.
  • When a call is executed we leave the sequence and
    flow over to the beginning of the function
  • Instructions are then executed inside the
    function using the normal sequential sequence.
  • When the instructions in the function are
    finished control returns to the original sequence
    and picks up where it left off.

12
Function Prototype
  • Thinking function as a contract (a service), a
    program used by many others, who ever calls your
    function is your client.
  • The function prototype is the start of a contract
    between the service provider (programmer
    implementing the function) and the client
    (programmer using the function).
  • void printComplex(double re, double im)
  • It is the clients responsibility to provide
    values for the parameters re and im.
  • Wrong example! -- ignoring values passed to
    function.
  • Parameter values are provided by the caller!

13
Function Declaration
  • Tell the compiler the name and type of the
    function, and the information about arguments
    that function expects
  • Just like variables, functions must be declared
    before they are used. There is a difference,
    though.
  • Variables are declared inside functions (at the
    internal level)
  • Functions are declared outside functions (at the
    external level)
  • In our complex printing example the declaration
    of printComplex appears before main.
  • void printComplex(double re, double im)
  • Declaration is almost identical to the function
    prototype.
  • Format
  • - Void function void Identifier
    (ParameterList)
  • - Value-returning functions DataType Identifier
    (ParameterList)

14
Function Declaration Examples
  • Examples
  • -- Void function
  • void outputInstruction ()
  • or void printResults (float, float)
  • or void outputResults (int Number)
  • -- Value-returning function
  • int getNumber()
  • or float cube (int)
  • or double area (double length, double width)

15
Why declare?
  • Big programs are spread across multiple files.
  • Functions are implemented once only (in one file)
  • Functions are used (called) in many places (many
    files) so form of function must be declared
    before it is called.
  • Function declaration allows compiler to check
    that the grammar of the call is correct.
  • Wrong example.

16
An function declaration example
  • No implementation code here (normal for bigger
    programs) but the declaration tells us a lot!
  • ReturnType char, int, double, String, etc.
  • include ltiostreamgt
  • using namespace std
  • int minimum (int a1, int a2)
  • int main ()
  • int first, second
  • cout ltlt "Input the first number "
  • cin gtgt first
  • cout ltlt " the second one "
  • cin gtgt second
  • cout ltlt "\nThe minimum of the two numbers is "
  • cout ltlt minimum (first,second) ltlt '\n'
  • return 0

17
Implementation of minimum function
  • int minimum (int a1, int a2)
  • if (a1 lt a2)
  • return a1
  • else
  • return a2

18
(No Transcript)
19
(No Transcript)
20
Function Programming Example 1
  • Use function, write a C program that coverts
    degrees Fahrenheit to degrees Celsius
  • Formula
  • Celsius (5 / 9 ) ( Fahrenheit 32 )
  • Problem Input
  • float fahrenheit
  • Problem Output
  • float celsius
  • Functions conversion, output

21
  • Start with program template

include ltiostreamgt using namespace std int
main() float degC, degF cout ltlt Enter
degree in Fahrenheit cin gtgt degF return
0






22
  • Start with program template

include ltiostreamgt using namespace std int
main() float degC, degF cout ltlt Enter
degree in Fahrenheit cin gtgt degF return
0
float convertFtoC (float degF) float
degC //local variable degC 5. / 9. (degF -
32.0) return degC
float convertFtoC (float degF)
void printResult (float degC, float degF)
void printResult (float degC, float degF)
cout ltlt degF ltlt degrees Fahrenheit
ltlt equals ltlt degC ltlt
degree Celsius. ltlt endl
degC convertFtoC ( degF)
printResult (degC, degF)
23
Function Programming Example 2
  • Function calls can include functions as an
    argument
  • Suppose we have square and cube functions
  • How to write the C program to calculate
  • Suppose we declared result and number to hold the
    value of y and x respectively, we can write as
  • result cube ( square ( number ) cube (
    number) )

24
Library Functions
  • Many common mathematical functions such as
    triangle, logarithm, exponentiation, absolute,
    etc. are available in the libraries such as cmath
  • Dont re-invent the wheel
  • Need to include the appropriate library header
    file, example include ltcmathgt
  • Details can be found in Table 3.1 (p.170) and in
    Appendix C.

25
Some Commonly Used Library Functions
26
(No Transcript)
27
(No Transcript)
28
Instant Quiz!
  • What is wrong with each of the following C
    function definitions?

b. float test2 (int i, float x) i
i 7 x 4.8 float (i)
a. void test1 (int m, int n) return 3
m n
29
Problem Solving With Function
  • Problem Evaluate an integral of a function F(x)
    given the upper and lower limits using the
    trapezoidal rule
  • Function
  • Trapezoidal Rule

30
Analyze the Problem
  • Specify input and output
  • Input upper and lower limits
  • Output the value of the integral
  • Decide functions to be used
  • sampleF(x) get the sample from the integrand
    function
  • trap(lowerLimit, upperLimit) get the approximate
    area
  • Structure of program
  • Input upper and lower limits
  • Calculate the value of the integral
  • Output the value of the integral

31
  • Start with program template

include ltiostreamgt include ltcmathgt using
namespace std int main() double lower,
upper, integralValue cout ltlt Enter the lower
limit cin gtgt lower cout ltlt Enter the
upper limit cin gtgt upper cout ltlt The
value of the integral is ltlt
integralValue ltlt endl return 0
double trap (double lower, double upper)


double sampleF (double x)

32
  • Start with program template

include ltiostreamgt include ltcmathgt using
namespace std int main() double lower,
upper, integralValue cout ltlt Enter the lower
limit cin gtgt lower cout ltlt Enter the
upper limit cin gtgt upper cout ltlt The
value of the integral is ltlt
integralValue ltlt endl return 0
double trap (double lower, double upper)
double average, range range upper
lower average (sampleF(upper)
sampleF(lower)) / 2.0 return range average
double sampleF (double x)
double trap (double lower, double upper)
double sampleF (double x) double sample
//local variable sample x sin(x x)
cos(x) return sample
integralValue trap(lower, upper)
33
Scope of Names
  • Refers to the region in a program where the name
    can be used
  • Local scope An identifier declared with a block
    (braces)
  • Scope extends from declaration to the end of
    block
  • Parameter scope extends to the whole function
    definition
  • Global scope An identifier declared outside all
    blocks
  • Scope extends from declaration to the end of the
    compilation unit (source file).

34
Scope of Names
  • void funcOne (int one, double two)
  • int funcTwo (int three, char four)
  • const float PI 3.14159
  • double varG
  • int main ()
  • int first
  • //end main
  • void funcOne (int one, doublw two)
  • float second
  • //end funcOne
  • int funcTwo (int three, char four)
  • bool third

35
More about Scope
  • Try to keep the scope of variables small it can
    make your code easier to read and modify
  • Prefer local variables over global variables
  • Use parameters rather than global variables to
    pass information to functions
  • If your parameter list is too long, maybe your
    function is doing too much consider splitting
    into more smaller functions
  • Example scope.cpp
Write a Comment
User Comments (0)
About PowerShow.com