1 / 48

C++ Programming: Program Design Including Data Structures, Second Edition

C++ Programming: Program Design Including Data Structures, Second Edition. Chapter 6: User-Defined Functions I. 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

carol
Download Presentation

C++ Programming: Program Design Including Data Structures, Second Edition

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ Programming: Program Design Including Data Structures, Second Edition Chapter 6: User-Defined Functions I

  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 • Explore how to construct and use a value-returning, user-defined function in a program C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  3. 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 expanded by J. Goetz, 2004

  4. Functions • Functions are like building blocks • They allowcomplicated programs to be divided into manageable pieces • Some advantages of functions: • A programmer canfocus on just that part of the program and construct it, debug it, and perfect it • Different people can work on different functionssimultaneously • Can be used in more than one place in a program or in different programs • enhance the program’s readability C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  5. Functions (continued) • Functions • Called modules • Like miniature programs • Can be put together to form a larger program C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  6. 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  11. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  12. Program with Several Functions function prototypes main function Square function Cube function C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  13. Two Parts of Function Definition int Cube ( int n )heading { body return n * n * n ; } expanded by J. Goetz, 2004

  14. What is in a heading? type of value returned parameter list name of function int Cube ( int n ) expanded by J. Goetz, 2004

  15. Value-returning Functions #include <iostream> int Square ( int ) ; // prototypes 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 expanded by J. Goetz, 2004

  16. Rest of Program // header and body int Square ( int n )// returns int { return n * n; } // header and body int Cube ( int n )// returns int { return n * n * n; } expanded by J. Goetz, 2004

  17. parameter void DisplayMessage( int index ) { if ( index < 35 ) cout << “Pleasant”; else if ( index <= 60 ) cout << “Unpleasant”; else cout << “Health Hazard”; } expanded by J. Goetz, 2004

  18. User-Defined Functions • Void functions: do not have a data type • Value-returning functions: have a data type • To use these functions you need to: • Include the correct header file • Know the name of the function • Know the number ofparameters, 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  19. 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 • A value-returning function is used: • in an assignment statement, • in an output statementor • a parameter in a function call C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  20. 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) C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  21. Value-Returning Functions (continued) • Heading: first four properties above • Formal Parameter: variable declared in the heading • Actual Parameter: variable or expressionlisted in a call to a function C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  22. 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 parameterlist is: dataType identifier, dataType identifier, ... C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  23. 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() C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  24. 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  25. Value-Returning Functions (continued) • A function call in a program results in the execution of the body of the called function A value-returning functionis used : • in an expression • Expression may be part of an assignment statementor an output statement • as a parameter in a function call C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  26. 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 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  27. return; • 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 expanded by J. Goetz, 2004

  28. Function Call Syntax • The syntax for a function call is: functionName(actual parameter list) • The syntax for the actual parameter list is: expression or variable,expression or variable, ... C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  29. 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. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  30. 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 expanded by J. Goetz, 2004

  31. Function Prototype • Function Prototype: function heading without the body of the function • The syntax is: functionType functionName(parameter list); • It is not necessary to specify the variable name in the parameter list • The data type of each parametermust be specified C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  32. 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  33. Flow of Execution (Continued) • Function prototypesappear 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  34. Flow of Execution (continued) • A function callstatement 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 backto the point immediately following the function call C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  35. Flow of Execution (continued) • A value-returning functionreturns a value • After executing the function • The value that the function returnsreplacesthefunction call statement C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  36. // write the program which calculates the course grade usingnamespace std; char courseGrade(int score); 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'; } } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  37. 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  38. Program Analysis • Suppose that the input data is: 15 20 7 8 28 21 43 12 35 3 • 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 • Comparemax and num, and store the larger number into max • Now max contains the larger of the first two numbers C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  39. Program Analysis (continued) • Read the thirdnum and compare it with max and store the larger number into max • At this point, max contains the largest of the first three numbers • Read the next num, compare it with max, and store the larger into max • Repeat this process for each remaining number in the data set C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  40. 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 • Comparenum 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  41. 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 • Comparenum 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 // Program: Largest #include <iostream> usingnamespace std; double larger(double x, double y); 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 return y; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  42. #include <iostream> // Palindrome #include <cmath> usingnamespace 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 returntrue; else//Step 2 { while (num / static_cast<int>(pow(10,pwr)) >= 10) //Step 2.a – extract the highest power of 10 which doesn’t exceeds num pwr++; while (num >= 10) //Step 2.b { if ((num / static_cast<int>(pow(10,pwr))) != (num % 10)) // first digit of num != last digit of num returnfalse; //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.2.1 - – remove last digit pwr = pwr - 2; //Step 2.b.2.2 - decrement by 2 b/c was removed 2 positions of num } }//end while returntrue; }//end else } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  43. 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  44. Summary • In a function call, the number of actual parameters and their typesmust matchwith 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 valuevia the return statement C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  45. Summary • A prototype is the function heading without the body of the function; • prototypes end with the semicolon • Prototypes are placedbefore 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  46. //Cable company billing program see the end of ch 4 slides – a solution in terms of functions #include <iostream> #include <iomanip> usingnamespace std; //named constants; residential customers constdouble rBillProcessingFee = 4.50; constdouble rBasicServiceCost = 20.50; constdouble rCostOfAPremiumChannel = 7.50; //named constants; business customers constdouble bBillProcessingFee = 15.00; constdouble bBasicServiceCost = 75.00; constdouble bBasicConnectionCost = 5.00; constdouble 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 cout << endl; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  47. 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 break; 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; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  48. 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; cout << endl; if (noOfBasicServiceConnections <= 10) bAmount = bBillProcessingFee + bBasicServiceCost + noOfPChannels * bCostOfAPremiumChannel; else bAmount = bBillProcessingFee + bBasicServiceCost + (noOfBasicServiceConnections - 10) * bBasicConnectionCost + noOfPChannels * bCostOfAPremiumChannel; return bAmount; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

More Related