Presentation is loading. Please wait.

Presentation is loading. Please wait.

Starting Out with C++, 3 rd Edition 1 Chapter 6 Functions.

Similar presentations


Presentation on theme: "Starting Out with C++, 3 rd Edition 1 Chapter 6 Functions."— Presentation transcript:

1 Starting Out with C++, 3 rd Edition 1 Chapter 6 Functions

2 Starting Out with C++, 3 rd Edition 2 6.1 Focus on Software Engineering: Breaking Up Your Programs Programs may be broken up into many manageable functions.

3 Starting Out with C++, 3 rd Edition 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 void main(void) is called the function header.

4 Starting Out with C++, 3 rd Edition 4 Figure 6-1 void main(void) { cout << “Hello World\n”; } Return Type Name Parameter List (This one is empty) Body

5 Starting Out with C++, 3 rd Edition 5 Calling a Function Function Header void displayMessage() Function Call displayMessage();

6 Starting Out with C++, 3 rd Edition 6 Program 6-1 #include //****************************************** // Definition of function displayMessage. * // This function displays a greeting. * //****************************************** void displayMessage() { cout << "Hello from the function displayMessage.\n"; } void main(void) { cout << "Hello from main.\n"; displayMessage(); cout << "Back in function main again.\n"; }

7 Starting Out with C++, 3 rd Edition 7 Program Output Hello from main. Hello from the function displayMessage. Back in function main again.

8 Starting Out with C++, 3 rd Edition 8 Figure 6-2 void main(void) { cout << “Hello from main.\n”; displayMessage(); cout << “Back in function main again.\n”; } void displayMessage() { cout << “Hello from the function displayMessage.\n”; }

9 Starting Out with C++, 3 rd Edition 9 Program 6-2 //The function displayMessage is repeatedly called from a loop #include //****************************************** // Definition of function displayMessage. * // This function displays a greeting. * //****************************************** void displayMessage() { cout << "Hello from the function displayMessage.\n"; } void main(void) { cout << "Hello from main.\n"; for (int count = 0; count < 5; count++) displayMessage();// Call displayMessage cout << "Back in function main again.\n"; }

10 Starting Out with C++, 3 rd Edition 10 Program Output Hello from main. Hello from the function displayMessage. Back in function main again.

11 Starting Out with C++, 3 rd Edition 11 Program 6-3 // This program has three functions: main, first, and second. #include //************************************* // Definition of function first. * // This function displays a message. * //************************************* void first(void) { cout << "I am now inside the function first.\n"; }

12 Starting Out with C++, 3 rd Edition 12 Program continues //************************************* // Definition of function second. * // This function displays a message. * //************************************* void second(void) { cout << "I am now inside the function second.\n"; } void main(void) { cout << "I am starting in function main.\n"; first();// Call function first second();// Call function second cout << "Back in function main again.\n"; }

13 Starting Out with C++, 3 rd Edition 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 Starting Out with C++, 3 rd Edition 14 Figure 6-3 void first(void) { cout << “I am now inside function first.\n”; } void second(void) { cout << “I am now inside function second.\n”; } void main(void) { cout << “I am starting in function main.\n”; first(); second(); cout << “Back in function main again.\n” }

15 Starting Out with C++, 3 rd Edition 15 Program 6-4 // This program has three functions: main, deep, and deeper #include //************************************** // Definition of function deeper. * // This function displays a message. * //************************************** void deeper(void) { cout << "I am now inside the function deeper.\n"; }

16 Starting Out with C++, 3 rd Edition 16 Program continues //************************************** // Definition of function deep. * // This function displays a message. * //************************************** void deep() { cout << "I am now inside the function deep.\n"; deeper();// Call function deeper cout << "Now I am back in deep.\n"; } void main(void) { cout << "I am starting in function main.\n"; deep();// Call function deep cout << "Back in function main again.\n"; }

17 Starting Out with C++, 3 rd Edition 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 Starting Out with C++, 3 rd Edition 18 Figure 6-4 void deep(void) { cout << “I am now inside function deep.\n”; deeper(); cout << “Now I am back in deep.\n”; } void deeper(void) { cout << “I am now inside function deeper.\n”; } void main(void) { cout << “I am starting in function main.\n”; deep(); cout << “Back in function main again.\n” }

