CHAPTER 7 USER-DEFINED FUNCTIONS II - PowerPoint PPT Presentation

1 / 71
About This Presentation
Title:

CHAPTER 7 USER-DEFINED FUNCTIONS II

Description:

Enter the number of star lines (1 to 20) to be printed-- 15. Example 7-4 ... the dataType in the formal parameter list of a function, then the variable ... – PowerPoint PPT presentation

Number of Views:49
Avg rating:3.0/5.0
Slides: 72
Provided by: dma120
Category:
Tags: chapter | defined | functions | user | list | names | of | star

less

Transcript and Presenter's Notes

Title: CHAPTER 7 USER-DEFINED FUNCTIONS II


1
CHAPTER 7USER-DEFINED FUNCTIONS II
2
  • VOID FUNCTIONS
  • Void functions and value-returning functions have
    similar structures.
  • Both have a heading part and a statement part.
  • User-defined void functions can be placed either
    before or after the function main.
  • The program execution always begins with the
    first statement in the function main.
  • If you place user-defined void functions after
    the function main, you should place the function
    prototype before the function main.
  • A void function does not have a data type and so
    functionType in the heading part and the return
    statement in the body of the void function are
    meaningless.
  • In a void function, you can use the return
    statement without any value it is typically used
    to exit the function early.
  • Void functions may or may not have formal
    parameters.
  • A call to a void function is a stand-alone
    statement.

3
  • Void Functions without Parameters
  • Syntax Function Definition
  • void functionName(void)
  • statements
  • The word void inside the parentheses is optional.
  • In C, void is a reserved word.
  • Syntax Function Call
  • functionName()

4
  • Example 7-1
  • Annual
  • Spring Sale

5
  • include ltiostreamgt
  • using namespace std
  • void printStars(void)
  • int main()
  • printStars() //Line 1
  • coutltlt" Annual "ltltendl
    //Line 2
  • printStars() //Line 3
  • coutltlt" Spring Sale "ltltendl
    //Line 4
  • printStars() //Line 5
  • return 0
  • void printStars(void)
  • coutltlt""ltltendl
  • coutltlt""ltltendl

6
  • Void Functions with Parameters
  • Syntax Function Definition
  • void functionName(formal parameter list)
  • statements
  • Syntax Formal parameter list
  • dataType variable, dataType variable, ...

7
  • Syntax Function Call
  • functionName(actual parameter list)
  • Syntax Actual Parameter List
  • expression or variable, expression or variable,

8
  • Sample Run The user input is in red.
  • Enter the number of star lines (1 to 20) to be
    printed--gt 15


9
  • Example 7-4
  • //Program Print a triangle of stars
  • include ltiostreamgt
  • using namespace std
  • void printStars(int blanks, int starsInLine)
  • int main()
  • int numberOfLines
  • int counter
  • int numberOfBlanks
  • coutltlt"Enter the number of star lines (1 to
    20)"
  • ltlt" to be printed--gt " //Line 1
  • cingtgtnumberOfLines //Line 2

10
  • while(numberOfLines lt 0 numberOfLines gt 20)
    //Line 3
  • coutltlt"Number of star lines should be "
  • ltlt"between 1 and 20"ltltendl //Line 4
  • coutltlt"Enter the number of star lines "
  • ltlt"(1 to 20)to be printed--gt " //Line 5
  • cingtgtnumberOfLines //Line 6
  • coutltltendlltltendl //Line 7
  • numberOfBlanks 30 //Line 8
  • for(counter 1 counter lt numberOfLines
  • counter) //Line 9
  • printStars(numberOfBlanks, counter) //Line 10
  • numberOfBlanks-- //Line 11

11
  • return 0 //Line 12
  • void printStars(int blanks, int starsInLine)
  • int count
  • for(count 1 count lt blanks count) //Line
    13
  • coutltlt" " //Line 14
  • for(count 1 count lt starsInLine count)
    //Line 15
  • coutltlt" " //Line 16
  • coutltltendl

