Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions.

Similar presentations


Presentation on theme: "Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions."— Presentation transcript:

1 Functions Chapter 4

2 C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions Study how a function is called Investigate how a function executes Show design process for functions Take a first look at sequence, selection, repetition Introduce the if, for, and while statements Study libraries and their use Introduce computability theory Take a first look at class methods

3 C++ An Introduction to Programming, 3rd ed. 3 Problem Two scales used to measure temperature are the Fahrenheit and Celsius scales. A program is needed to convert temperatures in Fahrenheit to the equivalent Celsius temperatures. General Behavior For conversion to Celsius, enter Fahrenheit temp: 99 Equivalent Celsius tem is 99.9

4 C++ An Introduction to Programming, 3rd ed. 4 Objects Description Software Objects TypeKindName screen ostream varying cout prompt string constant Fahrenheit temp double varying tempFahrenheit keyboard istream varying cin Celsius temp double varying tempCelsius descriptive text string constant

5 C++ An Introduction to Programming, 3rd ed. 5 Operations Formula used i. Display string on screen ii. Read number from keyboard iii. Compute Celsius equivalent of Fahrenheit a. Perform real subtraction b. Perform real division iv. Display a number on screen

6 C++ An Introduction to Programming, 3rd ed. 6 Algorithm 1. Output a prompt for a Fahrenheit temperature to cout. 2. Input tempFahrenheit from cin. 3. Calculate tempCelsius = (tempFahrenheit – 32.0) / 1.8. 4. Output tempCelsius (and descriptive text) to cout. Coding and Testing Note source code in Figure 4.1Figure 4.1 Note sample runs for Figure 4.1sample runs

7 C++ An Introduction to Programming, 3rd ed. 7 #include using namespace std; double dFahrToCelsius(double dTempFahr); // FUNCTION PROTOTYPE int main() { cout " << dFahrToCelsius(212) << endl " << dFahrToCelsius(32) << endl; } double dFahrToCelsius(double dTempFahr) { double dCelsius; dCelsius = (dTempFahr - 32.0) / 1.8; return dCelsius; }

8 C++ An Introduction to Programming, 3rd ed. 8 Temperature Conversion with Functions Consider the need for use of this task by other programs We can construct a function that encapsulates the conversion code Note source code Figure 4.2Figure 4.2 Uses a function to do the conversion

9 C++ An Introduction to Programming, 3rd ed. 9 Comparison of Versions Program of Figure 4.2 has same output as that of Figure 4.1 Flow of execution is very different.

10 C++ An Introduction to Programming, 3rd ed. 10 Function Definitions Function definition Contains statements that dictate its behavior when it is called. Function must be defined in order to be called Else a linker error will occur. Pattern: ReturnType Name (ParameterDeclarations) { StatementList }

11 C++ An Introduction to Programming, 3rd ed. 11 Example Definitions const PI = 3.14159; double EllipseArea(double length, double width); { double dArea, dHalfLength, dHalfWidth; halfLength = length/2.0; halfWidth = width/2.0; dArea = PI * halfLength * halfWidth; return dArea; }

12 C++ An Introduction to Programming, 3rd ed. 12 Functions Are Subprograms Same steps for program design can be used for function design 1.Behavior 2.Objects 3.Operations 4.Algorithm 5.Coding 6.Testing, execution, debugging 7.Maintenance Behavior for functions will also include Receive values from calling function Return value to calling function Behavior for functions will also include Receive values from calling function Return value to calling function

13 C++ An Introduction to Programming, 3rd ed. 13 Behavior and Objects Receive from caller a Fahrenheit temp Do the conversion with the correct formula Return to caller the equivalent temp Description Software Objects TypeKindMovementName a Fahrenheit temp double varyingreceived (in) tempFahr equivalent Celsius temp double varyingreturned (out)

14 C++ An Introduction to Programming, 3rd ed. 14 Parameters Function variables for which the caller can specify values. Defined between the parentheses of a function’s definition. double fahrToCelsius(double tempFahr) { return (tempFahr - 32.0) / 1.8; }

15 C++ An Introduction to Programming, 3rd ed. 15 Arguments When a function is called Caller can pass it values called arguments Stored in the function’s parameters. double newTemp = fahrToCelsius (212) double fahrToCelsius(double tempFahr) { return (tempFahr - 32.0) / 1.8; } The function then runs using its parameter values. 212

16 C++ An Introduction to Programming, 3rd ed. 16 Operations Real subtraction ( tempFahr – 32.0 ) Real division ( (tempFahr – 32.0)/1.8 ) Return a real value double fahrToCelsius(double tempFahr) { return (tempFahr - 32.0) / 1.8; }