19 Starting Out with C++, 3 rd Edition 19 6.3 Function Prototypes A function prototype eliminates the need to place a function definition before all calls to the function. Here is a prototype for the displayMessage function in Program 6-1 void displayMessage(void);

20 Starting Out with C++, 3 rd Edition 20 Program 6-5 // This program has three functions: main, first, and second. #include // Function Prototypes void first(void); void second(void); void main(void) { cout << "I am starting in function main.\n"; first(); // Call function first second(); // Call function second cout << “Back in function main again.\n"; } Program Continues on next slide

21 Starting Out with C++, 3 rd Edition 21 Program 6-5 Continues // Definition of function first. // This function displays a message. void first(void) { cout << “I am now inside the function first.\n”; } // Definition of function second // This function displays a message. void second(void) { cout << “I am now inside the function second.\n”; }

22 Starting Out with C++, 3 rd Edition 22 Program 6-5 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.

23 Starting Out with C++, 3 rd Edition 23 6.4 Sending Information Into a Function When a function is called, the program may send values (arguments) into the function. Arguments are passed into parameters. void displayValue(int num) { cout << “The value is “ << num << endl; }

24 Starting Out with C++, 3 rd Edition 24 Program 6-6 // This program demonstrates a function with a parameter. #include // Function Prototype void displayValue(int) void main(void) { cout << "I am passing 5 to displayValue.\n"; displayValue(5);//Call displayValue with argument 5 cout << "Now I am back in main.\n"; } Program Continues to next slide

25 Starting Out with C++, 3 rd Edition 25 Program 6-6 //********************************************* // Definition of function displayValue. * // It uses an integer parameter whose value is displayed. * //********************************************* void displayValue(int num) { cout << “The value is “ << num << endl; }

26 Starting Out with C++, 3 rd Edition 26 Program Output I am passing 5 to displayValue. The value is 5 Now I am back in main.

27 Starting Out with C++, 3 rd Edition 27 Figure 6-5 displayValue(5); void displayValue(int num) { cout << “The value is “ << num << endl; }

28 Starting Out with C++, 3 rd Edition 28 Program 6-7 // This program demonstrates a function with a parameter. #include // Function Prototype void displayValue(int); void main(void) { cout << "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 << "Now I am back in main.\n"; } Program continues on next slide

29 Starting Out with C++, 3 rd Edition 29 Program 6-7 Continued //********************************************************* // Definition of function displayValue. * // It uses an integer parameter whose value is displayed. * //********************************************************* void displayValue(int num) { cout << "The value is " << num << endl; }

30 Starting Out with C++, 3 rd Edition 30 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.

31 Starting Out with C++, 3 rd Edition 31 Program 6-8 // This program demonstrates a function with three parameters. #include // Function prototype void showSum(int, int, int); void main(void) { int value1, value2, value3; cout << "Enter three integers and I will display "; cout << "their sum: "; cin >> value1 >> value2 >> value3; showSum(value1, value2, value3); // Call showSum with // 3 arguments }

32 Starting Out with C++, 3 rd Edition 32 Program continues //************************************************************ // Definition of function showSum. * // It uses three integer parameters. Their sum is displayed. * //************************************************************ void showSum(int num1, int num2, int num3) { cout << (num1 + num2 + num3) << endl; }

33 Starting Out with C++, 3 rd Edition 33 Program Output with Example Input Enter three integers and I will display their sum: 4 8 7 [Enter] 19

34 Starting Out with C++, 3 rd Edition 34 Figure 6-6 showSum(value1, value2, value3); void showSum(int num1, int num2, int num3) { cout << num1 + num2 + num3 << endl; }

35 Starting Out with C++, 3 rd Edition 35 6.5 Changing the value of a Parameter When an argument is passed into a parameter, only a copy of the argument’s value is passed. Changes to the parameter do not affect the original argument. This is called “passed by value.”

36 Starting Out with C++, 3 rd Edition 36 Program 6-9 // This program demonstrates that changes to a function parameter // have no effect on the original argument. #include // Function Prototype void changeThem(int, float); void main(void) { int whole = 12; float real = 3.5; cout << "In main the value of whole is " << whole << endl; cout << "and the value of real is " << real << endl; changeThem(whole, real);// Call changeThem with 2 arguments cout << "Now back in main again, the value of "; cout << "whole is " << whole << endl; cout << "and the value of real is " << real << endl; }

