Chapter 6 Functions - PowerPoint PPT Presentation

1 / 128
About This Presentation
Title:

Chapter 6 Functions

Description:

A function call is a statement that causes a function to execute. ... Health Club Membership Menu. 1. Standard adult Membership. 2. child Membership ... – PowerPoint PPT presentation

Number of Views:24
Avg rating:3.0/5.0
Slides: 129
Provided by: mbfl8
Category:

less

Transcript and Presenter's Notes

Title: Chapter 6 Functions


1
Chapter 6 Functions
2
6.1 Focus on Software Engineering Breaking Up
Your Programs
  • Programs may be broken up into many manageable
    functions.

3
6.2 Defining and Calling Functions
  • A function call is a statement that causes a
    function to execute. A function definition
    contains the statements that make up the
    function.
  • The line in the definition that reads int main()
    is called the function header.

4
Figure 6-1
5
Calling a Function
  • Function Header
  • void displayMessage()
  • Function Call
  • displayMessage()

6
Program 6-1
  • include ltiostreamgt
  • using namespace std
  • // Definition of function displayMessage.
  • // This function displays a greeting.
  • void displayMessage()
  • cout ltlt "Hello from the function
    displayMessage.\n"
  •  
  • int main()
  • cout ltlt "Hello from main.\n"
  • displayMessage()
  • cout ltlt "Back in function main again.\n"
  • return 0

7
Program Output
  • Hello from main.
  • Hello from the function displayMessage.
  • Back in function main again.

8
Figure 6-2
void displayMessage() cout ltlt Hello from the
function displayMessage.\n
int main() cout ltlt Hello from
main.\n displayMessage() cout ltlt Back in
function main again.\n return 0
9
Program 6-2
  • //The function displayMessage is repeatedly
    called from a loop
  • include ltiostreamgt
  • using namespace std
  •  
  • void displayMessage()
  • cout ltlt "Hello from the function
    displayMessage.\n"
  •  
  • int main()
  • cout ltlt "Hello from main.\n"
  • for (int count 0 count lt 5 count)
  • displayMessage() // Call displayMessage
  • cout ltlt "Back in function main again.\n"
  • return 0

10
Program Output
  • Hello from main.
  • Hello from the function displayMessage.
  • Hello from the function displayMessage.
  • Hello from the function displayMessage.
  • Hello from the function displayMessage.
  • Hello from the function displayMessage.
  • Back in function main again.

11
Program 6-3
  • // This program has three functions main, first,
    and second.
  • include ltiostreamgt
  • using namespace std
  • // Definition of function first.
  • // This function displays a message.
  •  
  • void first()
  • cout ltlt "I am now inside the function first.\n"

12
 Program continues
  • // Definition of function second. This function
    displays a message.
  • void second()
  • cout ltlt "I am now inside the function
    second.\n"
  •  
  • int main()
  • cout ltlt "I am starting in function main.\n"
  • first() // Call function first
  • second() // Call function second
  • cout ltlt "Back in function main again.\n"return
    0

13
Program Output
  • I am starting in function main.
  • I am now inside the function first.
  • I am now inside the function second.
  • Back in function main again.

14
Figure 6-3
void first() cout ltlt I am now inside
function first.\n
void second() cout ltlt I am now inside
function second.\n
int main() cout ltlt I am starting in
function main.\n first() second()
cout ltlt Back in function main again.\n
return 0
15
Program 6-4
  • // This program has three functions main, deep,
    and deeper
  •  
  • include ltiostreamgt
  • using namespace std
  • // Definition of function deeper.
  • // This function displays a message.
  •  
  • void deeper()
  • cout ltlt "I am now inside the function
    deeper.\n"

16
 Program continues
  • // Definition of function deep.
  • // This function calls the function deeper.
  •  void deep()
  • cout ltlt "I am now inside the function deep.\n"
  • deeper() // Call function deeper
  • cout ltlt "Now I am back in deep.\n"
  •  int main()
  • cout ltlt "I am starting in function main.\n"
  • deep() // Call function deep
  • cout ltlt "Back in function main again.\n"
  • return 0

17
Program Output
  • I am starting in function main.
  • I am now inside the function deep.
  • I am now inside the function deeper.
  • Now I am back in deep.
  • Back in function main again.