17 C++ An Introduction to Programming, 3rd ed. 17 Design Specification of the function Determines the form of the function heading Return value Name Parameters Algorithm of the function Determines the content of the function body Input, Output Branching, looping

18 C++ An Introduction to Programming, 3rd ed. 18 Testing, Execution, Debugging To test a function, we need a driver program Figure 4.3 shows the driver programFigure 4.3 Note also the test runtest run

19 C++ An Introduction to Programming, 3rd ed. 19 Function Prototype Acts as a declaration of the function Allowing it to be called Function prototype must precede any call or definition of a function Else a compiler error will occur Compiler must know of a function's existence Pattern: ReturnType Name (ParameterDeclarations);

20 C++ An Introduction to Programming, 3rd ed. 20 Example Prototypes #include // cin, cout, >,... #include // sqrt(), pow(),... using namespace std; double EllipseArea(double length, double width); double EllipseCircumference(double length, double width); int main() { cout << “\nTo compute the area and circumference” << “\n of an ellipse, enter its length and width: ”; double length, width; cin >> length >> width; double area = EllipseArea(length, width); double circumference = EllipseCircumference(length,width); cout << “\nThe area is “ << area << “\n and the circumference is “ << circumference << endl; } To call a function, use the name of the function as if it is an expression

21 C++ An Introduction to Programming, 3rd ed. 21 Local Variables Our example only used the parameter tempFahr Many functions need other variables or constants double windChill(double tempFahr, double windSpeed) { double v_part = -35.75 + 0.4275 * tempFahr; return 35.74 + 0.6215 * tempFahr + v_part * pow(windSpeed, 0.16); }

22 C++ An Introduction to Programming, 3rd ed. 22 Functions That Return Nothing Often a program has a task that is repeated often Print out some values Retrieve values from a file This is done with void functions Note the printAsMoney ( ) function in Figure 4.5 Figure 4.5 Note the sample runssample runs

23 C++ An Introduction to Programming, 3rd ed. 23 Functions That Use Selection Problem: Write a function, that given two real values, returns the minimum of the two values. Behavior Receive two real values from caller If first is less than second, return first value Otherwise return second value

24 C++ An Introduction to Programming, 3rd ed. 24 Functions That Use Selection Objects Description Software Objects TypeKindMovementName first value double variablereceived first second value double variablereceived second minimum value double variablereturned

25 C++ An Introduction to Programming, 3rd ed. 25 Functions That Use Selection Operations i. Receive two real values from the function’s caller ii. Compare two real values to see if one is less than the other iii. Return the first value iv. Return the second value v. Select either iii or iv (but not both), based on the result of ii Algorithm If first < second return first ; otherwise return second.

26 C++ An Introduction to Programming, 3rd ed. 26 Functions That Use Selection Coding View Figures 4.6, 4.7 Testing Note sample runssample runs

27 C++ An Introduction to Programming, 3rd ed. 27 Function Behavior Determined by the statements within the function. Statements fall into one of three categories: Statements that simply execute in sequence. Statements that select one of several alternatives. Statements that repeat another statement.

28 C++ An Introduction to Programming, 3rd ed. 28 Sequential Execution C++ statements are executed One after another In sequence { Statement 1 Statement 2... Statement N } The C++ compound statement (or block) A statement for eliciting sequential execution of a series of statements. by default:

29 C++ An Introduction to Programming, 3rd ed. 29 Selective Execution Consider a requirement that a statement be executed Selectively Based on a condition (a boolean expression): if (Condition) Statement 1 [ else Statement 2 ] if (Condition) Statement 1 [ else Statement 2 ] The C++ if statement For eliciting selective execution of a statement Allowing a program to choose to execute either Statement 1 or Statement 2, but not both.

30 C++ An Introduction to Programming, 3rd ed. 30 C++ Statements Note that a Statement can be either Single statement, Compound statement: if (score > 100 || score < 0) { cerr << “Invalid score!\n”; exit(1); } else if (score >= 60) grade = ‘P’; else grade = ‘F’; if (score > 100 || score < 0) { cerr << “Invalid score!\n”; exit(1); } else if (score >= 60) grade = ‘P’; else grade = ‘F’; To select two or more statements Must be wrapped in curly-braces { } Forms a compound statement.

31 C++ An Introduction to Programming, 3rd ed. 31 Nested if s Syntax calls for a statement Could be an if statement if (abs(x-7) 7) cout << "x approaches 7 from right"; else cout << "x not close to 7"; if (Condition) Statement 1 [ else Statement 2 ] if (Condition) Statement 1 [ else Statement 2 ] Which else goes with which if?? In a nested if statement, an else is matched with the nearest preceding unmatched if