12
  • Value Parameter A formal parameter that receives
    a copy of the content of the corresponding actual
    parameter.
  • Reference Parameter A formal parameter that
    receives the location (memory address) of the
    corresponding actual parameter.
  • When we attach after the dataType in the formal
    parameter list of a function, then the variable
    following that dataType becomes a reference
    parameter.
  • Example 7-3
  • void expfun(int one, int two, char three,
    double four)

13
  • If a formal parameter is a value parameter, the
    value of the corresponding actual parameter is
    copied into the formal parameter.
  • The value parameter has its own copy of the data.
  • During program execution, the value parameter
    manipulates the data stored in its own memory
    space.
  • If a formal parameter is a reference parameter,
    it receives the address of the corresponding
    actual parameter.
  • A reference parameter stores the address of the
    corresponding actual parameter.
  • During program execution to manipulate the data,
    the address stored in the reference parameter
    directs it to the memory space of the
    corresponding actual parameter.

14
  • Reference Parameters
  • Value parameters provide only a one-way link
    between actual parameters and formal parameters.
  • A reference parameter receives the address of the
    actual parameter.
  • Reference parameters can pass one or more values
    from a function and can change the value of the
    actual parameter.
  • Reference parameters are useful in three
    situations
  • When you want to return more than one value from
    a function
  • When the value of the actual parameter needs to
    be changed
  • When passing the address would save memory space
    and time relative to copying a large amount of
    data

15
  • Example 7-5
  • Given the course score (a value between 0 and
    100), the following program determines the course
    grade of a student.
  • 1. main
  • a. Get Course Score.
  • b. Print Course Grade.
  • 2. getScore
  • a. Prompt the user for the input.
  • b. Get the input.
  • c. Print course score.
  • 3. printGrade
  • a. Calculate the course grade.
  • b. Print course grade.

16
  • // Program Compute grade.
  • // This program reads a course score and prints
    the
  • // associated course grade.
  • include ltiostreamgt
  • using namespace std
  • void getScore(int score)
  • void printGrade(int score)
  • int main ()
  • int courseScore
  • coutltlt"Line 1 Based on the course score, this
    program "
  • ltlt"computes the course grade."ltltendl //Line
    1

17
  • getScore(courseScore) //Line 2
  • printGrade(courseScore) //Line 3
  • return 0
  • void getScore(int score)
  • coutltlt"Line 4 Enter course score--gt " //Line
    4
  • cingtgtscore //Line 5
  • coutltltendlltlt"Line 6 Course score is "
  • ltltscoreltltendl //Line 6

18
  • void printGrade(int score)
  • coutltlt"Line 7 Your grade for the course is
    " //Line 7
  • if(score gt 90) //Line 8
  • coutltlt"A"ltltendl
  • else if(score gt 80)
  • coutltlt"B"ltltendl
  • else if(score gt 70)
  • coutltlt"C"ltltendl
  • else if(score gt 60)
  • coutltlt"D"ltltendl
  • else
  • coutltlt"F"ltltendl

19
  • Sample Run
  • Line 1 Based on the course score, this program
    computes the course grade.
  • Line 4 Enter course score--gt 85
  • Line 6 Course score is 85
  • Line 7 Your grade for the course is B

20
  • VALUE AND REFERENCE PARAMETERS AND MEMORY
    ALLOCATION
  • When a function is called, memory for its formal
    parameters and variables declared in the body of
    the function (called local variables) is
    allocated in the function data area.
  • In the case of a value parameter, the value of
    the actual parameter is copied into the memory
    cell of its corresponding formal parameter.
  • In the case of a reference parameter, the address
    of the actual parameter passes to the formal
    parameter.
  • Content of the formal parameter is an address.
  • During execution, changes made by the formal
    parameter permanently change the value of the
    actual parameter.
  • Stream variables (for example, ifstream and
    ofstream) should be passed by reference to a
    function.

21
  • Example 7-6
  • //Example 7-6 Reference and value parameters
  • include ltiostreamgt
  • using namespace std
  • void funOne(int a, int b, char v)
  • void funTwo(int x, int y, char w)
  • int main()
  • int num1, num2
  • char ch
  • num1 10 //Line 1
  • num2 15 //Line 2
  • ch 'A' //Line 3

