Flow Control 2 Looping Continued... - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

Flow Control 2 Looping Continued...

Description:

int &rodent = rat; // Make rodents an alias for rats ... means a reference-to-int and allow you to use rats and rodents interchangeably. ... – PowerPoint PPT presentation

Number of Views:29
Avg rating:3.0/5.0
Slides: 34
Provided by: duyng
Category:

less

Transcript and Presenter's Notes

Title: Flow Control 2 Looping Continued...


1
Flow Control 2Looping Continued...
  • do-while statement
  • Syntax do
  • statement
  • while (condition)
  • next statement
  • The statement is executed AT LEAST ONCE. The
    statement will iterate as long as condition is
    TRUE.
  • Most useful structure for input validation.
  • Example
  • char c
  • do
  • cin gtgt c
  • while (c c \t c \n)
  • / skip all the white space before the first
    visible character. /

2
  • Although for a simple statement as in the
    example, the braces are not required, we usually
    write the do-while loop as
  • do
  • statement
  • while(condition)
  • to avoid thinking of the semicolon after the
    while as an empty statement for a while loop.

3
  • The break and continue statements
  • Interrupt the normal flow of control.
  • The break statement causes exit from the
    innermost enclosing loop or switch statement as
    explained before.
  • Example while(1)
  • cin gtgt x
  • if (x lt 0.0)
  • break
  • cout ltlt sqrt(x) ltlt endl
  • / break jumps here /
  • The continue statement causes the current
    iteration of a loop to stop and the next
    iteration to begin immediately. It occurs in
    for, while, and do-while loops only.

4
  • Example
  • while (cnt lt n)
  • cin gtgt x
  • if (x gt -0.01 x lt 0.01)
  • continue / discard small values /
  • cnt
  • sum x
  • / continue transfer control here /
  • In a for loop, continue skips the rest of the
    loop body and begins the next iteration from the
    update statement.

5
  • The goto statement
  • Very bad practice (there will be no goto usage
    in this class!)
  • Jump to a labeled statement unconditionally.
  • Syntax label statement
  • goto label
  • label is in the form of an identifier.
  • The exit command
  • Causes the program to end.

6
Functions
  • Top-down approach
  • Break a big problem into smaller problems.
    Refine each small problem into even smaller ones
    until each small problem is obvious and easy to
    handle. This divide-and-conquer approach is
    called top-down design.
  • Example Design a program to find the maximum,
    minimum of three numbers and sort the numbers.
    The structure of your main program may look like
    this
  • 1. Print an introduction message to explain how
    to use the program.
  • 2. Read the input numbers.
  • 3. Process the numbers
  • 4. Print out the results.

7
  • We can further divide step 3 into smaller steps
  • 3a. Find the maximum number.
  • 3b. Find the minimum number.
  • 3c. Sort the numbers.
  • Functions
  • Functions extend the abilities of operators, e.g.
    we want to calculate powers of a number (x2 --gt
    pow(x,2)).
  • Functions are sub-programs that allow users to
    ignore irrelevant details.

8
  • Functions define and promote reusable codes to
    reduce programming effort, e.g. library calls.

Function
Inputs (Argument list)
Output (returned result)
9
Sample Predefined C Functions
  • C/C provide many predefined mathematical
    functions
  • ceil(x) - rounds x to the smallest integer not
    less than x.
  • cos(x)
  • sin(x)
  • floor(x) - rounds x to the largest integer not
    greater than x.
  • fabs(x) - absolute value.
  • sqrt(x)
  • log(x)
  • log10(x)
  • etc

10
  • Function definitions
  • return_type function_name (argument list)
  • Example
  • double sum(int num1, int num2)
  • double result
  • result (double)num1 (double)num2
  • return result
  • Return type matches the data type of the result
    to be sought.
  • Function name is any legitimate identifier.

11
  • Argument list is a comma separated list data
    types and identifiers in pairs. Argument list in
    the function definition is called formal
    parameters. They form the interface of the
    function to the outside calling functions and can
    be used in the function body.
  • Function body is enclosed in braces.
  • Functions are called by writing the function name
    and arguments in a parenthesis matching the data
    types defined in the function definition.
    Example
  • x sum(3, 5) / x has been declared double
    /
  • The return statement passes the control back to
    the calling function and also passes the result
    back. In the last example, the result is
    assigned to x.
  • Syntax return expression

