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.

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
1 Lecture 10 Chapter 7 Functions Dale/Weems/Headington.
True or false A variable of type char can hold the value 301. ( F )
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
1 Lecture 6 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Overview creating your own functions calling your own functions.
1 Chapter 6 Looping Dale/Weems/Headington. 2 l Physical order vs. logical order l A loop is a repetition control structure based on a condition. l it.
Chapter 6: User-Defined Functions I
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Functions Modules in C++ are called functions and classes
Chapter 7 Functions.
Chapter 4 Procedural Abstraction and Functions That Return a Value.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
1 Chapter 7 Functions. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 Programming in C++ Dale/Weems/Headington Chapter 7 Functions.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Learners Support Publications Classes and Objects.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
Chapter 8 Functions. Chapter 8 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
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.
Programming Life Cycle Problem analysisunderstand the problem Requirements definition specify what program will do High- and low-level designhow it meets.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPS120: Introduction to Computer Science Functions.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
1 COMS 261 Computer Science I Title: String Class Date: October 3, 2005 Lecture Number: 14.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 7 Functions. Types of Functions Value returning Functions that return a value through the use of a return statement They allow statements such.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
Chapter 7 Functions CS185/09 - Introduction to Programming Caldwell College.
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.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
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.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
1 Chapter 9 Scope, Lifetime, and More on Functions.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
Chapter 8 Functions.
Modular Programming with Functions
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Chapter 3 Assignment and Interactive Input.
User-Defined Functions
Chapter 9 Scope, Lifetime, and More on Functions
User Defined Functions
Additional Control Structures
Chapter 6: User-Defined Functions I
Introduction to Problem Solving and Programming
Chapter 8 Functions.
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
Presentation transcript:

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 always begins with function main l any other functions are subprograms and must be called - can be called from anywhere and many times l when to use - easier to understand, maintain

3 Function Calls One function calls another by using the name of the called function next to ( ) enclosing an argument list. Program execution starts with first line of main A function call temporarily transfers control from the calling function to the called function. Function definitions - any order Compiler - one pass - translated in order Must be declared before used - physically precede function call

4 FunctionName ( Argument 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. Function Call Syntax

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

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

7 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. It must be included if the main function is defined first int Cube( int ); // prototype

8 When a function is called, Definition usually appears after the main function call Temporary memory is set up ( for its value parameters and any local variables, and also for the function’s name if the return type is not void). Then the flow of control passes to the first statement in the function’s body. The called function’s body statements are executed until one of these occurs: return statement (with or without a return value), or, closing brace of function body. Then control goes back to where the function was called.

9 #include int Cube ( int ) ;// prototype using namespace std; void main ( ) { int yourNumber ; arguments int myNumber ; yourNumber = 14 ; myNumber = 9 ; cout << “My Number = “ << myNumber ; cout << “its cube is “ << Cube (myNumber) << endl ; cout << “Your Number = “ << yourNumber ; cout << “its cube is “ << Cube (yourNumber) << endl ; }

10 To Compile Successfully, l before a function is called in your program, the compiler must previously process either the function’s prototype, or the function’s definition (heading and body) l function prototype and definition must match - 2 separate functions l function definition - tells compiler the name, data type of return value and data types of parameters

11 A C++ function can return 2 TYPES l Value returning - in its identifier at most 1 value of the type which was specified (called the return type) in its heading and prototype - called part of an expression l void-function - cannot return any value in its identifier - complete stand-alone statement - parenthesis required

12 Writing void function l Void instead of int - no value returned l function definition - heading to } l no return l use an imperative word(s) - does something

13 Parameter/argument List l is the means used for a function to share information with the block containing the call - communicate with each other l different sets of data for different situations l can have different names than arguments l must match in number, type, position l commas separate multiple arguments

14 Classified by Location Always appear in a function call within the calling block. Always appear in the function heading, or function prototype. Arguments Parameters

15 Write a void function called DisplayMessage ( ) which you can call from main ( ) to describe the pollution index value it receives as a parameter. Your city describes a pollution Index less than 35 as “Pleasant”, 35 through 60 as “Unpleasant”, and above 60 as “Health Hazard.”

16 parameter void DisplayMessage( int index ) { if ( index < 35 ) cout << “Pleasant”; else if ( index <= 60 ) cout << “Unpleasant”; else cout << “Health Hazard”; }

17 #include void DisplayMessage (int); // prototype using namespace std; int main ( ) argument { int pollutionIndex; cout << “Enter air pollution index”; cin >> pollutionIndex; DisplayMessage(pollutionIndex); // call return 0; } The Rest of the Program

18 Variables l Local n Only accessible within block declared n cannot be shared - other functions n when called start over n when done - released l Global n while program is run n shared between functions

19 return; l is valid only in the body block of void functions l causes control to leave the function and immediately return to the calling block leaving any subsequent statements in the function body unexecuted l single-entry, single-exit