32 C++ An Introduction to Programming, 3rd ed. 32 Nested if s The result may not be what you want Use curly brackets to make a compound statement or block if (abs(x-7) 7) cout << "x approaches 7 from right"; } else cout << "x not close to 7";

33 C++ An Introduction to Programming, 3rd ed. 33 Functions that Use Repetition Problem: The factorial of a nonnegative integer n, is denoted by n! and defined by Write a function that, given an integer ≤ 0, computes n factorial

34 C++ An Introduction to Programming, 3rd ed. 34 Objects, Operations Operations i. Check the precondition ii. Declare and initialize two integer variables ( product and count ) iii. Multiply two integers ( product and count ) and assign the result to an integer ( product ) iv. Increment an integer variable ( count ) v. Repeat Operations iii and iv so long as count is less than or equal to n Description Software Objects TypeKindMovementName nonnegative integer int variablereceived n the running product int variablereturned product the counter int variablelocal count

35 C++ An Introduction to Programming, 3rd ed. 35 Algorithm, Source Code, Testing 1. Initialize product to 1. 2. Repeat the following for each value of count in the range 2 to n : Multiply product by count. 3. Return product. Note source code of Figures 4.8, 4.9 which implements the algorithm and tests the functionFigures 4.8, 4.9 View sample runssample runs

36 C++ An Introduction to Programming, 3rd ed. 36 #include using namespace std; int factorial(int n); int main() { int nTheNumber; cout << "To compute n!, enter n: "; cin >> nTheNumber; cout << nTheNumber << "! = " << factorial(nTheNumber) << endl; } /* factorial computes the factorial of a nonnegative integer. * * Receive: n, an integer * Precondition: n is nonnegative * Return: n! *************************************************************/ #include // assert() using namespace std; int factorial(int n) { assert(n >= 0); int nProduct = 1; for (int nCount = 2; nCount <= n; nCount++) nProduct *= nCount; return nProduct; }

37 C++ An Introduction to Programming, 3rd ed. 37 Repetitive Execution Consider a requirement that a statement be repeated Repetition being controlled by a condition: for (InitializerExpr; LoopCondition; IncrementExpr) Statement for (InitializerExpr; LoopCondition; IncrementExpr) Statement The C++ for statement For eliciting repetitive execution of a statement, allowing a program to repeat the execution of Statement.

38 C++ An Introduction to Programming, 3rd ed. 38 The for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement for (InitializerExpr; LoopCondition; IncrementExpr) Statement Statement will be executed so long as LoopCondition is true. InitializerExpr LoopCondition Statement IncrementExpr F T Statement is often called the body of the loop.

39 C++ An Introduction to Programming, 3rd ed. 39 The for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement for (InitializerExpr; LoopCondition; IncrementExpr) Statement Each execution of LoopCondition, Statement, IncrementExpr is called one repetition or iteration of the loop. InitializerExpr LoopCondition Statement IncrementExpr F T

40 C++ An Introduction to Programming, 3rd ed. 40 The for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement for (InitializerExpr; LoopCondition; IncrementExpr) Statement When LoopCondition becomes false, Control proceeds to the next statement. InitializerExpr LoopCondition Statement IncrementExpr F T Note: if the LoopCondition is initially false, then the body of the loop will not be executed even once.

41 C++ An Introduction to Programming, 3rd ed. 41 Counting The “normal” use of the for loop is to count: for (int count = 1; count <= limit; count++) cout << count << endl; Output (suppose limit == 5): 1 2 3 4 5

42 C++ An Introduction to Programming, 3rd ed. 42 Nested Loops Loops can also be nested: for (int val1 = 1; val1 <= limit1; val1++) for (int val2 = 1; val2 <= limit2; val2++) cout << val1 << ‘*’ val2 “ = “ << val1 * val2 << endl; Output (suppose limit1 == 2, limit2 == 3): 1*1 = 1 1*2 = 2 1*3 = 3 2*1 = 2 2*2 = 4 2*3 = 6

43 C++ An Introduction to Programming, 3rd ed. 43 Counting Loops The for loop is normally used to count through a range of values: for (int count = first; count <= last; count++) Statement for (int count = first; count <= last; count++) Statement Such a loop will count From first To last (inclusive), Executing Statement Once for each value in the range first..last.

44 C++ An Introduction to Programming, 3rd ed. 44 Problem with for Loop Consider a program to process several input values It does not know how many input values are coming How to run a counting loop to handle this situation?? Solution Use the while loop The body of the loop executes repeatedly while the loop condition is true