37 Starting Out with C++, 3 rd Edition 37 Program continues //************************************************************** // 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 << "In changeThem the value of i is changed to "; cout << i << endl; cout << "and the value of f is changed to " << f << endl; }

38 Starting Out with C++, 3 rd Edition 38 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

39 Starting Out with C++, 3 rd Edition 39 Figure 6-7

40 Starting Out with C++, 3 rd Edition 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 Starting Out with C++, 3 rd Edition 41 Program 6-10 // This is a menu-driven program that makes a function call // for each selection the user makes. #include // Function Prototypes void adult(int); void child(int); void senior(int); void main(void) { int choice, months;

42 Starting Out with C++, 3 rd Edition 42 Program continues cout.setf(ios::fixed | ios::showpoint); cout.precision(2); do { cout << "\n\t\tHealth Club Membership Menu\n\n"; cout << "1. Standard adult Membership\n"; cout << "2. child Membership\n"; cout << "3. senior Citizen Membership\n"; cout << "4. Quit the Program\n\n"; cout << "Enter your choice: "; cin >> choice;

43 Starting Out with C++, 3 rd Edition 43 Program continues if (choice != 4) {cout << "For how many months? "; cin >> months; } switch (choice) {case 1: adult(months); break; case 2: child(months); break; case 3: senior(months); break; case 4: cout << "Thanks for using this "; cout << "program.\n"; break;

44 Starting Out with C++, 3 rd Edition 44 Program continues default: cout << "The valid choices are 1-4. "; cout << "Try again.\n"; } } while (choice != 4); } //*********************************************************** // 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 << "The total charges are $"; cout << (mon * 40.0) << endl; }

45 Starting Out with C++, 3 rd Edition 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 << "The total charges are $"; cout << (mon * 20.0) << endl; }

46 Starting Out with C++, 3 rd Edition 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 << "The total charges are $"; cout << (mon * 30.0) << endl; }

47 Starting Out with C++, 3 rd Edition 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 Starting Out with C++, 3 rd Edition 48 6.7 The return Statement The return statement causes a function to end immediately.

49 Starting Out with C++, 3 rd Edition 49 Program 6-11 // This program demonstrates a function with a return statement. #include // Function prototype void halfway(void); void main(void) { cout << "In main, calling halfway...\n"; halfway(); cout << "Now back in main.\n"; }

50 Starting Out with C++, 3 rd Edition 50 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(void) { cout << "In halfway now.\n"; return; cout <<"Will you ever see this message?\n"; }

51 Starting Out with C++, 3 rd Edition 51 Program Output In main, calling halfway... In halfway now. Now back in main.

52 Starting Out with C++, 3 rd Edition 52 Program 6-12 // This program uses a function to perform division. If division // by zero is detected, the function returns. #include // Function prototype. void divide(float, float); void main(void) { float num1, num2; cout << "Enter two numbers and I will divide the first\n"; cout << "number by the second number: "; cin >> num1 >> num2; divide(num1, num2); }

53 Starting Out with C++, 3 rd Edition 53 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 << "Sorry, I cannot divide by zero.\n"; return; } cout << "The quotient is " << (arg1 / arg2) << endl; }

54 Starting Out with C++, 3 rd Edition 54 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.

55 Starting Out with C++, 3 rd Edition 55 6.8 Returning a value From a Function A function may send a value back to the part of the program that called the function.

56 Starting Out with C++, 3 rd Edition 56 Figure 6-10

57 Starting Out with C++, 3 rd Edition 57 Program 6-13 // This program uses a function that returns a value. #include //Function prototype int square(int); void main(void) { int value, result; cout << "Enter a number and I will square it: "; cin >> value; result = square(value); cout << value << " squared is " << result << endl; }

58 Starting Out with C++, 3 rd Edition 58 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; }

59 Starting Out with C++, 3 rd Edition 59 Program Output with Example Input Enter a number and I will square it: 20 [Enter] 20 squared is 400