22
  • coutltlt"Line 4 Inside main num1 "ltltnum1
  • ltlt", num2 "ltltnum2ltlt", and ch
    "ltltchltltendl //Line 4
  • funOne(num1, num2, ch) //Line 5
  • coutltlt"Line 6 After funOne num1 "ltltnum1
  • ltlt", num2 "ltltnum2ltlt", and ch
    "ltltchltltendl //Line 6
  • funTwo(num2, 25, ch) //Line 7
  • coutltlt"Line 8 After funTwo num1 "ltltnum1
  • ltlt", num2 "ltltnum2ltlt", and ch "ltltchltltendl
    //Line
  • return 0

23
  • void funOne(int a, int b, char v)
  • int one
  • one a //Line 9
  • a //Line 10
  • b b 2 //Line 11
  • v 'B' //Line 12
  • coutltlt"Line 13 Inside funOne a "ltltaltlt", b
    "ltltb
  • ltlt", v "ltltvltlt", and one
    "ltltoneltltendl//Line 13
  • void funTwo(int x, int y, char w)
  • x //Line 14
  • y y 2 //Line 15
  • w 'G' //Line 16
  • coutltlt"Line 17 Inside funTwo x "ltltx

24
  • Output
  • Line 4 Inside main num1 10, num2 15, and ch
    A
  • Line 13 Inside funOne a 11, b 30, v B,
    and one 10
  • Line 6 After funOne num1 10, num2 30, and
    ch A
  • Line 17 Inside funTwo x 31, y 50, and w G
  • Line 8 After funTwo num1 10, num2 31, and
    ch G

25
  • Just before Line 1 executes, memory is allocated
    only for the variables of the function main this
    memory is not initialized. After Line 3 executes,
    the variables are as shown in Figure 7-1.

26
  • coutltlt"Line 4 Inside main num1 "ltltnum1
  • ltlt", num2 "ltltnum2ltlt", and ch
    "ltltchltltendl //Line 4
  • Line 4 produces the following output.
  • Line 4 Inside main num1 10, num2 15, and ch
    A

27
  • one a //Line 9
  • Just before Line 9 executes, the variables are as
    shown in Figure 7-2.

28
  • one a //Line 9
  • After Line 9 (one a)executes, the variables
    are as shown in Figure 7-3.

29
  • a //Line 10
  • After Line 10 (a) executes, the variables are
    as shown in Figure 7-4.

30
  • b b 2 //Line 11
  • After Line 11 (b b 2) executes, the
    variables are as shown in Figure 7-5.

31
  • v 'B' //Line 12
  • After Line 12 (v 'B') executes, the variables
    are as shown in Figure 7-6.

32
  • coutltlt"Line 13 Inside funOne a "ltltaltlt", b
    "ltltb
  • ltlt", v "ltltvltlt", and one
    "ltltoneltltendl//Line 13
  • Line 13 produces the following output.
  • Line 13 Inside funOne a 11, b 30, v B,
    and one 10

33
  • After the execution of line 13, control goes back
    to line 6 and memory allocated for the variables
    of function funOne is deallocated. Figure 7-7
    shows the values of the variables of the function
    main.

34
  • coutltlt"Line 6 After funOne num1 "ltltnum1
  • ltlt", num2 "ltltnum2ltlt", and ch
    "ltltchltltendl //Line 6
  • Line 6 produces the following output.
  • Line 6 After funOne num1 10, num2 30, and
    ch A

35
  • x //Line 14
  • Before the execution of Line 14.

36
  • x //Line 14
  • After Line 14 (x) executes, the variables are
    as shown in Figure 7-9.

37
  • y y 2 //Line 15
  • After Line 15 (y y 2)executes, the variables
    are as shown in Figure 7-10.

38
  • w 'G' //Line 16
  • After Line 16 (w 'G') executes, the variables
    are as shown in Figure 7-11.

39
  • coutltlt"Line 17 Inside funTwo x "ltltx
  • ltlt", y "ltlty ltlt", and w
    "ltltwltltendl//Line 17
  • Line 17 produces the following output.
  • Line 17 Inside funTwo x 31, y 50, and w
    G

