Exploring Functions in Software Development: A Practical Guide
E N D
Presentation Transcript
Functions Chapter 4
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 C++ An Introduction to Programming, 3rd ed.
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.2 • Uses a function to do the conversion C++ An Introduction to Programming, 3rd ed.
Comparison of Versions • Program of Figure 4.2 has same output as that of Figure 4.1 • Flow of execution is very different. C++ An Introduction to Programming, 3rd ed.
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 } C++ An Introduction to Programming, 3rd ed.
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); } C++ An Introduction to Programming, 3rd ed.
Behavior for functions will also include • Receive values from calling function • Return value to calling function Functions Are Subprograms • Same steps for program design can be used for function design • Behavior • Objects • Operations • Algorithm • Coding • Testing, execution, debugging • Maintenance C++ An Introduction to Programming, 3rd ed.
Behavior and Objects • Receive from caller a Fahrenheit temp • Do the conversion with the correct formula • Return to caller the equivalent temp C++ An Introduction to Programming, 3rd ed.
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; } C++ An Introduction to Programming, 3rd ed.
212 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. C++ An Introduction to Programming, 3rd ed.
Operations • 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; } C++ An Introduction to Programming, 3rd ed.
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 C++ An Introduction to Programming, 3rd ed.
Testing, Execution, Debugging • To test a function, we need a driver program • Figure 4.3 shows the driver program • Note also the test run C++ An Introduction to Programming, 3rd ed.
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); C++ An Introduction to Programming, 3rd ed.
To call a function, use the name of the function as if it is an expression Example Prototypes #include <iostream> // cin, cout, <<, >>, ... #include <cmath> // 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; } C++ An Introduction to Programming, 3rd ed.
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) { doublev_part = -35.75 + 0.4275 * tempFahr; return 35.74 + 0.6215 * tempFahr + v_part * pow(windSpeed, 0.16); } C++ An Introduction to Programming, 3rd ed.
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 • Note the sample runs • Improve the readability of the program C++ An Introduction to Programming, 3rd ed.
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. C++ An Introduction to Programming, 3rd ed.
Sequential Execution • C++ statements are executed • One after another • In sequence by default: { Statement1 Statement2 ... StatementN } • The C++ compound statement (or block) • A statement for eliciting sequential execution of a series of statements. C++ An Introduction to Programming, 3rd ed.
ifCondition T F elseStatement thenStatement 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 Statement1 or Statement2, but not both. C++ An Introduction to Programming, 3rd ed.
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’; • To select two or more statements • Must bewrapped in curly-braces { } • Forms a compound statement. C++ An Introduction to Programming, 3rd ed.
Single branchif (boolean_exp) statement Dual branchif (boolean_exp) statement1 else statement2 Multibranchif (boolean_exp) statementelse if (boolean_exp) statementelse if … Selection: the if Statement C++ An Introduction to Programming, 3rd ed.
Selection: the if Statement • Note multibranch if • Appears to be a different version • Actually is an if statement with anotherif statement as the statement of the elseif (boolean_exp) statementelse if (boolean_exp) statementelse if … C++ An Introduction to Programming, 3rd ed.
Cond1 F T Cond2 Stmt1 T F . . . Stmt2 CondN T F StmtN StmtN+1 The Multi-branch if • The if’s final form has a nested if as Statement2: if (Cond1) Stmt1 else if (Cond2) Stmt2 ... else if (CondN) StmtN else StmtN+1 C++ An Introduction to Programming, 3rd ed.
Multibranch if • Note which else goes with which if C++ An Introduction to Programming, 3rd ed.
if (Condition) Statement1 [ else Statement2 ] Which else goes with which if?? In a nested if statement, an else is matched with the nearest preceding unmatched if Nested ifs • Syntax calls for a statement • Could be an if statement if (abs(x-7) < epsilon) if (x < 7) cout << "x approaches 7 from left"; else if (x > 7) cout << "x approaches 7 from right";else cout << "x not close to 7"; C++ An Introduction to Programming, 3rd ed.
Nested ifs • The result may not be what you want • Use curly brackets to make a compound statement or blockif (abs(x-7) < epsilon){ if (x < 7) cout << "x approaches 7 from left"; else if (x > 7) cout << "x approaches 7 from right";}else cout << "x not close to 7"; C++ An Introduction to Programming, 3rd ed.
In a nested if statement, an else is matched with the nearest preceding unmatched if. 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? C++ An Introduction to Programming, 3rd ed.
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 writeif (x = 7) … C++ An Introduction to Programming, 3rd ed.
Warning: Confusing = and == • When you writeif (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 C++ An Introduction to Programming, 3rd ed.
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 C++ An Introduction to Programming, 3rd ed.
Repetitive Execution • Consider a requirement that a statement be repeated • Repetition being controlled by a condition: 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. C++ An Introduction to Programming, 3rd ed.
InitializerExpr F LoopCondition T Statement IncrementExpr The for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement • Statement will be executed so long as LoopCondition is true. • Statement is often called the body of the loop. C++ An Introduction to Programming, 3rd ed.
InitializerExpr F LoopCondition T Statement IncrementExpr The for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement Each execution of LoopCondition, Statement, IncrementExpr is called one repetition or iteration of the loop. C++ An Introduction to Programming, 3rd ed.
InitializerExpr F LoopCondition T Statement Note: if the LoopCondition is initially false, then the body of the loop will not be executed even once. IncrementExpr The for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement • When LoopCondition becomes false, • Control proceeds to the next statement. C++ An Introduction to Programming, 3rd ed.
Counting • The “normal” use of the for loop is to count: for (int count = 1; count <= limit; count++) cout << count << endl; 1 2 3 4 5 • Output (suppose limit == 5): C++ An Introduction to Programming, 3rd ed.
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 C++ An Introduction to Programming, 3rd ed.
Counting Loops • The for loop is normally used to count through a range of values: 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. C++ An Introduction to Programming, 3rd ed.
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 C++ An Introduction to Programming, 3rd ed.
F Expression T Statement The while Loop • For such situations, C++ provides the more readable while loop, • pattern is: while (Expression) 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.10 C++ An Introduction to Programming, 3rd ed.
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 C++ An Introduction to Programming, 3rd ed.
Computability Theory • Note the Venn Diagram which visualizes the concept C++ An Introduction to Programming, 3rd ed.
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? C++ An Introduction to Programming, 3rd ed.
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 Heat C++ An Introduction to Programming, 3rd ed.
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.13 C++ An Introduction to Programming, 3rd ed.
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 C++ An Introduction to Programming, 3rd ed.
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.15 C++ An Introduction to Programming, 3rd ed.
Benefits of Libraries • Functions are reusable • Libraries hide implementation details • Programs are easier to maintain • Separate compilation • Independent coding • Testing is simplified C++ An Introduction to Programming, 3rd ed.