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

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

5 C++ An Introduction to Programming, 3rd ed. 5 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 }

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

7 C++ An Introduction to Programming, 3rd ed. 7 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

8 C++ An Introduction to Programming, 3rd ed. 8 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)

9 C++ An Introduction to Programming, 3rd ed. 9 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; }

10 C++ An Introduction to Programming, 3rd ed. 10 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

11 C++ An Introduction to Programming, 3rd ed. 11 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; }

12 C++ An Introduction to Programming, 3rd ed. 12 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

13 C++ An Introduction to Programming, 3rd ed. 13 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

14 C++ An Introduction to Programming, 3rd ed. 14 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);

15 C++ An Introduction to Programming, 3rd ed. 15 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

16 C++ An Introduction to Programming, 3rd ed. 16 Local Variables Our example only used the parameter tempFahr (add “call by value”) 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); }

17 C++ An Introduction to Programming, 3rd ed. 17 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 Improve the readability of the program

18 C++ An Introduction to Programming, 3rd ed. 18 Control Flow 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.

19 C++ An Introduction to Programming, 3rd ed. 19 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:

20 C++ An Introduction to Programming, 3rd ed. 20 Selective Execution Consider a requirement that a statement be executed Selectively Based on a condition (a boolean expression): 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. ifCondition elseStatement F T thenStatement

21 C++ An Introduction to Programming, 3rd ed. 21 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.

22 C++ An Introduction to Programming, 3rd ed. 22 Selection: the if Statement Single branch if (boolean_exp) statement Dual branch if (boolean_exp) statement1 else statement2 Multibranch if (boolean_exp) statement else if (boolean_exp) statement else if …

23 C++ An Introduction to Programming, 3rd ed. 23 Selection: the if Statement Note multibranch if Appears to be a different version Actually is an if statement with another if statement as the statement of the else if (boolean_exp) statement else if (boolean_exp) statement else if …

24 C++ An Introduction to Programming, 3rd ed. 24 The Multi-branch if The if ’s final form has a nested if as Statement 2 : if (Cond 1 ) Stmt 1 else if (Cond 2 ) Stmt 2... else if (Cond N ) Stmt N else Stmt N+1 Cond 1 Stmt 1 T F Stmt 2 Cond 2 TF Stmt N Cond N TF Stmt N+1...

25 C++ An Introduction to Programming, 3rd ed. 25 Multibranch if Note which else goes with which if

26 C++ An Introduction to Programming, 3rd ed. 26 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

27 C++ An Introduction to Programming, 3rd ed. 27 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";

28 C++ An Introduction to Programming, 3rd ed. 28 The Dangling else Problem Consider: if (x > 0) if (y > 0) z = sqrt (x) + sqrt(y); else cerr << " * * Unable to Compute * *"; Which if does the else go with? In a nested if statement, an else is matched with the nearest preceding unmatched if.

29 C++ An Introduction to Programming, 3rd ed. 29 Warning: Confusing = and == True and false in C++ An integer value of 0 interprets as false A non zero value interprets as true Assignments are expressions x = 7; The value is assigned to the variable … and The expression has a value (the value assigned) What happens when you write if (x = 7) …

30 C++ An Introduction to Programming, 3rd ed. 30 Warning: Confusing = and == When you write if (x = 7) … The value is assigned to the variable The expression has that value (in this case non zero) The value of the expression is used to select the true or false branch of the if statement The program will Compile and run without crashing But will probably not execute as expected

31 C++ An Introduction to Programming, 3rd ed. 31 Baisc 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

32 C++ An Introduction to Programming, 3rd ed. 32 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.

33 C++ An Introduction to Programming, 3rd ed. 33 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.

34 C++ An Introduction to Programming, 3rd ed. 34 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

35 C++ An Introduction to Programming, 3rd ed. 35 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.

36 C++ An Introduction to Programming, 3rd ed. 36 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

37 C++ An Introduction to Programming, 3rd ed. 37 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

38 C++ An Introduction to Programming, 3rd ed. 38 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.

39 C++ An Introduction to Programming, 3rd ed. 39 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

40 C++ An Introduction to Programming, 3rd ed. 40 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

41 C++ An Introduction to Programming, 3rd ed. 41 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

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

43 C++ An Introduction to Programming, 3rd ed. 43 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?

44 C++ An Introduction to Programming, 3rd ed. 44 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

45 C++ An Introduction to Programming, 3rd ed. 45 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

46 C++ An Introduction to Programming, 3rd ed. 46 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

47 C++ An Introduction to Programming, 3rd ed. 47 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

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


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