40
  • After the execution of Line 17, control goes to
    Line 8. The memory allocated for the variables of
    function funTwo is deallocated.

41
  • coutltlt"Line 8 After funTwo num1 "ltltnum1
  • ltlt", num2 "ltltnum2ltlt", and ch "ltltchltltendl
    //Line 8
  • Line 8 produces the following output.
  • Line 8 After funTwo num1 10, num2 31, and
    ch G
  • After the execution of line 8, the program
    terminates.

42
  • REFERENCE PARAMETERS AND VALUE-RETURNING
    FUNCTIONS
  • SCOPE OF AN IDENTIFIER
  • The scope of an identifier refers to where in the
    program an identifier is accessible (that is
    visible).
  • Local identifier Identifiers declared within a
    function (or block).
  • Global identifier Identifiers declared outside
    of every function definition.
  • C does not allow the nesting of functions. That
    is, the definition of one function cannot be
    included in the body of another function.

43
  • 1. Global identifiers (such as variables) are
    accessible by a function or a block if,
  • a. The identifier is declared before the function
    definition (block),
  • b. The function name is different from the
    identifier,
  • c. All parameters of the function have names
    different than the name of the identifier,
  • d. All local identifiers (such as local
    variables) have names different than the name of
    the identifier.
  • 2. (Nested Block) An identifier declared within a
    block is accessible
  • a. Only within the block from the point they are
    declared until the end of the block and
  • b. By those blocks that are nested within that
    block if the nested block does not have an
    identifier with the same name as that of the
    outside block (the block that encloses the nested
    block.)
  • 3. The scope of a function name is similar to the
    scope of an identifier declared outside of any
    block.

44
  • C allows the programmer to declare a variable
    in the initialization statement of the for
    statement.
  • for(int count 1 count lt 10 count)
  • coutltltcountltltendl
  • The scope of the variable count is limited to
    only the body of the for loop.

45
  • include ltiostreamgt
  • using namespace std
  • const double rate 10.50
  • int z
  • double t
  • void one(int x, char y)
  • void two(int a, int b, char x)
  • void three(int one, double y, int z)
  • int main ()
  • int num, first
  • double x, y, z
  • char name, last
  • .
  • .
  • .

46
  • void one(int x, char y)
  • .
  • .
  • .
  • int w
  • void two(int a, int b, char x)
  • int count
  • .
  • .
  • .

47
  • void three(int one, double y, int z)
  • char ch
  • int a
  • .
  • .
  • .
  • //Block four
  • int x
  • char a
  • .
  • .
  • //end Block four
  • .
  • .
  • .

48
(No Transcript)
49
  • 1. Some compilers initialize global variables to
    their default values.
  • 2. In C, is called the scope resolution
    operator. By using the scope resolution operator,
    a global variable declared before the definition
    of a function (block) can be accessed by the
    function (or block) even if the function (or
    block) has an identifier with the same name as
    the variable.
  • 3. C provides a way to access a global variable
    declared after the definition of a function. In
    this case, the function must not contain any
    identifier with the same name as the global
    variable. In the preceding example, the function
    one does not contain any identifier named w.
    Therefore, w can be accessed by function one if
    you declare w as an external variable inside one.
    To declare w as an external variable inside
    function one, the function one must contain the
    following statement
  • extern int w

50
  • SIDE EFFECTS OF GLOBAL VARIABLES
  • Using global variables has side effects.
  • Any function that uses global variables is not
    independent and usually it cannot be used in more
    than one program.
  • Also, if more than one function uses the same
    global variable and if something goes wrong, it
    is difficult to find what went wrong and where.
  • Problems caused by global variables in one area
    of a program might be misunderstood as problems
    caused in another area.
  • Use appropriate parameters instead of using
    global variables.

51
  • STATIC AND AUTOMATIC VARIABLES
  • A variable for which memory is allocated at block
    entry and deallocated at block exit is called an
    automatic variable.
  • A variable for which memory remains allocated as
    long as the program executes is called a static
    variable.
  • Variables declared outside of any block are
    static variables and by default variables
    declared within a block are automatic variables.
  • We can declare a static variable within a block
    by using the reserved word static.
  • The syntax for declaring a static variable is
  • static dataType identifier
  • The statement
  • static int x
  • declares x to be a static variable of the type
    int.
  • Static variables declared within a block are
    local to the block and their scope is the same as
    any other local identifier of that block