45 C++ An Introduction to Programming, 3rd ed. 45 The while Loop For such situations, C++ provides the more readable while loop, pattern is: while (Expression) Statement Expression T F Statement Statement can be either a single or compound C++ statement. Repetition continues so long as Expression is true! Note use of while loop in driver for testing factorial, Figure 4.10Figure 4.10

46 C++ An Introduction to Programming, 3rd ed. 46 Computability Theory We have used sequence, selection, and repetition The set of all operations possible with sequence is a proper subset of all operations built with sequence and selection Similarly with sequence, selection, and repletion

47 C++ An Introduction to Programming, 3rd ed. 47 Computability Theory Note the Venn Diagram which visualizes the concept

48 C++ An Introduction to Programming, 3rd ed. 48 Computability Theory This branch of computer science investigates theoretically questions such as: What can or cannot be computed? How can functions be classified? What relationships exist among those classes? What is the most efficient algorithm for solving a particular problem?

49 Problem Session Working in groups of two, solve the following problem...

50 C++ An Introduction to Programming, 3rd ed. 50 Problem Consider an eight-function calculator Allows the user to perform addition, subtraction, multiplication, division, exponentiation, base-ten logarithm, factorial, and quit operations Use OCD (Object Centered Design) Behavior: User enters symbol for the operation Program displays prompts for operand(s) Results calculated, displayed

51 C++ An Introduction to Programming, 3rd ed. 51 Objects Description Software Objects TypeKindName

52 C++ An Introduction to Programming, 3rd ed. 52 Operations Description Name Predefined?LibraryOperator Use description to fill in chart for operations.

53 C++ An Introduction to Programming, 3rd ed. 53 Algorithm and Coding Work together to determine the steps necessary to have the objects manipulated by the operations Write the source code Compile and Link Test the program

54 C++ An Introduction to Programming, 3rd ed. 54 An Introduction to Libraries We seek to easily reuse handy functions we develop Libraries are files containing items to be shared by different programs Functions logically grouped into libraries by the task that they do Header file contains declarations, prototypes (also called the interface file) Note Figure 4.12 – a header file for library HeatFigure 4.12

55 C++ An Introduction to Programming, 3rd ed. 55 An Introduction to Libraries Programs which will use functions from the Heat library must specify #include "Heat.h" The implementation file includes the definitions of these library functions Note the source code of how the Heat.cpp file appears, Figure 4.13Figure 4.13

56 C++ An Introduction to Programming, 3rd ed. 56 An Introduction to Libraries Items in the.cpp file that are declared in the.h file can be accessed by any program that uses the #include directive and links to the implementation file Items in the. cpp file NOT declared in the.h file CANNOT be accessed outside the implementation file Even if the #include is used

57 C++ An Introduction to Programming, 3rd ed. 57 An Introduction to Libraries Documentation file is a copy of the header file annotated with documentation of the objects function prototype specifications Once the library is constructed it can be used as shown in Figure 4.15Figure 4.15

58 C++ An Introduction to Programming, 3rd ed. 58 Benefits of Libraries Functions are reusable Libraries hide implementation details Programs are easier to maintain Separate compilation Independent coding Testing is simplified

59 C++ An Introduction to Programming, 3rd ed. 59 OBJECTive Thinking: Class Methods Class methods are function members A mechanism for building a new operation for a class type Categories of methods Class method – defines a message that can be sent to a class Instance method – defines a message sent to an object (an instance of a class)

60 C++ An Introduction to Programming, 3rd ed. 60 A Temperature Class Method #include using namespace std; #include "Temperature.h" int main() { cout << "To convert Fahrenheit to Celsius,\n" << " enter a Fahrenheit temperature: "; double fahrTemp; cin >> fahrTemp; double celsTemp = Temperature::fahrToCels(fahrTemp); cout << "The equivalent temperature is " << celsTemp << endl; } Message is sent to the class, not to an object. Note class methods in declaration of Figure 4.17Figure 4.17 Note class methods in declaration of Figure 4.17Figure 4.17 Note the scope operator

61 C++ An Introduction to Programming, 3rd ed. 61 A Temperature Class Method As we wrapped variable declarations in a class, we can also wrap function prototypes When keyword static prefaces class method – this specifies a class method When keyword static not used, the method is an instance method When the method is defined, note the use of the class name and scope operator Class methods must not access instance variables

62 C++ An Introduction to Programming, 3rd ed. 62 A Temperature Class Method Variables within a class may also be specified as static variables This makes them class variables Each instance of a class shares class variables Each instance of a class has its own instance variables Class methods may access class variables Instance methods may access both Class variables Instance variables


Download ppt "Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions."

Similar presentations


Ads by Google