Chapter 6: User-Defined Functions I

Slides:



Advertisements
Similar presentations
Chapter 6: User-Defined Functions I
Advertisements

1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
Chapter 6: User-Defined Functions I
Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
1 Lecture 14:User-Definded function I Introduction to Computer Science Spring 2006.
Chapter 6: User-Defined Functions I
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 7: User-Defined Methods
Functions Modules in C++ are called functions and classes
Chapter 3: Input/Output
Chapter 7 Functions.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
1 Programming in C++ Dale/Weems/Headington Chapter 7 Functions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
CHAPTER 5 FUNCTIONS I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 4: Control Structures I (Selection)
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
1 Functions. 2 Chapter 7 Topics  Writing a Program Using Functional Decomposition  Writing a Void Function for a Task  Using Function Arguments and.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
TK 1914 : C++ Programming Control Structures I (Selection)
1 Chapter 7 Functions Dale/Weems/Headington. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
CHAPTER 6 USER-DEFINED FUNCTIONS I. In this chapter, you will: Learn about standard (predefined) functions and discover how to use them in a program Learn.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
CHAPTER 6 USER-DEFINED FUNCTIONS Made By- Kartik Belwal.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
1 Chapter 9 Scope, Lifetime, and More on Functions.
USER-DEFINED FUNCTIONS I. In this chapter, you will: Learn about standard (predefined) functions and discover how to use them in a program Learn about.
CHAPTER 6 USER-DEFINED FUNCTIONS I
Chapter 8 Functions.
Chapter 4: Control Structures I (Selection)
Topic 2 Input/Output.
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 6: User-Defined Functions I
Chapter 7: User-Defined Functions II
User-Defined Functions
Chapter 9 Scope, Lifetime, and More on Functions
User Defined Functions
Chapter 4 Selection.
Chapter 4: Control Structures I (Selection)
Chapter 6: User-Defined Functions I
Functions Imran Rashid CTO at ManiWeber Technologies.
Chapter 8 Functions.
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

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”; }

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

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)

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)

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

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 }

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

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

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()

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

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

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

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

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

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

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

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, ...

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.

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

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

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

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

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

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

// 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';

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

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 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

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

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

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 - 1 - i]) return false; return true;

#include <cmath> using namespace std; #include <iostream> // Palindrome: if it reads forward and backward in the same way: e.g. 1881 - 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.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 }//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

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

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

//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

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;

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; }

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

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

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