52
  • Example 7-9
  • //Program Static and automatic variables
  • include ltiostreamgt
  • using namespace std
  • void test()
  • int main()
  • int count
  • for(count 1 count lt 5 count)
  • test()
  • return 0

53
  • void test()
  • static int x 0
  • int y 10
  • x x 2
  • y y 1
  • coutltlt"Inside test x "ltltxltlt" and y "
  • ltlty ltltendl
  • Output
  • Inside test x 2 and y 11
  • Inside test x 4 and y 11
  • Inside test x 6 and y 11
  • Inside test x 8 and y 11
  • Inside test x 10 and y 11

54
  • FUNCTION OVERLOADING AN INTRODUCTION
  • In C, you can have several functions with the
    same name.
  • If you have several functions with the same name,
    every function must have a different set of
    parameters.
  • In C terminology, this is referred as
    overloading a function name.
  • The types of parameters determine which function
    to be executed.
  • int largerInt(int x, int y)
  • char largerChar(char first, char second)
  • double largerDouble(double u, double v)
  • string largerString(string first, string second)

55
  • Instead of giving different names to these
    functions, we can use the same name, say larger
    for each of the functions, that is, we can
    overload the function larger.
  • int larger(int x, int y)
  • char larger(char first, char second)
  • double larger(double u, double v)
  • string larger(string first, string second)
  • If the call is larger(5,3), the first function
    will be executed.
  • If the call is larger('A', '9'), the second
    function will be executed.
  • Function overloading is used when we have the
    same action for different sets of data.
  • For function overloading to work, we must give
    the definition of each of the functions.

56
  • FUNCTIONS WITH DEFAULT PARAMETERS
  • When a function is called, the number of actual
    and formal parameters must be the same.
  • C relaxes this condition for functions with
    default parameters.
  • You specify the value of a default parameter when
    the function name appears for the first time,
    such as in the prototype.

57
  • In general, the following rules apply for
    functions with default parameters
  • If you do not specify the value of a default
    parameter, the default value is used for that
    parameter.
  • All of the default parameters must be the
    rightmost parameters of the function.
  • Suppose a function has more than one default
    parameter. In a function call, if a value to a
    default parameter is not specified, then you must
    omit all of the arguments to its right.
  • Default values can be constants, global
    variables, or function calls.
  • The caller has the option of specifying a value
    other than the default for any default parameter.
  • You cannot assign a constant value as a default
    value to a reference parameter.

58
  • void funcExp(int x, int y, double t, char z
    'A',
  • int u 67, char v 'G',
  • double w 78.34)
  • int a, b
  • char ch
  • double d
  • The following function calls are legal
  • 1. funcExp(a, b, d)
  • 2. funcExp(a, 15, 34.6,'B', 87, ch)
  • 3. funcExp(b, a, 14.56,'D')
  • The following function calls are illegal
  • 1. funcExp(a, 15, 34.6, 46.7)
  • 2. funcExp(b, 25, 48.76, 'D', 4567, 78.34)

59
  • The following are illegal function prototypes
    with default parameters.
  • void funcOne(int x, double z 23.45, char ch,
  • int u 45)
  • int funcTwo(int length 1, int width,
  • int height 1)
  • void funcThree(int x, int y 16, double z
    34)

60
  • PROGRAMMING EXAMPLE CLASSIFY NUMBERS
  • In this example, using functions we rewrite the
    program that determines the number of odds and
    evens from a given list of integers. This program
    was first written in Chapter 5.
  • The main algorithm remains the same
  • 1. Initialize variables, zeros, odds, and evens
    to 0.
  • 2. Read a number.
  • 3. If the number is even, increment the even
    count, and if the number is also zero, increment
    the zero count else increment the odd count.
  • 4. Repeat Steps 2 and 3 for each number in the
    list.