18
Figure 6-4
void deep() cout ltlt I am now inside
function deep.\n deeper() cout ltlt Now I
am back in deep.\n
void deeper() cout ltlt I am now inside
function deeper.\n
int main() cout ltlt I am starting in
function main.\n deep() cout ltlt Back in
function main again.\n return 0
19
6.3 Sending Information Into a Function
  • When a function is called, the program may send
    values into the function.

20
Program 6-5
  •  include ltiostreamgt
  • using namespace std
  • // Definition of function displayValue.
  • // It uses an integer parameter whose value is
    displayed.
  • void displayValue(int num)
  • cout ltlt "The value is " ltlt num ltlt endl
  •  
  • int main()
  • cout ltlt "I am passing 5 to displayValue.\n"
  • displayValue(5) // Call displayValue with
    argument 5
  • cout ltlt "Now I am back in main.\n"
  • return 0

21
Program Output
  • I am passing 5 to displayValue.
  • The value is 5
  • Now I am back in main.

22
Figure 6-5
displayValue(5)
void displayValue(int num) cout ltlt The
value is ltlt num ltlt endl
23
Program 6-6
  • // This program demonstrates a function with a
    parameter.
  • include ltiostreamgt
  • using namespace std
  •  
  • // Definition of function displayValue.
  • // It uses an integer parameter whose value is
    displayed.
  • void displayValue(int num)
  • cout ltlt "The value is " ltlt num ltlt endl

24
Program continues
  • int main()
  • cout ltlt "I am passing several values to
    displayValue.\n"
  • displayValue(5) // Call displayValue with
    argument 5
  • displayValue(10) // Call displayValue with
    argument 10
  • displayValue(2) // Call displayValue with
    argument 2
  • displayValue(16) // Call displayValue with
    argument 16
  • cout ltlt "Now I am back in main.\n"
  • return 0

25
Program Output
  • I am passing several values to displayValue.
  • The value is 5
  • The value is 10
  • The value is 2
  • The value is 16
  • Now I am back in main.

26
Program 6-7
  • // This program demonstrates a function with
    three parameters.
  •  
  • include ltiostreamgt
  • using namespace std
  • // Definition of function showSum.
  • // It uses three integer parameters. Their sum is
    displayed.
  • void showSum(int num1, int num2, int num3)
  • cout ltlt (num1 num2 num3) ltlt endl

27
 Program continues
  • int main()
  • int value1, value2, value3
  •   cout ltlt "Enter three integers and I will
    display "
  • cout ltlt "their sum "
  • cin gtgt value1 gtgt value2 gtgt value3
  • showSum(value1, value2, value3) // Call showSum
    with // 3
    arguments
  • return 0

28
Program Output with Example Input
  • Enter three integers and I will display their
    sum 4 8 7 Enter
  • 19

29
Figure 6-6
showSum(value1, value2, value3)
void showSum(int num1, int num2, int num3)
cout ltlt num1 num2 num3 ltlt endl
30
6.4 Changing the value of a Parameter
  • When an argument is passed into a parameter, only
    a copy of the arguments value is passed.
    Changes to the parameter do not affect the
    original argument. This is called passed by
    value.

31
Program 6-8
  • // This program demonstrates that changes to a
    function parameter
  • // have no effect on the original argument.
  •  include ltiostreamgt
  •  using namespace std
  • // Definition of function changeThem.
  • // It uses i, an int parameter, and f, a float.
    The values of
  • // i and f are changed and then displayed.
  •  
  • void changeThem(int i, float f)
  • i 100
  • f 27.5
  • cout ltlt "In changeThem the value of i is changed
    to "
  • cout ltlt i ltlt endl
  • cout ltlt "and the value of f is changed to " ltlt f
    ltlt endl

32
  Program continues
  • int main()
  • int whole 12
  • float real 3.5
  •   cout ltlt "In main the value of whole is " ltlt
    whole ltlt endl
  • cout ltlt "and the value of real is " ltlt real ltlt
    endl
  • changeThem(whole, real) // Call changeThem with
    2 arguments
  • cout ltlt "Now back in main again, the value of "
  • cout ltlt "whole is " ltlt whole ltlt endl
  • cout ltlt "and the value of real is " ltlt real ltlt
    endl
  • return 0

33
Program Output
  • In main the value of whole is 12
  • and the value of real is 3.5
  • In changeThem the value of i is changed to 100
  • and the value of f is changed to 27.5
  • Now back in main again, the value of whole is 12
  • and the value of real is 3.5