60 Starting Out with C++, 3 rd Edition 60 Figure 6-11 result = square(value); int square(int number) { return number * number; } 20

61 Starting Out with C++, 3 rd Edition 61 6.9 Returning Boolean Values Function may return true or false values.

62 Starting Out with C++, 3 rd Edition 62 Program 6-15 // This program uses a function that returns true or false. #include // Function prototype bool isEven(int); void main(void) { int val; cout << "Enter an integer and I will tell you "; cout << "if it is even or odd: "; cin >> val; if (isEven(val)) cout << val << " is even.\n"; else cout << val << " is odd.\n"; }

63 Starting Out with C++, 3 rd Edition 63 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) { bool status; if (number % 2) status = false; // The number is odd if there's a remainder. else status = true; // Otherwise, the number is even. return status; }

64 Starting Out with C++, 3 rd Edition 64 Program Output Enter an integer and I will tell you if it is even or odd: 5 [Enter] 5 is odd.

65 Starting Out with C++, 3 rd Edition 65 6.10 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.

66 Starting Out with C++, 3 rd Edition 66 Program 6-16 // This program shows that variables declared in a function // are hidden from other functions. #include void func(void); // Function prototype void main(void) { int num = 1; cout << "In main, num is " << num << endl; func(); cout << "Back in main, num is still " << num << endl; }

67 Starting Out with C++, 3 rd Edition 67 Program continues //********************************************************* // Definition of function func. * // It has a local variable, num, whose initial value, 20, * // is displayed. * //********************************************************* void func(void) { int num = 20; cout << "In func, num is " << num << endl; }

68 Starting Out with C++, 3 rd Edition 68 Program Output In main, num is 1 In func, num is 20 Back in main, num is still 1

69 Starting Out with C++, 3 rd Edition 69 Figure 6-8 Function main num = 1 Function func num = 20 This num variable is only visible in function main. This num variable is only visible in function func.

70 Starting Out with C++, 3 rd Edition 70 Program 6-17 // This program shows that a global variable is visible // to all the functions that appear in a program after // the variable's declaration. #include void func(void); // Function prototype int num = 2; // Global variable void main(void) { cout << "In main, num is " << num << endl; func(); cout << "Back in main, num is " << num << endl; }

71 Starting Out with C++, 3 rd Edition 71 Program continues //***************************************************** // Definition of function func. * // func changes the value of the global variable num * //***************************************************** void func(void) { cout << "In func, num is " << num << endl; num = 50; cout << "But, it is now changed to " << num << endl; }

72 Starting Out with C++, 3 rd Edition 72 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

73 Starting Out with C++, 3 rd Edition 73 Program 6-18 // This program shows that a global variable is visible // to all the functions that appear in a program after // the variable's declaration. #include void func(void); // Function prototype void main(void) { cout << "In main, num is not visible!\n"; func(); cout << "Back in main, num still isn't visible!\n"; }

74 Starting Out with C++, 3 rd Edition 74 Program continues int num = 2; // Global variable //***************************************************** // Definition of function func * // func changes the value of the global variable num. * //***************************************************** void func(void) { cout << "In func, num is " << num << endl; num = 50; cout << "But, it is now changed to " << num << endl; }

75 Starting Out with C++, 3 rd Edition 75 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!

76 Starting Out with C++, 3 rd Edition 76 Global Variables are Initialized to Zero by Default Unless you explicitly initialize numeric global variables, they are automatically initialized to zero. Global character variables are initialized to NULL, or ASCII code 0.

77 Starting Out with C++, 3 rd Edition 77 Program 6-19 // This program has an uninitialized global variable. #include int globalNum; // Global variable. Automatically set to zero. void main(void) { cout << "globalNum is " << globalNum << endl; }

78 Starting Out with C++, 3 rd Edition 78 Program Output globalNum is 0

79 Starting Out with C++, 3 rd Edition 79 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.

80 Starting Out with C++, 3 rd Edition 80 Program 6-20 // This program shows that when a local variable has the // same name as a global variable, the function only sees // the local variable. #include // Function prototypes void texas(); void arkansas(); int cows = 10; void main(void) { cout << "There are " << cows << " cows in main.\n"; texas(); arkansas(); cout << "Back in main, there are " << cows << " cows.\n"; }

81 Starting Out with C++, 3 rd Edition 81 Program continues //****************************************** // Definition of function texas. * // The local variable cows is set to 100. * //****************************************** void texas(void) { int cows = 100; cout << "There are " << cows << " cows in texas.\n"; }

82 Starting Out with C++, 3 rd Edition 82 Program continues //****************************************** // Definition of function arkansas. * // The local variable cows is set to 50. * //****************************************** void arkansas(void) { int cows = 50; cout << "There are " << cows << " cows in arkansas.\n"; }

83 Starting Out with C++, 3 rd Edition 83 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.

84 Starting Out with C++, 3 rd Edition 84 Program 6-21 // 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 void ringUpSale(void); // Function prototype // Global Variables const float taxRate = 0.06; float tax, sale, total; void main(void) { char again;

85 Starting Out with C++, 3 rd Edition 85 Program continues cout.precision(2); cout.setf(ios::fixed | ios::showpoint); do { ringUpSale(); cout << "Is there another item to be purchased? "; cin >> again; } while (again == 'y' || again == 'Y'); tax = sale * taxRate; total = sale + tax; cout << "The tax for this sale is " << tax << endl; cout << "The total is " << total << endl; }