12
  • Variable declaration can be anywhere in a
    function before the identifier is used. By
    convention, we always declare locally used
    variables in the beginning of the function.
  • A function with a return type void returns
    nothing to the calling function. The return
    statement simply passes control back to the
    calling function.
  • By default, a function declared with no explicit
    return type returns an int.
  • A function with only the keyword void in the
    argument list takes no input. Omission of the
    keyword void causes the compiler to assume the
    void keyword.
  • C requires that all functions be prototyped.
  • If the definition of a function is declared
    before the function is used, then prototyping is
    not required.

13
  • The parentheses cannot be omitted in both the
    definition and function call even if the function
    has no input.
  • Example Calculate the square of the sum of two
    real numbers

sum_of_square.cpp
14
  • Call-by-value (or pass-by-value)
  • This is one mechanism for parameter passing in
    C. In a function call, the called function
    makes a local copy of the formal parameters. The
    values of the actual parameters. The values of
    the actual parameters are copies to the memories
    of the local copy of the formal parameters. All
    the manipulations of the formal parameters by the
    function will only modify the local value. The
    actual parameter in the calling function will not
    be changed. When the function goes out of scope,
    all the local variables are destroyed and the
    memory resources used are returned to the OS.

15
  • Function declaration (prototypes)
  • Prototypes are similar to function definition
    except that function body enclosed in the braces
    is missing and prototypes end with a semicolon.
    Example
  • double sum_of_square(double x, double y)
  • The return type and argument types must match in
    the prototype and definition.
  • Identifiers in the argument list can be omitted
    as
  • double sum_of_square(double, double)
  • Prototypes are provided to check against function
    definition and improve code correctness.
  • Prototypes are usually put in the beginning of
    the file before the functions are called, or they
    are put in a header file and included in the
    beginning of the .cpp file, e.g. header files.

16
  • Prototype is also a forward declaration of
    functions.
  • Provide default arguments
  • double sum_of_square(double x 1, double y
    1)
  • Function calls sum_of_square() or
    sum_of_square(2)
  • Variable scopes
  • Local variables variables declared in the
    argument list and in the function body. They are
    known to the function only.
  • Different functions can use the same name for
    their local variables. In the last example,
    result in the main function and result in
    sum_of_square are different identifiers.
  • Memory for local variables are allocated by the
    OS only when the function is called.
  • Local variables are destroyed when the function
    returns. We say the variable is out of scope.

17
  • Global variables Variables defined outside any
    functions and are visible to all functions.
  • Global variables are shielded by local variables
    declared with the same name.
  • Example
  • include ltiostream.hgt
  • /declaring global variables. /
  • int x, y
  • int func1(void)
  • double u, v
  • .
  • char func2(int s)
  • float x
  • .

18
  • x and y are global variables. Since x is
    redefined as float in func2, func2 does not see
    the global int type x. It only sees the global
    y. u and v are only seen by func1, s only by
    func2. Those are local variables. Since y is
    seen by both func1 and func2, it is possible that
    func1 modifies y somewhere and func2 does not
    know and assumes y is still unchanged. This
    side-effect is prone to mistake, so the use of
    global variable is strongly discouraged unless
    absolutely necessary.
  • Static variables
  • Declaring a local variable inside a function as a
    static variable prevents the compiler from
    destroying that variable upon the programs exit.
  • static float x

19
Inline Functions
  • Keyword inline
  • Preceding the function with the word inline
    causes the compiler to replace each function call
    in the program with the actual function code.
  • inline sum_of_square(double x, double y) /
    Codes go here /
  • The inline keyword can also be declared at the
    function prototype.

20
Terminology
  • Parameter passing
  • Actual parameters The parameters in the
    argument list of function calls.
  • Example
  • int foo(double x, int y)
  • int main(void)
  • double s
  • int t
  • foo(s, t)
  • x and y in the function definition are formal
    parameters.
  • s and t in the function call are actual
    parameters.