34
Figure 6-7
35
6.5 Function Prototypes
  • A function prototype eliminates the need to place
    a function definition before all calls to the
    function.
  • You may optionally list the parameter variable
    names in a function prototype, although the
    compiler only needs the types.
  • You must place either the function definition or
    function prototype ahead of all calls to the
    function. Otherwise the program will not compile.

36
Program 6-9
  • // This program uses a function prototype for
    showSum
  •  
  • include ltiostreamgt
  • using namespace std
  • void showSum(int, int, int) // Function
    prototype
  •  
  • int main()
  • int value1, value2, value3
  • cout ltlt "Enter three integers and I will display
    "
  • cout ltlt "their sum "
  • cin gtgt value1 gtgt value2 gtgt value3
  • showSum(value1, value2, value3)
  • return 0

37
 Program continues
  • // Definition of function showSum.
  • // It uses three integer parameters. Their sum is
  • // displayed.
  •  
  • void showSum(int num1, int num2, int num3)
  • cout ltlt num1 num2 num3 ltlt endl
  •  

38
Program 6-10
  • // This program has three functions main, first,
    and second.
  •  
  • include ltiostreamgt
  •  using namespace std
  • // Function prototypes
  • void first()
  • void second()
  •  
  • int main()
  • cout ltlt "I am starting in function main.\n"
  • first()
  • second()
  • cout ltlt "Back in function main again.\n"
  • return 0

39
Program continues
  • // Definition of function first
  • void first()
  • cout ltlt "I am now inside the function first.\n"
  •  
  • // Definition of function second
  • void second()
  • cout ltlt "I am now inside the function
    second.\n"

40
6.6 Focus on Software Engineering Using
Functions in a Menu-Driven Program
  • Functions are ideal for use in menu-driven
    programs. When the user selects an item from a
    menu, the program can call the appropriate
    function.

41
Program 6-11
  • // This is a menu-driven program that makes a
    function call
  • // for each selection the user makes.
  • include ltiostreamgt
  • using namespace std
  • // Function Prototypes
  • void adult(int)
  • void child(int)
  • void senior(int)
  •  
  • int main()
  • int months, choice

42
 Program continues
  • cout.setf(iosfixed iosshowpoint)
  • cout.precision(2)
  •   do
  • cout ltlt "\n\t\tHealth Club Membership
    Menu\n\n"
  • cout ltlt "1. Standard adult Membership\n"
  • cout ltlt "2. child Membership\n"
  • cout ltlt "3. senior Citizen Membership\n"
  • cout ltlt "4. Quit the Program\n\n"
  • cout ltlt "Enter your choice "
  • cin gtgt choice

43
Program continues
  • if (choice ! 4)
  • cout ltlt "For how many months? "
  • cin gtgt months
  • switch (choice)
  • case 1 adult(months)
  • break
  • case 2 child(months)
  • break
  • case 3 senior(months)
  • break
  • case 4 cout ltlt "Thanks for using this "
  • cout ltlt "program.\n"
  • break

44
Program continues
  • default cout ltlt "The valid choices are 1-4. "
  • cout ltlt "Try again.\n"
  • while (choice ! 4)
  • return 0
  •  
  • // Definition of function adult. Uses an integer
    parameter, mon.
  • // mon holds the number of months the membership
    should be
  • // calculated for. The cost of an adult
    membership for that many
  • // months is displayed.
  • void adult(int mon)
  • cout ltlt "The total charges are "
  • cout ltlt (mon 40.0) ltlt endl

45
 Program continues
  • // Definition of function child. Uses an integer
    parameter, mon.
  • // mon holds the number of months the membership
    should be
  • // calculated for. The cost of a child membership
    for that many
  • // months is displayed.
  •  
  • void child(int mon)
  • cout ltlt "The total charges are "
  • cout ltlt (mon 20.0) ltlt endl

46
 Program continues
  • // Definition of function senior. Uses an integer
    parameter, mon.
  • // mon holds the number of months the membership
    should be
  • // calculated for. The cost of a senior citizen
    membership for
  • // that many months is displayed.
  •  
  • void senior(int mon)
  • cout ltlt "The total charges are "
  • cout ltlt (mon 30.0) ltlt endl

47
Program Output with Example Input
  • Health Club Membership Menu
  •  
  • 1. Standard adult Membership
  • 2. child Membership
  • 3. senior Citizen Membership
  • 4. Quit the Program
  • Enter your choice 1
  •  
  • For how many months 12
  • The total charges are 480.00
  •  
  • Health Club Membership Menu
  •  
  • 1. Standard adult Membership
  • 2. child Membership
  • 3. senior Citizen Membership
  • 4. Quit the Program
  • Enter your choice 4
  • Thanks for using this program.