86 Starting Out with C++, 3 rd Edition 86 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(void) { int qty; float unitPrice, tax, thisSale, subTotal; cout << "Quantity: "; cin >> qty; cout << "Unit price: "; cin >> unitPrice; thisSale = qty * unitPrice; // Get the total unit price

87 Starting Out with C++, 3 rd Edition 87 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 << "Price for these items: " << thisSale << endl; cout << "tax for these items: " << tax << endl; cout<< "subTotal for these items: " << subTotal << endl; }

88 Starting Out with C++, 3 rd Edition 88 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

89 Starting Out with C++, 3 rd Edition 89 Be Careful With Global Variables It is tempting to make all your variables global. But don’t do it! Using global variables can cause problems. –It is harder to debug a program that uses global variables

90 Starting Out with C++, 3 rd Edition 90 6.11 Static Local Variables If a function is called more than once in a program, the values stored in the function’s local variables do not persist between function calls. To get a variable to keep it’s value even after the function ends, you must create static variables

91 Starting Out with C++, 3 rd Edition 91 Program 6-22 // This program shows that local variables do not retain // their values between function calls. #include // Function prototype void showLocal(void); void main(void) { showLocal(); }

92 Starting Out with C++, 3 rd Edition 92 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(void) { int localNum = 5; // Local variable cout << "localNum is " << localNum << endl; localNum = 99; }

93 Starting Out with C++, 3 rd Edition 93 Program Output localNum is 5

94 Starting Out with C++, 3 rd Edition 94 Program 6-23 //This program uses a static local variable. #include void showStatic(void); // Function prototype void main(void) { for (int count = 0; count < 5; count++) showStatic(); } //************************************************************* // Definition of function showStatic. * // statNum is a static local variable. Its value is displayed * // and then incremented just before the function returns. * //************************************************************* void showStatic(void) { static int statNum; cout << "statNum is " << statNum << endl; statNum++; }

95 Starting Out with C++, 3 rd Edition 95 Program Output statNum is 0 statNum is 1 statNum is 2 statNum is 3 statNum is 4

96 Starting Out with C++, 3 rd Edition 96 Program 6-24 // This program shows that a static local variable is only // initialized once. #include void showStatic(void); // Function prototype void main(void) { for (int count = 0; count < 5; count++) showStatic(); }

97 Starting Out with C++, 3 rd Edition 97 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 << "statNum is " << statNum << endl; statNum++; }

98 Starting Out with C++, 3 rd Edition 98 Program Output statNum is 5 statNum is 6 statNum is 7 statNum is 8 statNum is 9

99 Starting Out with C++, 3 rd Edition 99 6.12 Default Arguments Default arguments are passed to parameters automatically if no argument is provided in the function call. A function’s default arguments should be assigned in the earliest occurrence of the function name. This will usually mean the function prototype.