20 Header files contain declarations of l Contain function prototypes l named constants like const int INT_MAX = 32767; l function prototypes like float sqrt( float ); l classes like string, ostream, istream l objects like cin, cout

21 Parameters l Value parameters - receives a copy - change has no affect on argument - 2 separate copies n any type of argument allowed l Reference parameter - one copy - attach an & to type - changes argument n share same RAM spot n pass by address or pass by location n only variable argument allowed n data types must match - syntax error n same order - logic error

22 When to Use Reference Parameters l reference parameters should be used when you want your function to give a value to, or change the value of, a variable from the calling block without an assignment statement in the calling block

23 Questions l Why is a function used for a task? To cut down on the amount of detail in your main program (encapsulation). l Can one function call another function? Yes l Can a function even call itself? Yes, that is called recursion. It is very useful and requires special care in writing.

24 More Questions l Does it make any difference what names you use for parameters? NO. Just use them in function body. l Do parameter names and argument names have to be the same? NO. l What is the advantage of that? It seems confusing.

25 Functions are written to specifications l the specifications state the return type, the parameter types, whether any parameters are “outgoing,” and what task the function is to perform with its parameters l the advantage is that teamwork can occur without knowing what the argument identifiers (names) will be

26 Write prototype and function definition for l a void function called GetRating( ) with one reference parameter of type char l the function repeatedly prompts the user to enter a character at the keyboard until one of these has been entered: E, G, A, P to represent Excellent, Good, Average, Poor

27 void GetRating( char& ); // prototype void GetRating (char& letter) {cout << “Enter employee rating.” << endl; cout << “Use E, G, A, or P : ” ; cin >> letter; while ( (letter != ‘E’) && (letter != ‘G’) && (letter != ‘A’) && (letter != ‘P’) ) { cout << “Rating invalid. Enter again: ”; cin >> letter; }

28 #include void GetRating( char& ); // prototype using namespace std; int main( ) { char rating; rating = ‘X’; GetRating(rating);// call cout << “That was rating = “ << rating << endl; return 0; }

29 Designing a function l Design interface, design implementation l Hiding the code - not in main l Interface - specification of what it does and how it is called - outside world sees - what not how l Interface - precondition/postcondition

30 Designing a function l Implementation - supports the interface - satisfy postcondition with the precondition - algorithm l encapsulation - changes do not affect main l identifiers must match in number, type position l precondition must be true for function to work correctly l caller ensures precondition, called ensures postcondition

31 Documenting l The direction of the data flow - between the function and its caller l incoming - one way into function l outgoing - one way out of the function l incoming/outgoing - in and out of function

32 Data Flow Determines Passing-Mechanism Incoming /* in */ Pass-by-value Outgoing /* out */ Pass-by-reference Incoming/outgoing Pass-by-reference /* inout */ Parameter Data Flow Passing-Mechanism

33 An Assertion l is a truth-valued statement--one that is either true or false (not necessarily in C++ code) EXAMPLES studentCount > 0 sum is assigned && count > 0 response == ‘y’ or ‘n’ 0.0 <= deptSales <= beta == entry * 2

34 Preconditions and Postconditions l the precondition is an assertion describing everything that the function requires to be true at the moment the function is invoked l the postcondition describes the state at the moment the function finishes executing l the caller is responsible for ensuring the precondition, and the function code must ensure the postcondition FOR EXAMPLE...

35 Function with Postconditions void GetRating ( /* out */ char& letter) // Precondition: None // Postcondition: User has been prompted to enter a character // && letter == one of these input values: E,G,A, or P { cout << “Enter employee rating.” << endl; cout << “Use E, G, A, or P : ” ; cin >> letter; while ( (letter != ‘E’) && (letter != ‘G’) && (letter != ‘A’) && (letter != ‘P’) ) { cout << “Rating invalid. Enter again: ”; cin >> letter; }

36 Function with Preconditions and Postconditions void GetRoots( /* in */ float a, /* in */ float b, /* in */ float c, /* out */ float& root1, /* out */ float& root2 ) // Precondition: a, b, and c are assigned // && a != 0 && b*b - 4*a*c != 0 // Postcondition: root1 and root2 are assigned // && root1 and root2 are roots of quadratic with coefficients a, b, c { float temp; temp = b * b * a * c; root1 = (-b + sqrt(temp) ) / ( 2.0 * a ); root2 = (-b - sqrt(temp) ) / ( 2.0 * a ); return; }

37 Function with Preconditions and Postconditions void Swap( /* inout */ int& firstInt, /* inout */ int& secondInt ) // Precondition: firstInt and secondInt are assigned // Postcondition: firstInt == // && secondInt == { int temporaryInt ; temporaryInt = firstInt ; firstInt = secondInt ; secondInt = temporaryInt ; }

38 Assert library function l Executable assertions l header file l if true nothing happens, if false - execution of program terminates with error message l only convenient for developing program - never given to user

39 l Assign #14 - pg , programming warm-up exercises 1, 3, 11; l Assign #15 - exam prep exercises 1, 2, 4, 5, 7, 8, 9, 10.