48
6.7 Local and Global Variables
  • A local variable is declared inside a function,
    and is not accessible outside the function.
  • A global variable is declared outside all
    functions and is accessible in its scope.

49
Program 6-12
  • // This program shows that variables declared in
    a function
  • // are hidden from other functions.
  • include ltiostreamgt
  • using namespace std
  • void func() // Function prototype
  •  
  • int main()
  • int num 1
  • cout ltlt "In main, num is " ltlt num ltlt endl
  • func()
  • cout ltlt "Back in main, num is still " ltlt num ltlt
    endl
  • return 0

50
 Program continues
  • // Definition of function func.
  • // It has a local variable, num, whose initial
    value, 20,
  • // is displayed.
  •  
  • void func()
  • int num 20
  •   cout ltlt "In func, num is " ltlt num ltlt endl
  •  

51
Program Output
  • In main, num is 1
  • In func, num is 20
  • Back in main, num is still 1

52
Figure 6-8
Function main num 1
This num variable is only visible in function
main.
Function func num 20
This num variable is only visible in function
func.
53
Program 6-13
  • // This program shows that a global variable is
    visible
  • // to all the functions that appear in a program
    after
  • // the variable's declaration.
  •  
  • include ltiostreamgt
  • using namespace std
  • void func() // Function prototype
  • int num 2 // Global variable
  •  
  • int main()
  • cout ltlt "In main, num is " ltlt num ltlt endl
  • func()
  • cout ltlt "Back in main, num is " ltlt num ltlt endl
  • return 0

54
 Program continues
  • // Definition of function func.
  • // func changes the value of the global variable
    num.
  • void func()
  • cout ltlt "In func, num is " ltlt num ltlt endl
  • num 50
  • cout ltlt "But, it is now changed to " ltlt num ltlt
    endl
  •  

55
Program Output
  • In main, num is 2
  • In func, num is 2
  • But, it is now changed to 50
  • Back in main, num is 50

56
Program 6-14
  • // This program shows that a global variable is
    visible
  • // to all the functions that appear in a program
    after
  • // the variable's declaration.
  • include ltiostreamgt
  • using namespace std 
  • void func() // Function prototype
  •  
  • int main()
  • cout ltlt "In main, num is not visible!\n"
  • func()
  • cout ltlt "Back in main, num still isn't
    visible!\n"
  • return 0

57
 Program continues
  • int num 2 // Global variable
  • // Definition of function func
  • // func changes the value of the global variable
    num.
  • void func()
  • cout ltlt "In func, num is " ltlt num ltlt endl
  • num 50
  • cout ltlt "But, it is now changed to " ltlt num ltlt
    endl

58
Program Output
  • In main, num is not visible!
  • In func, num is 2
  • But, it is now changed to 50
  • Back in main, num still isn't visible!

59
Program 6-15
  • // This program has an uninitialized global
    variable.
  • include ltiostreamgt
  • using namespace std
  • int globalNum // Global variable. Automatically
    set to zero.
  •  
  • int main()
  • cout ltlt "globalNum is " ltlt globalNum ltlt endl
  • return 0

60
Program Output
  • globalNum is 0

61
Local and Global Variables with the Same Name
  • If a function has a local variable with the same
    name as a global variable, only the local
    variable can be seen by the function.

62
Program 6-16
  • // This program shows that when a local variable
    has the
  • // same name as a global variable, the function
    only sees
  • // the local variable.
  •  
  • include ltiostreamgt
  • using namespace std
  • // Function prototypes
  • void texas()
  • void arkansas()
  •  
  • int cows 10

63
 Program continues
  • int main()
  • cout ltlt "There are " ltlt cows ltlt " cows in
    main.\n"
  • texas()
  • arkansas()
  • cout ltlt "Back in main, there are " ltlt cows ltlt "
    cows.\n"
  • return 0
  •  
  • // Definition of function texas.
  • // The local variable cows is set to 100.
  •  void texas()
  • int cows 100
  •  
  • cout ltlt "There are " ltlt cows ltlt " cows in
    texas.\n"

64
 Program continues
  • // Definition of function arkansas.
  • // The local variable cows is set to 50.
  •  
  • void arkansas()
  • int cows 50
  •   cout ltlt "There are " ltlt cows ltlt " cows in
    arkansas.\n"
  •  