21
Reference
  • C adds a new derived type to the C language -
    the reference variable.
  • A reference is a name that acts as an alias, or
    alternative name, for a previously defined
    variable.
  • The main use for a reference is as a formal
    argument to a function. By using reference as an
    argument, the function works with the original
    data instead of with a copy.

22
  • Before seeing how references are used in function
    calls, lets examine the basics of defining and
    using a reference.
  • Both C and C use the symbol to indicate the
    address of a variable. C assigns an additional
    meaning to the symbol - to define reference
    variables.
  • Example
  • int rat
  • int rodent rat // Make rodents an alias for
    rats
  • In this case, the means a reference-to-int and
    allow you to use rats and rodents interchangeably.

23
  • Consider the following example
  • int rat 101
  • int rodent rat // rodent a reference
  • The expressions rodent and rat are used
    interchangeably.
  • It is necessary to initialize the reference when
    you declare it. You cannot declare a reference
    and then assign it a value later
  • int rat
  • int rodent
  • rodent rat // Illegal, cannot do this.

24
  • Consider the following example
  • int rat 101
  • int rodent rat
  • int bunny 50
  • rodent bunny
  • The first two statements implies
  • rat 101 rodent 101
  • rat address 1010203 rodent address
    1010203
  • The third statement initializes bunny implying
  • bunny 50 and bunny address 2030405
  • The final statement results in
  • bunny 50 rodent 50 rat 50
  • bunny address 2030405 rodent address
    1010203
  • rat address 1010203
  • The final statement has the same meaning as
    rat bunny

25
  • Call-by-reference (or pass-by-reference)
  • The formal parameter is an alias to the actual
    parameter in this case. They both refer to the
    same memory location. Manipulation of the formal
    parameter is reflected in the change of the
    actual parameter. Only the alias name is
    destroyed when the function returns.
  • Implemented in PASCAL
  • Sometimes called call-by-variable or
    pass-by-reference
  • Functions only allow one return variable,
    call-by-reference enables more than one variables
    to be changed in a function call.

26
Example Write a function to swap the contents
in two integer variables.
swap.cpp
27
swap(i1, i2)
main()
void swap(int a, int b)
Address
00110
i1
00111
i1
3
a
00111
a
aliases
01000
i2
4
b
01000
b
i2
01001
temp
01010
Call-by-reference as seen by the computer
28
  • Some notes on functions
  • Always put comments in front of each function
    definition to explain what the function will
    accomplish.
  • Each function should only do one thing. The
    guideline is that each function should be about
    one page long. If it is too long, you are
    attempting too many things at the same time.
    Break the function into simpler jobs.
  • Each function must have a prototype.
  • Keep the argument list to a minimum. Do not pass
    too many arguments at a time. If you are passing
    too many arguments, you may be doing too many
    things at the same time. Again, break your
    function into smaller ones.

29
References As Function Parameters
  • Most often, references are used as function
    parameters, making a variable name in the
    function an alias for a variable in the calling
    program. This method of passing arguments is
    called passing by reference.
  • Consider the swapping functions below
  • void swapr(int a, int b) // Use references
  • int temp
  • temp a
  • a b
  • b temp

30
  • void swapp(int a, int b) // Try using values
  • int temp
  • temp a
  • a b
  • b temp

31
  • void main()
  • int wallet1 300
  • int wallet2 350
  • swapr(wallet1, wallet2)
  • cout ltlt wallet1 ltlt ltlt wallet2 ltlt endl
  • swapv(wallet1, wallet2)
  • cout ltlt wallet1 ltlt ltlt wallet2 ltlt endl

32
  • Passing by reference and passing by value look
    identical. The only way to tell the difference
    is by looking at the function prototypes or the
    function definitions.
  • The internal difference between swapr(int a,
    intb) and swapv(int a, int b) is that in the
    former function, variables a and b serve as
    aliases for wallet1 and wallet2, respectively.

33
Homework
  • Homework 3
  • Page 230, 3.20
  • Page 232, 3.29
  • Page 232, 3.31
  • Read Chapter 4
Write a Comment
User Comments (0)
About PowerShow.com