100 Starting Out with C++, 3 rd Edition 100 Program 6-25 // This program demonstrates default function arguments. #include // Function prototype with default arguments void displayStars(int = 10, int = 1); void main(void) { displayStars(); cout << endl; displayStars(5); cout << endl; displayStars(7, 3); }

101 Starting Out with C++, 3 rd Edition 101 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 < rows; down++) { for (int across = 0; across < cols; across++) cout << "*"; cout << endl; }

102 Starting Out with C++, 3 rd Edition 102 Program Output ********** ***** *******

103 Starting Out with C++, 3 rd Edition 103 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.

104 Starting Out with C++, 3 rd Edition 104 6.13 Using Reference Variables as Parameters When used as parameters, reference variables allow a function to access the parameter’s original argument, changes to the parameter are also made to the argument.

105 Starting Out with C++, 3 rd Edition 105 Example: void doubleNum(int &refVar) { refVar *= 2; } // The variable refVar is called // “a reference to an int”

106 Starting Out with C++, 3 rd Edition 106 Program 6-26 // This program uses a reference variable as a function // parameter. #include // Function prototype. The parameter is a reference variable. void doubleNum(int &); void main(void) { int value = 4; cout << "In main, value is " << value << endl; cout << "Now calling doubleNum..." << endl; doubleNum(value); cout << "Now back in main. value is " << value << endl; }

107 Starting Out with C++, 3 rd Edition 107 Program continues //************************************************************ // Definition of doubleNum. * // The parameter refVar is a reference variable. The value * // in refVar is doubled. * //************************************************************ void doubleNum (int &refVar) { refVar *= 2; }

108 Starting Out with C++, 3 rd Edition 108 Program Output In main, value is 4 Now calling doubleNum... Now back in main. value is 8

109 Starting Out with C++, 3 rd Edition 109 Program 6-27 // This program uses reference variables as function // parameters. #include // Function prototypes. Both functions use reference variables // as parameters void doubleNum(int &); void getNum(int &); void main(void) { int value; getNum(value); doubleNum(value); cout << "That value doubled is " << value << endl; }

110 Starting Out with C++, 3 rd Edition 110 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 << "Enter a number: "; cin >> userNum; }

111 Starting Out with C++, 3 rd Edition 111 Program continues //************************************************************ // Definition of doubleNum. * // The parameter refVar is a reference variable. The value * // in refVar is doubled. * //************************************************************ void doubleNum (int &refVar) { refVar *= 2; }

112 Starting Out with C++, 3 rd Edition 112 Program Output with Example Input Enter a number: 12 [Enter] That value doubled is 24

113 Starting Out with C++, 3 rd Edition 113 Reference Argument Warning Don’t get carried away with using reference variables as function parameters. Any time you allow a function to alter a variable that’s outside the function, you are creating potential debugging problems. Reference variables should only be used as parameters when the situation demands them.

114 Starting Out with C++, 3 rd Edition 114 6.14 Overloaded Functions Two or more functions may have the same name as long as their parameter lists are different.

115 Starting Out with C++, 3 rd Edition 115 Program 6-28 #include // Function prototypes int square(int); float square(float); void main(void) { int userInt; float userFloat; cout.precision(2); cout << "Enter an integer and a floating-point value: "; cin >> userInt >> userFloat; cout << "Here are their squares: "; cout << square(userInt) << " and " << square(userFloat); }

116 Starting Out with C++, 3 rd Edition 116 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; }

117 Starting Out with C++, 3 rd Edition 117 Program Output with Example Input Enter an integer and floating-point value: 12 4.2 [Enter] Here are their squares: 144 and 17.64

118 Starting Out with C++, 3 rd Edition 118 Program 6-29 // This program demonstrates overloaded functions to calculate // the gross weekly pay of hourly-paid or salaried employees. #include // Function prototypes void getChoice(char &); float calcWeeklyPay(int, float); float calcWeeklyPay(float); void main(void) { char selection; int worked; float rate, yearly; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << “Do you want to calculate the weekly pay of\n"; cout << “(H) an hourly-paid employee, or \n”; cout << “(S) a salaried employee?\n”;