65
Program Output
  • There are 10 cows in main.
  • There are 100 cows in texas.
  • There are 50 cows in arkansas.
  • Back in main, there are 10 cows.
  •  

66
Program 6-17
  • // This program has local and global variables.
    In the function
  • // ringUpSale, there is a local variable named
    tax. There is
  • // also a global variable with the same name.
  • include ltiostreamgt
  • using namespace std 
  • void ringUpSale() // Function prototype
  •  
  • // Global Variables
  • const float taxRate 0.06
  • float tax, sale, total
  •  
  • int main()
  • char again

67
 Program continues
  • cout.precision(2)
  • cout.setf(iosfixed iosshowpoint)
  • do
  • ringUpSale()
  • cout ltlt "Is there another item to be purchased?
    "
  • cin gtgt again
  • while (again 'y' again 'Y')
  • tax sale taxRate
  • total sale tax
  • cout ltlt "The tax for this sale is " ltlt tax ltlt
    endl
  • cout ltlt "The total is " ltlt total ltlt endl
  • return 0

68
 Program continues
  • // Definition of function ringUpSale.
  • // This function asks for the quantity and unit
    price of an item.
  • // It then calculates and displays the sales tax
    and subtotal
  • // for those items.
  •  
  • void ringUpSale()
  • int qty
  • float unitPrice, tax, thisSale, subTotal
  •  
  • cout ltlt "Quantity "
  • cin gtgt qty
  • cout ltlt "Unit price "
  • cin gtgt unitPrice
  • thisSale qty unitPrice // Get the total
    unit price

69
Program continues
  • sale thisSale // Update global
    variable sale
  • tax thisSale taxRate // Get sales tax for
    these items
  • subTotal thisSale tax // Get subtotal for
    these items
  • cout ltlt "Price for these items " ltlt thisSale ltlt
    endl
  • cout ltlt "tax for these items " ltlt tax ltlt endl
  • cout ltlt "subTotal for these items " ltlt subTotal
    ltlt endl

70
Program Output with Example Input
  • Quantity 2 Enter
  • Unit Price 20.00 Enter
  • Price for these items 40.00
  • tax for these items 2.40
  • subTotal for these items 42.40
  • Is there another item to be purchased? y Enter
  • Quantity 3 Enter
  • Unit Price 12.00 Enter
  • Price for these items 36.00
  • tax for these items 2.16
  • subTotal for these items 38.16
  • Is there another item to be purchased? n Enter
  • The tax for this sale is 4.56
  • The total is 80.56

71
Be Careful With Global Variables
  • It is tempting to make all your variables global.
    But dont do it!
  • Using global variables can cause problems.
  • It is harder to debug a program that uses global
    variables

72
6.8 Static Local Variables
  • If a function is called more than once in a
    program, the values stored in the functions
    local variables do not persist between function
    calls.
  • To get a variable to keep its value even after
    the function ends, you must create static
    variables

73
Program 6-18
  • // This program shows that local variables do not
    retain
  • // their values between function calls.
  •  
  • include ltiostreamgt
  • using namespace std
  • // Function prototype
  • void showLocal()
  •  
  • int main()
  • showLocal()
  • showLocal()
  • return 0

74
Program continues
  • // Definition of function showLocal.
  • // The initial value of localNum, which is 5, is
    displayed.
  • // The value of localNum is then changed to 99
    before the
  • // function returns.
  •  
  • void showLocal()
  • int localNum 5 // Local variable
  •  
  • cout ltlt "localNum is " ltlt localNum ltlt endl
  • localNum 99

75
Program Output
  • localNum is 5
  • localNum is 5

76
Program 6-19
  • //This program uses a static local variable.
  • include ltiostreamgt
  • void showStatic() // Function prototype
  • int main()
  • for (int count 0 count lt 5 count)
  • showStatic()
  • return 0
  • // Definition of function showStatic.
  • void showStatic()
  • static int statNum
  • cout ltlt "statNum is " ltlt statNum ltlt endl
  • statNum

77
Program Output
  • statNum is 0
  • statNum is 1
  • statNum is 2
  • statNum is 3
  • statNum is 4

78
Program 6-20
  • // This program shows that a static local
    variable is only
  • // initialized once.
  • include ltiostreamgt
  • using namespace std
  • void showStatic() // Function prototype
  • int main()
  • for (int count 0 count lt 5 count)
  • showStatic()return 0

