Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6: User-Defined Functions I

Similar presentations


Presentation on theme: "Chapter 6: User-Defined Functions I"— Presentation transcript:

1 Chapter 6: User-Defined Functions I
Credits go to © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. C++ Programming: Program Design Including Data Structures Second Edition

2 Objectives In this chapter you will: Learn about standard (predefined) functions and discover how to use them in a program Learn about user-defined functions Examine value-returning functions, including actual and formal parameters Learn about function prototypes Explore how to construct and use a value-returning, user-defined function in a program Discover the difference between value and reference parameters Explore reference parameters and value-returning functions Learn about the scope of an identifier Examine the difference between local and global identifiers Discover static variables Learn how to debug programs using drivers and stubs Learn function overloading Explore functions with default parameters

3 every C++ program must have a function called main()
Functions every C++ program must have a function called main() program execution always begins with function main any other functions are subprograms and must be called

4 Functions are like building blocks
They allow complicated programs to be divided into manageable pieces Some additional advantages of functions: A programmer can focus on just that part of the program and construct it, debug it, and perfect it Different people can work on different functions simultaneously Can be used in more than one place in a program or in different programs It can be reused Enhance the program’s readability

5 Functions (continued)
Called modules Like miniature programs Can be put together to form a larger program

6 the unique value of the function associated with the arguments
Predefined Functions In algebra, a function is defined as a rule or correspondence between values, called the function’s arguments, and the unique value of the function associated with the arguments If f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and f(3) = 11 1, 2, and 3 are arguments 7, 9, and 11 are the corresponding values

7 Predefined Functions (continued)
Some of the predefined mathematical functions are: sqrt(x) pow(x,y) floor(x) Predefined functions are organized into separate libraries I/O functions are in iostream header Math functions are in cmath header

8 The Power Function (pow)
pow(x,y) calculates xy, pow(2,3) = 8.0 pow returns a value of the type double x and y are called the parameters (or arguments) of the function pow Function pow has two parameters

9 The sqrt and floor Functions
The square root function sqrt(x) Calculates the non-negative square root of x, for x >= 0.0 sqrt(2.25) is 1.5 Type double and has only one parameter

10 The sqrt and floor Functions (continued)
The floor function floor(x) Calculates largest whole number not greater than x floor(48.79) is 48.0 Type double and has only one parameter

11

12 Program with Several Functions
function prototypes main function Square function Cube function

13 Two Parts of Function Definition
int Cube ( int n ) heading { body return n * n * n ; }

14 int Cube ( int n ) What is in a heading? type of value returned
parameter list name of function int Cube ( int n )

15 Value-returning Functions
#include <iostream> int Square ( int ) ; // prototypes – promise of a full definition later, // specify the name of the function and data types int Cube ( int ) ; using namespace std; int main ( ) { cout << “The square of 27 is “ << Square (27) << endl; // function call cout << “The cube of 27 is “ << Cube (27) << endl; // function call return 0; } 15

16 Rest of Program int Square ( int n ) // returns int
// header and body int Square ( int n ) // returns int { return n * n; } int Cube ( int n ) // returns int return n * n * n;

17 void-returning Functions
void functions: do not have a data type parameter void DisplayMessage( int index ) { if ( index < 35 ) cout << “Pleasant”; else if ( index <= 60 ) cout << “Unpleasant”; else cout << “Health Hazard”; }

18 Value-Returning Functions
The syntax is: functionType functionName ( formal parameter list ) { statements } functionType: type of the value returned by the function Also called the data type The syntax of the formal parameter list is: dataType identifier, dataType identifier, ... or it can be empty

19 Syntax to call a function abs ( -5)
Formal Parameter List FIGURE 6-1 Various parts of the function abs Syntax to call a function abs ( -5)

20 User-Defined Functions
Void functions: do not have a data type Value-returning functions: have a data type functionType functionName( formal parameter list ) To use these functions you need to: Include the correct header file Know the name of the function Know the number of parameters, if any Know the data type of each parameter Know the data type of the value computed by the function, called the type of the function Code required to accomplish the task (the body of the function)

21 Value-Returning Functions
Because the value returned by a value-returning function is unique, we must: Save the value for further calculation Use the value in some calculation Print the value So a value-returning function is used respectively: in an assignment statement, a parameter in a function call or in an expression in an output statement

22 Value-Returning Functions (continued)
Properties that form the function definition: Name of the function Number of parameters Data type of each parameter Type of the function Code required to accomplish the task (the body of the function) functionType functionName( formal parameter list ) { statements }

23 Value-Returning Functions (continued)
functionType functionName( formal parameter list ) { statements } Name of the function Number of parameters Data type of each parameter Type of the function Heading: first 4 properties above Formal Parameter: variable declared in the heading Actual Parameter: variable or expression listed in a call to a function