119 Starting Out with C++, 3 rd Edition 119 Program continues getChoice(selection); switch (selection) { case ‘H’ : case ‘h’ : cout << “How many hours were worked? “; cin >> worked; cout << “What is the hour pay rate? “; cin >> rate; cout << “The gross weekly pay is “; cout << calcWeeklyPay(worked, rate); break; case ‘S’ : case ‘s’ : cout << “What is the annual salary? “; cin >> yearly; cout << “The gross weekly pay is “; cout << calcWeeklyPay(yearly); break; }

120 Starting Out with C++, 3 rd Edition 120 Program continues //*********************************************************** // Definition of function getChoice. * // The parameter letter is a reference to a char. * // This function asks the user for an H or an S and returns * // the validated input. * //*********************************************************** void getChoice(char &letter) { do { cout << “Enter your choice (H or S): “; cin >> letter; } while (letter != ‘H’ && letter != ‘h’ && letter != ‘S’ && letter != ‘s’); }

121 Starting Out with C++, 3 rd Edition 121 Program continues //*********************************************************** // Definition of overloaded function calcWeeklyPay. * // This function calculates the gross weekly pay of * // an hourly-paid employee. The parameter hours hold the * // hourly pay rate. The function returns the weekly salary. * //*********************************************************** void calcWeekly(int hours, float payRate) { return hours * payRate; }

122 Starting Out with C++, 3 rd Edition 122 Program continues //*********************************************************** // Definition of overloaded function calcWeeklyPay. * // This function calculates the gross weekly pay of * // a salaried employee. The parameter holds the employee’s * // annual salary. The function returns the weekly salary. * //*********************************************************** void calcWeekly(float annSalary) { return annSalary / 52.0; }

123 Starting Out with C++, 3 rd Edition 123 Program Output with Example Input Do you want to calculate the weekly pay of (H) an houly-paid employee, or (S) a salaried employee? H[Enter] How many hours were worked? 40[Enter] What is the hour pay rate? 18.50[Enter] The gross weekly pay is 740.00 Program Output with Other Example Input Do you want to calculate the weekly pay of (H) an houly-paid employee, or (S) a salaried employee? S[Enter] What is the annual salary? 48000.00[Enter] The gross weekly pay is 923.08

124 Starting Out with C++, 3 rd Edition 124 6.15 The exit() Function The exit() function causes a program to terminate, regardless of which function or control mechanism is executing.

125 Starting Out with C++, 3 rd Edition 125 Program 6-30 // This program shows how the exit function causes a program // to stop executing. #include #include // For exit void function(void); // Function prototype void main(void) { function(); }

126 Starting Out with C++, 3 rd Edition 126 Program continues //*********************************************************** // This function simply demonstrates that exit can be used * // to terminate a program from a function other than main. * //*********************************************************** void function(void) { cout << "This program terminates with the exit function.\n"; cout << "Bye!\n"; exit(0); cout << "This message will never be displayed\n"; cout << "because the program has already terminated.\n"; }

127 Starting Out with C++, 3 rd Edition 127 Program Output This program terminates with the exit function. Bye!

128 Starting Out with C++, 3 rd Edition 128 Program 6-31 // This program demonstrates the exit function. #include #include // For exit void main(void) { char response; cout << "This program terminates with the exit function.\n"; cout << "Enter S to terminate with the EXIT_SUCCESS code\n"; cout << "or f to terminate with the EXIT_FAILURE code: "; cin >> response;

129 Starting Out with C++, 3 rd Edition 129 Program continues if (response == 'S') { cout << "Exiting with EXIT_SUCCESS.\n"; exit(EXIT_SUCCESS); } else { cout << "Exiting with EXIT_FAILURE.\n"; exit(EXIT_FAILURE); }

130 Starting Out with C++, 3 rd Edition 130 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.

131 Starting Out with C++, 3 rd Edition 131 6.16 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.

132 Starting Out with C++, 3 rd Edition 132 // Stub for the adult function. void adult(int months) { cout << "The function adult was called with " << months; cout << " as its argument.\n"; } // Stub for the child function. void child(int months) { cout << "The function child was called with " << months; cout << " as its argument.\n"; } // Stub for the senior function. void senior(int months) { cout << "The function senior was called with " << months; cout << " as its argument.\n"; }


Download ppt "Starting Out with C++, 3 rd Edition 1 Chapter 6 Functions."

Similar presentations


Ads by Google