79
 Program continues
  • // Definition of function showStatic.
  • // statNum is a static local variable. Its value
    is displayed
  • // and then incremented just before the function
    returns.
  •  
  • void showStatic()
  • static int statNum 5
  •  
  • cout ltlt "statNum is " ltlt statNum ltlt endl
  • statNum

80
Program Output
  • statNum is 5
  • statNum is 6
  • statNum is 7
  • statNum is 8
  • statNum is 9

81
6.9 Default Arguments
  • Default arguments are passed to parameters
    automatically if no argument is provided in the
    function call.
  • A functions default arguments should be assigned
    in the earliest occurrence of the function name.
    This will usually mean the function prototype.

82
Program 6-21
  • // This program demonstrates default function
    arguments.
  • include ltiostreamgt
  • using namespace std
  • // Function prototype with default arguments
  • void displayStars(int 10, int 1)
  •  
  • int main()
  • displayStars()
  • cout ltlt endl
  • displayStars(5)
  • cout ltlt endl
  • displayStars(7, 3)
  • return 0

83
 Program continues
  • // Definition of function displayStars.
  • // The default argument for cols is 10 and for
    rows is 1.
  • // This function displays a rectangle made of
    asterisks.
  • void displayStars(int cols, int rows)
  • // Nested loop. The outer loop controls the rows
  • // and the inner loop controls the columns.
  • for (int down 0 down lt rows down)
  • for (int across 0 across lt cols across)
  • cout ltlt ""
  • cout ltlt endl
  •  

84
Program Output
  •  
  •  

85
Default Argument Summary
  • The value of a default argument must be a
    constant (either a literal value of a named
    constant).
  • When an argument is left out of a function call
    (because it has a default value), all the
    arguments that come after it must be left out
    too.
  • When a function has a mixture of parameters both
    with and without default arguments, the
    parameters with default arguments must be
    declared last.

86
6.10 Using Reference Variables as Parameters
  • When used as parameters, reference variables
    allow a function to access the parameters
    original argument, changes to the parameter are
    also made to the argument.

87
Example
  • void doubleNum(int refVar)
  • refVar 2
  • // The variable refVar is called
  • // a reference to an int

88
Program 6-22
  • // This program uses a reference variable as a
    function
  • // parameter.
  • include ltiostreamgt
  • // Function prototype. The parameter is a
    reference variable.
  • void doubleNum(int )
  •  
  • int main()
  • int value 4
  •   cout ltlt "In main, value is " ltlt value ltlt endl
  • cout ltlt "Now calling doubleNum..." ltlt endl
  • doubleNum(value)
  • cout ltlt "Now back in main. value is " ltlt value
    ltlt endl
  • return 0

89
 Program continues
  • // Definition of doubleNum.
  • // The parameter refVar is a reference variable.
    The value
  • // in refVar is doubled.
  •  
  • void doubleNum (int refVar)
  • refVar 2
  •  

90
Program Output
  • In main, value is 4
  • Now calling doubleNum...
  • Now back in main. value is 8

91
Program 6-23
  • // This program uses reference variables as
    function
  • // parameters.
  • include ltiostreamgt
  • // Function prototypes. Both functions use
    reference variables
  • // as parameters
  • void doubleNum(int )
  • void getNum(int )
  •  
  • int main()
  • int value
  • getNum(value)
  • doubleNum(value)
  • cout ltlt "That value doubled is " ltlt value ltlt
    endl
  • return 0

92
 Program continues
  • // Definition of getNum.
  • // The parameter userNum is a reference variable.
    The user is
  • // asked to enter a number, which is stored in
    userNum.
  •  
  • void getNum(int userNum)
  • cout ltlt "Enter a number "
  • cin gtgt userNum

93
 Program continues
  • // Definition of doubleNum.
  • // The parameter refVar is a reference variable.
    The value
  • // in refVar is doubled.
  •  
  • void doubleNum (int refVar)
  • refVar 2

94
Program Output with Example Input
  • Enter a number 12 Enter
  • That value doubled is 24
  •  

95
Reference Argument Warning
  • Dont get carried away with using reference
    variables as function parameters. Any time you
    allow a function to alter a variable thats
    outside the function, you are creating potential
    debugging problems. Reference variables should
    only be used as parameters when the situation
    demands them.

96
6.11 The return Statement
  • The return statement causes a function to end.

