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

Slides:



Advertisements
Similar presentations
1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Advertisements

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.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Chapter 6: User-Defined Functions I
Computer Programming 1 Functions. Computer Programming 2 Objectives Take a first look at building functions Study how a function is called Investigate.
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.
CS 201 Functions Debzani Deb.
Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Chapter 6: User-Defined Functions I
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
Selection. Computer Programming 2 Objectives Examine if statement in more detail Study use of switch statement to implement multialternative selections.
Chapter 6: Functions.
The switch Statement Selection Revisited. Problem Using OCD, design and implement a program that allows the user to perform an arbitrary temperature conversion.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Libraries Making Functions Globally Reusable (§ 6.4) 1.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
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.
Controlling Function Behavior Sequence, Selection and Repetition.
C++ An Introduction to Computing, 3rd ed. 1 Repetition Chapter 7.
CPS120: Introduction to Computer Science Decision Making in Programs.
Libraries 1 Making Functions Globally Reusable (§ 4.6)
1 Simple Functions Writing Reuseable Formulas. In Math Suppose f (x) = 2 x 2 +5Suppose f (x) = 2 x 2 +5 f(5)=?f(5)=? f(5) = 2* =55f(5) = 2*
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPS120: Introduction to Computer Science Functions.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Selection Chapter 6. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on introduction to structures Examine if statement in more detail Study.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 Controlling Behavior Chap.5 Study Sections 5.1 – 5.3 The if and for Statements.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Simple Functions Writing Reuseable Formulas. Problem Using OCD, design and implement a program that computes the area and circumference of an Australian.
Libraries Making Functions Reuseable. Review Last time, we wrote a program to compute the area and circumference of an ellipse. a a bb.
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
Calvin College Controlling Behavior The if, switch and for Statements.
Chapter 4 October 22, The If Statement Programs make decisions If(condition){ Statement(s); } Condition  boolean expression Evaluates to either.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Control Structures 1 The if, for, and while Statements §5.1, §5.4, & §5.5 (Several examples here; also Lab #4)
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Controlling Behavior The if and for Statements. Function Behavior The behavior of a function is determined by the statements within the function. Statements.
Controlling Behavior The if and for Statements.
Chapter 3 Control Statements
Chapter 6: User-Defined Functions I
Chapter 7: User-Defined Functions II
Introduction to Programmer-Defined Functions
The Selection Structure
CSC113: Computer Programming (Theory = 03, Lab = 01)
Writing Reuseable Formulas
User-Defined Functions
Control Structures – Selection
Lab 1 Introduction to C++.
Summary Two basic concepts: variables and assignments Basic types:
Chapter 6: User-Defined Functions I
Controlling Behavior The if and for Statements.
Presentation transcript:

Functions Chapter 4

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

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

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.

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 }

C++ An Introduction to Programming, 3rd ed. 6 Example Definitions const double PI = ; 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. 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

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)

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 ) / 1.8; }

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 ) / 1.8; } The function then runs using its parameter values. 212

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 ) / 1.8; }

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

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

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

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

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 = * tempFahr; return * tempFahr + v_part * pow(windSpeed, 0.16); }

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

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.

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:

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

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.

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 …

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 …

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

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

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

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

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.

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

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

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

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.

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.

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

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.

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

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

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.

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

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

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

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

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?

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

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

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

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

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