61
  • To simplify the function main and further
    illustrate parameter passing, the program
    includes
  • A function, initialize, to initialize the
    variables, such as zeros, odds, and evens.
  • A function, getNumber, to get the number.
  • A function, classifyNumber, to determine whether
    the number is odd or even (and whether it is also
    zero). This function also increments the
    appropriate count.
  • A function, printResults, to print the results.

62
  • initialize
  • void initialize(int zeroCount, int oddCount,
  • int evenCount)
  • zeroCount 0
  • oddCount 0
  • evenCount 0
  • getNumber
  • void getNumber(int num)
  • cingtgtnum

63
  • classifyNumber
  • void classifyNumber(int num, int zeroCount,
  • int oddCount, int evenCount)
  • switch(num 2)
  • case 0 evenCount // update even count
  • if(num 0) // number is also zero
  • zeroCount // update zero count
  • break
  • case 1
  • case -1 oddCount // update odd count
  • //end switch

64
  • printResults
  • void printResults(int zeroCount, int oddCount,
  • int evenCount)
  • coutltlt"There are "ltltevenCountltlt" evens, "
  • ltlt"which also includes "ltltzeroCount
  • ltlt" zeros"ltltendl
  • coutltlt"Total number of odds are "
  • ltltoddCountltltendl

65
  • Main Algorithm
  • 1. Call function initialize to initialize
    variables.
  • 2. Prompt the user to enter 20 numbers.
  • 3. For each number in the list
  • a. Call function getNumber to read a number
  • b. Output the number.
  • c. Call function classifyNumber to classify the
    number and increment the appropriate count.
  • 4. Call function printResults to print the final
    results.

66
  • //Program Classify Numbers
  • //This program counts the number of zeros, odd,
    and even
  • //numbers
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • const int N 20
  • //function prototypes
  • void initialize(int zeroCount, int oddCount,
  • int evenCount)
  • void getNumber(int num)
  • void classifyNumber(int num, int zeroCount,
  • int oddCount, int
    evenCount)
  • void printResults(int zeroCount, int oddCount,
  • int evenCount)

67
  • int main ()
  • //variable declaration
  • int counter //Loop control variable
  • int number //Store the new number
  • int zeros //Store the number of zeros
  • int odds //Store the number of odd
    integers
  • int evens //Store the number of even
    integers
  • initialize(zeros, odds, evens) //Step 1
  • coutltlt"Please enter "ltltNltlt" integers."
  • ltltendl //Step 2
  • coutltlt"The numbers you entered are--gt "ltltendl

68
  • for (counter 1 counter lt N
    counter) //Step 3
  • getNumber(number) //Step 3a
  • coutltltsetw(3)ltltnumber //Step 3b
  • classifyNumber(number,zeros,odds,evens)//Step
    3c
  • // end for loop
  • coutltltendl
  • printResults(zeros,odds,evens) //Step 4
  • return 0

69
  • void initialize(int zeroCount, int oddCount,
  • int evenCount)
  • zeroCount 0
  • oddCount 0
  • evenCount 0
  • void getNumber(int num)
  • cingtgtnum

70
  • void classifyNumber(int num, int zeroCount,
  • int oddCount, int evenCount)
  • switch(num 2)
  • case 0 evenCount // update even count
  • if(num 0) // number is also zero
  • zeroCount // update zero count
  • break
  • case 1
  • case -1 oddCount // update odd count
  • //end switch

71
  • void printResults(int zeroCount, int oddCount,
  • int evenCount)
  • coutltlt"There are "ltltevenCountltlt" evens, "
  • ltlt"which also includes "ltltzeroCount
  • ltlt" zeros"ltltendl
  • coutltlt"Total number of odds are "
  • ltltoddCountltltendl
  • Sample Run
  • Please enter 20 integers.
  • The numbers you entered are--gt
  • 0 0 12 23 45 7 -2 -8 -3 -9 4 0 1 0 -7 23 -24 0 0
    12
  • 0 0 12 23 45 7 -2 -8 -3 -9 4 0 1 0 -7 23
    -24 0 0 12
  • There are 12 evens, which also includes 6 zeros
  • Total number of odds are 8
Write a Comment
User Comments (0)
About PowerShow.com