97
Program 6-24
  • // This program demonstrates a function with a
    return statement.
  • include ltiostreamgt
  • using namespace std 
  • // Function prototype
  • void halfway()
  •  
  • int main()
  • cout ltlt "In main, calling halfway...\n"
  • halfway()
  • cout ltlt "Now back in main.\n"
  • return 0

98
 Program continues
  • // Definition of function halfway.
  • // This function has a return statement that
    forces it to
  • // terminate before the last statement is
    executed.
  •  
  • void halfway()
  • cout ltlt "In halfway now.\n"
  • return
  • cout ltlt"Will you ever see this message?\n"

99
Program Output
  • In main, calling halfway...
  • In halfway now.
  • Now back in main.

100
Program 6-25
  • // This program uses a function to perform
    division. If division
  • // by zero is detected, the function returns.
  • include ltiostreamgt
  • using namespace std
  • // Function prototype.
  • void divide(float, float)
  •  
  • int main()
  • float num1, num2
  •  
  • cout ltlt "Enter two numbers and I will divide the
    first\n"
  • cout ltlt "number by the second number "
  • cin gtgt num1 gtgt num2
  • divide(num1, num2)
  • return 0

101
 Program continues
  • // Definition of function divide.
  • // Uses two parameters arg1 and arg2. The
    function divides arg1
  • // by arg2 and shows the result. If arg2 is zero,
    however, the
  • // function returns.
  •  
  • void divide(float arg1, float arg2)
  • if (arg2 0.0)
  • cout ltlt "Sorry, I cannot divide by zero.\n"
  • return
  • cout ltlt "The quotient is " ltlt (arg1 / arg2) ltlt
    endl

102
Program Output with Example Input
  • Enter two numbers and I will divide the first
  • number by the second number 12 0 Enter
  • Sorry, I cannot divide by zero.

103
6.12 Returning a value From a Function
  • A function may send a value back to the part of
    the program that called the function.

104
Figure 6-10
105
Program 6-26
  • // This program uses a function that returns a
    value.
  • include ltiostreamgt
  • using namespace std 
  • //Function prototype
  • int square(int)
  • int main()
  • int value, result
  • cout ltlt "Enter a number and I will square it "
  • cin gtgt value
  • result square(value)
  • cout ltlt value ltlt " squared is " ltlt result ltlt
    endl
  • return 0

106
 Program continues
  • // Definition of function square.
  • // This function accepts an int argument and
    returns
  • // the square of the argument as an int.
  •  
  • int square(int number)
  • return number number

107
Program Output with Example Input
  • Enter a number and I will square it 20 Enter
  • 20 squared is 400

108
Figure 6-11
result square(value)
20
int square(int number) return number
number
109
6.13 Returning Boolean Values
  • Function may return true or false values.

110
Program 6-28
  • // This program uses a function that returns true
    or false.
  • include ltiostreamgt
  • using namespace std
  • // Function prototype
  • bool isEven(int)
  • int main()
  • int val
  •  
  • cout ltlt "Enter an integer and I will tell you "
  • cout ltlt "if it is even or odd "
  • cin gtgt val
  • if (isEven(val))
  • cout ltlt val ltlt " is even.\n"
  • else
  • cout ltlt val ltlt " is odd.\n"
  • return 0

111
 Program continues
  • // Definition of function isEven. This function
    accepts an
  • // integer argument and tests it to be even or
    odd. The function
  • // returns true if the argument is even or false
    if the argument is odd.
  • // The return value is bool.
  •  
  • bool isEven(int number)
  • if (number 2)
  • return false // The number is odd if there's a
    remainder.
  • else
  • return true // Otherwise, the number is even.

112
Program Output
  • Enter an integer and I will tell you if it is
    even or odd 5 Enter
  • 5 is odd.
  •  

113
6.14 Overloaded Functions
  • Two or more functions may have the same name as
    long as their parameter lists are different.

114
Program 6-29
  • include ltiostreamgt
  • using namespace std
  • // Function prototypes
  • int square(int)
  • float square(float)
  • int main()
  • int userInt
  • float userFloat
  •  
  • cout.precision(2)
  • cout ltlt "Enter an integer and a floating-point
    value "
  • cin gtgt userInt gtgt userFloat
  • cout ltlt "Here are their squares "
  • cout ltlt square(userInt) ltlt " and " ltlt
    square(userFloat)
  • return 0