24 Value-Returning Functions (continued)
y FIGURE 6-2 Various parts of the function larger

25 The formal parameter list can be empty
Functions The formal parameter list can be empty If the formal parameter list is empty Parentheses are still needed Function heading of the value-returning function takes either of the following forms: functionType functionName() functionType functionName(void) In a function call the actual parameter is empty A call to a value-returning function with an empty formal parameter list is: functionName()

26 Value-Returning Functions
To call a value-returning function: Use its name, with the actual parameters (if any) in parentheses There is a one-to-one correspondence between actual and formal parameters The order of actual and formal parameters should be the same

27 Value-Returning Functions (continued)
A function call in a program results in the execution of the body of the called function A value-returning function is used : in an expression Expression may be part of an assignment statement or an output statement as a parameter in a function call

28 return variable; When a return statement executes
The return Statement Once the function computes the value, the function returns the value via the return statement The syntax of the return statement is: return expr; // or return variable; When a return statement executes Function immediately terminates Control goes back to the caller When a return statement executes in the function main, the program terminates

29 The return Statement int secret(int x) { if (x > 5) //Line 1 return 2 * x; //Line 2 } A correct definition of the function secret is: if (x > 5) //Line 1 return 2 * x; //Line 2 return x; //Line 3

30 or return expr1, expr2, expr3; The last one – expr3
The return Statement A return statement returns only one value. If a return statement contains > 1 expression, which value is returned? return expr1, expr2, variable; or return expr1, expr2, expr3; The last one – expr3

31 Examples pointing out that the return statement only returns one value
return x, y; //only the value of y will be returned int funcRet1() { int x = 45; return 23, x; //only the value of x is returned // = 45 } int funcRet2(int z) int a = 2; int b = 3; return 2 * a + b, z + b; //only the value of z + b = z + 3 is returned

32 The return Statement without return a value
Formal parameters are optional in void functions A call to a void function is a stand-alone statement The function definition of void functions with parameters has the following syntax: return statement is valid only in the body block of void functions causes control to leave the function and immediately return to the calling block: leaving any subsequent statements in the function body unexecuted

33 The syntax for a function call is:
Function Call Syntax The syntax for a function call is: The syntax for the actual parameter list is: expression or variable,expression or variable, ...

34 functionName ( actual parameter list )
Function Call Syntax functionName ( actual parameter list ) The argument list is a way for functions to communicate with each other by passing information. The argument list can contain 0, 1, or more arguments, separated by commas, depending on the function.

35 int Cube( int ); // prototype
What is in a prototype? A prototype looks like a heading but must end with a semicolon; and its parameter list just needs to contain the type of each parameter. int Cube( int ); // prototype

36 Function Prototype: function heading without the body of the function
The syntax is: It is not necessary to specify the variable name in the parameter list The data type of each parameter must be specified

37 Execution always begins at
Flow of Execution Execution always begins at The first statement in the function main() no matter where main is placed in the program Other functions are executed only when they are called

38 Flow of Execution (Continued)
Function prototypes appear before any function definition The compiler translates these first The compiler can then correctly translate a function call knowing the header of the function remember the compiler compiles the program sequentially from the beginning to the end

39 Flow of Execution (continued)
A function call statement results in Transfer of control to the first statement in the body of the called function After the last statement of the called function is executed Control is passed back to the point immediately following the function call

40 Flow of Execution (continued)
A value-returning function returns a value After executing the function The value that the function returns replaces the function call statement

41 // write the program which calculates the course grade example 6-3 p
using namespace std; char courseGrade(int score); // prototype int main() { int testScore; cout << "Enter test score (between 0 and 100): "; cin >> testScore; cout << "The grade is: " << courseGrade(testScore) << endl; return 0; } char courseGrade(int score) switch (score / 10) case 0: case 1: case 2: case 3: case 4: case 5: return 'F'; case 6: return 'D'; case 7: return 'C'; case 8: return 'B'; case 9: case 10: return 'A';

42 Programming Example In this programming example, the function larger is used to determine the largest number from a set of numbers Program determines the largest number from a set of 10 numbers Input: A set of 10 numbers Output: The largest of 10 numbers

43 Program Analysis Suppose that the input data is:
Read the first number of the data set Because this is the only number read to this point, you may assume that it is the largest number so far and call it max Read the second number and call it num Compare max and num, and store the larger number into max Now max contains the larger of the first two numbers 5. Read the third num and compare it with max and store the larger number into max 6. At this point, max contains the largest of the first three numbers 7. Read the next num, compare it with max, and store the larger into max 8. Repeat this process for each remaining number in the data set

44 For each remaining number in the list
Algorithm Design Read the first number Because this is the only number that you have read, it is the largest number so far Save it in a variable called max For each remaining number in the list Read the next number Store it in a variable called num Compare num and max If max < num num is the new largest number update the value of max by copying num into max If max >= num , discard num; that is, do nothing Because max now contains the largest number, print it

45 For each remaining number in the list
// Program: Largest Programming Example p.377 #include <iostream> using namespace std; double larger(double x, double y); //prototype int main() { double num; //variable to hold the current number double max; //variable to hold the larger number int count; //loop control variable cout << "Enter 10 numbers." << endl; cin >> num; //Step 1 max = num; //Step 1 for (count = 1; count < 10; count++) //Step 2 cin >> num; //Step 2a max = larger(max, num); //Step 2b } cout << "The largest number is " << max << endl; //Step 3 return 0; }//end main double larger(double x, double y) if (x >= y) return x; else // else can be omitted return y; Read the first number Because this is the only number that you have read, it is the largest number so far Save it in a variable called max For each remaining number in the list Read the next number Store it in a variable called num Compare num and max If max < num num is the new largest number update the value of max by copying num into max If max >= num , discard num; that is, do nothing Because max now contains the largest number, print it

46 Palindrome A palindrome is a string if it reads forward and backward in the same way: anna Example 6-6 p. 370 #include <iostream> #include <string> using namespace std; bool isPalindrome(string str); int main() { return 0; } bool isPalindrome(string str) int length = str.length(); //Step 1 for (int i = 0; i < (length - 1) / 2; i++) //Step 2 if (str[i] != str[length i]) return false; return true;

47 #include <cmath> using namespace std;
#include <iostream> // Palindrome: if it reads forward and backward in the same way: e.g for number specific #include <cmath> using namespace std; bool isNumPalindrome (int num); int main() { ……. return 0; } bool isNumPalindrome(int num) // if it reads forward and backward in the same way int pwr = 0; if (num < 10) //Step 1 true case return true; else //Step 2 //Step 2.a – extract the highest power of 10 which doesn’t exceeds num while (num / static_cast<int>(pow(10, pwr)) >= 10) pwr++; while (num >= 10) //Step 2.b { // if first digit of num != last digit of num if ((num / static_cast<int>(pow(10, pwr))) != (num % 10)) return false; //Step 2.b.1 else //Step 2.b.2 num = num % static_cast<int>(pow(10, pwr)); //Step 2.b.2.1 – remove first digit num = num / 10; //Step 2.b – remove last digit pwr = pwr - 2; //Step 2.b decrement by 2 b/c was removed 2 positions of num }//end while }//end else //Alg: if the first and the last digits of num are the same, remove the first and last digits of num and repeat this process on the new number which is obtained from num after removing the first and last digits of num. Repeat this process as long as the number is >= 10. To remove the first digit, you can use the mod operator where the divisor is 10^pwr. To remove the last digit divide the num by 10. You then decrement pwr by 2 for the next iteration, b/c was removed 2 positions of num

48 There are two types of customers:
#include <iostream> //example 6 – 7 #include <iomanip> using namespace std; //Named constants - residential customers const double rBillProcessingFee = 4.50; const double rBasicServiceCost = 20.50; const double rCostOfaPremiumChannel = 7.50; //Named constants - business customers const double bBillProcessingFee = 15.00; const double bBasicServiceCost = 75.00; const double bBasicConnectionCost = 5.00; const double bCostOfaPremiumChannel = 50.00; int main() { //Variable declaration int accountNumber; char customerType; int numberOfPremiumChannels; int noOfBasicServiceConnections; double amountDue; cout << fixed << showpoint; //Step 1 cout << setprecision(2); //Step 1 cout << "This program computes a cable bill." << endl; cout << "Enter account number: "; //Step 2 cin >> accountNumber; //Step 3 cout << endl; cout << "Enter customer type: R or r (Residential), " << "B or b(Business): "; //Step 4 cin >> customerType; //Step 5 This programming example calculates a customer’s bill for a local cable company (the solution from ch4) There are two types of customers: Residential Business Two rates for calculating a cable bill: One for residential customers One for business customers Output floating-point numbers in fixed decimal with decimal point and trailing zeros Output floating-point numbers with two decimal places, set the precision to two decimal places Prompt user to enter account number Get customer account number Prompt user to enter customer code Get customer code

49 If the customer code is r or R,
switch (customerType) { case 'r': //Step 6 case 'R': cout << "Enter the number" << " of premium channels: "; //Step 6a cin >> numberOfPremiumChannels; //Step 6b cout << endl; amountDue = rBillProcessingFee //Step 6c rBasicServiceCost + numberOfPremiumChannels * rCostOfaPremiumChannel; cout << "Account number = " << accountNumber << endl; //Step 6d cout << "Amount due = $" << amountDue << endl; // Step 6d break; case 'b': //Step 7 case 'B': cout << "Enter the number of basic " << "service connections: "; //Step 7a cin >> noOfBasicServiceConnections; //Step 7b cout << "Enter the number" << " of premium channels: "; //Step 7c cin >> numberOfPremiumChannels; //Step 7d if (noOfBasicServiceConnections <= 10) //Step 7e amountDue = bBillProcessingFee + bBasicServiceCost + numberOfPremiumChannels * bCostOfaPremiumChannel; else (noOfBasicServiceConnections -10) * bBasicConnectionCost + cout << "Account number = " << accountNumber << endl; //Step 7f cout << "Amount due = $" << amountDue << endl; //Step 7f default: cout << "Invalid customer type." << endl; //Step 8 }//end switch return 0; } If the customer code is r or R, Prompt user to enter number of premium channels Get the number of premium channels Calculate the billing amount Print account number and billing amount If customer code is b or B, Prompt user to enter number of basic service connections Get number of basic service connections Prompt user to enter number of premium channels Get number of premium channels Calculate billing amount If customer code is other than r, R, b, or B, output an error message Code for the methods in yellow – see next pages

50 //Cable company billing program (compare the end of ch 4 slides) – a solution in terms of functions
#include <iostream> #include <iomanip> using namespace std; //named constants; residential customers const double rBillProcessingFee = 4.50; const double rBasicServiceCost = 20.50; const double rCostOfAPremiumChannel = 7.50; //named constants; business customers const double bBillProcessingFee = 15.00; const double bBasicServiceCost = 75.00; const double bBasicConnectionCost = 5.00; const double bCostOfAPremiumChannel = 50.00; double residential(); //Function prototype double business(); //Function prototype int main() { //declare variables int accountNumber; char customerType; double amountDue; cout << fixed << showpoint; //Step 1 cout << setprecision(2); //Step 2 cout << "This program computes a cable bill." << endl; cout << "Enter account number: "; //Step 3 cin >> accountNumber; //Step 4 cout << endl; cout << "Enter customer type: R, r " << "(Residential), B, b (Business): "; //Step 5 cin >> customerType; //Step 6

51 switch (customerType) //Step 7
{ case 'r': //Step 7a case 'R': amountDue = residential(); //Step 7a.i cout << "Account number = "<< accountNumber << endl; //Step 7a.ii cout << "Amount due = $“ << amountDue << endl; //Step 7a.ii break; case 'b': //Step 7b case 'B': amountDue = business(); //Step 7b.i cout << "Account number = " << accountNumber << endl; //Step 7b.ii cout << "Amount due = $“ << amountDue << endl; //Step 7b.ii default: cout << "Invalid customer type." << endl; //Step 7c } return 0; double residential() int noOfPChannels; // number of premium channels double bAmount; // billing Amount cout << "Enter the number of premium " << "channels used: "; cin >> noOfPChannels; cout << endl; bAmount= rBillProcessingFee + rBasicServiceCost + noOfPChannels * rCostOfAPremiumChannel; return bAmount;

52 double business() { int noOfBasicServiceConnections; int noOfPChannels; //number of premium channels double bAmount; //billing Amount cout << "Enter the number of basic " << "service connections: "; cin >> noOfBasicServiceConnections; cout << endl; cout << "Enter the number of premium " << "channels used: "; cin >> noOfPChannels; if (noOfBasicServiceConnections <= 10) bAmount = bBillProcessingFee + bBasicServiceCost + noOfPChannels * bCostOfAPremiumChannel; else (noOfBasicServiceConnections - 10) * bBasicConnectionCost + return bAmount; }

53

54 Functions (modules) are miniature programs
Summary Functions (modules) are miniature programs Functions enable you to divide a program into manageable tasks C++ provides the standard functions Two types of user-defined functions: value-returning functions and void functions Variables defined in a function heading are called formal parameters Expressions, variables, or constant values in a function call are called actual parameters

55 A value-returning function returns its value via the return statement
Summary In a function call, the number of actual parameters and their types must match with the formal parameters in the order given To call a function, use its name together with the actual parameter list Function heading and the body of the function are called the definition of the function If a function has no parameters, you need empty parentheses in heading and call A value-returning function returns its value via the return statement

56 A prototype is the function heading without the body of the function;
Summary A prototype is the function heading without the body of the function; prototypes end with the semicolon ; Prototypes are placed before every function definition, including main User-defined functions execute only when they are called In a call statement, specify only the actual parameters, not their data types


Download ppt "Chapter 6: User-Defined Functions I"

Similar presentations


Ads by Google