115
Program continues 
  • // Definition of overloaded function square.
  • // This function uses an int parameter, number.
    It returns the
  • // square of number as an int.
  • int square(int number)
  • return number number
  • // Definition of overloaded function square.
  • // This function uses a float parameter, number.
    It returns the
  • // square of number as a float.
  • float square(float number)
  • return number number

116
Program Output with Example Input
  • Enter an integer and floating-point value 12 4.2
    Enter
  • Here are their squares 144 and 17.64

117
6.15 The exit() Function
  • The exit() function causes a program to
    terminate, regardless of which function or
    control mechanism is executing.

118
Program 6-31
  • // This program shows how the exit function
    causes a program
  • // to stop executing.
  •  
  • include ltiostreamgt
  • include ltcstdlibgt // For exit
  • using namespace std
  • void function() // Function prototype
  •  
  • int main()
  • function()
  • return 0

119
 Program continues
  • // This function simply demonstrates that exit
    can be used
  • // to terminate a program from a function other
    than main.
  • void function()
  • cout ltlt "This program terminates with the exit
    function.\n"
  • cout ltlt "Bye!\n"
  • exit(0)
  • cout ltlt "This message will never be
    displayed\n"
  • cout ltlt "because the program has already
    terminated.\n"

120
Program Output
  • This program terminates with the exit function.
  • Bye!

121
Program 6-32
  • // This program demonstrates the exit function.
  • include ltiostreamgt
  • include ltcstdlibgt // For exit
  • include ltcctypegt // For toupper
  • using namespace std 
  • int main()
  • char response
  •  
  • cout ltlt "This program terminates with the exit
    function.\n"
  • cout ltlt "Enter S to terminate with the
    EXIT_SUCCESS code\n"
  • cout ltlt "or f to terminate with the EXIT_FAILURE
    code "
  • cin gtgt response

122
 Program continues
  • if (toupper(response) 'S')
  • cout ltlt "Exiting with EXIT_SUCCESS.\n"
  • exit(EXIT_SUCCESS)
  • else
  • cout ltlt "Exiting with EXIT_FAILURE.\n"
  • exit(EXIT_FAILURE)
  • return 0

123
Program Output with Example Input
  • This program terminates with the exit function.
  • Enter S to terminate with the EXIT_SUCCESS code
  • or f to terminate with the EXIT_FAILURE code s
    Enter
  • Exiting with EXIT_SUCCESS.
  • Program Output With Other Example Input
  • This program terminates with the exit function.
  • Enter S to terminate with the EXIT_SUCCESS code
  • or f to terminate with the EXIT_FAILURE code f
    Enter
  • Exiting with EXIT_FAILURE.

124
6.16 Focus on Software Engineering Multi-File
Programs
  • Large programs may be broken into several files.
    The files are compiled separately and linked into
    one executable.

125
Strategy for Creating a Multi-File Program
  • Group all specialized functions that perform
    similar tasks into the same files. For example,
    a file might be created for functions that
    perform mathematical operations. Another file
    might contain functions for user input and
    output.
  • Group function main and all functions that play a
    primary role into one file.
  • Create a separate header file for each file that
    contains function definitions. The header files
    contain prototypes for each function.

126
Figure 6-12
File 1 bank.cpp
File 3 loans.cpp
Contains main and all primary functions.
Contains all functions for processing loans.
File 2 bank.h
File 4 loans.h
Contains prototypes for functions in bank.cpp
Contains prototypes for functions in loans.cpp
File 5 savings.cpp
File 7 checking.cpp
Contains all functions for processing savings
accounts.
Contains all functions for processing checking
accounts.
File 6 savings.h
File 8 checking.h
Contains prototypes for functions in savings.cpp
Contains prototypes for functions in checking.cpp
127
6.17 Stubs and Drivers
  • Stubs and drivers are very helpful tools for
    testing and debugging programs that use
    functions.
  • A stub is a dummy function that is called instead
    of the actual function it represents.
  • A driver is a program that tests a function by
    simply calling it.

128
  • // Stub for the adult function.
  • void adult(int months)
  • cout ltlt "The function adult was called with " ltlt
    months
  • cout ltlt " as its argument.\n"
  • // Stub for the child function.
  • void child(int months)
  • cout ltlt "The function child was called with " ltlt
    months
  • cout ltlt " as its argument.\n"
  • // Stub for the senior function.
  • void senior(int months)
  • cout ltlt "The function senior was called with "
    ltlt months
  • cout ltlt " as its argument.\n"
Write a Comment
User Comments (0)
About PowerShow.com