1 Lecture 10 Chapter 7 Functions Dale/Weems/Headington.

Slides:



Advertisements
Similar presentations
Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Advertisements

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
More on Functions Programming. COMP104 Lecture 19 / Slide 2 Passing Parameters by Reference l To have a function with multiple outputs, we have to use.
1 11/05/07CS150 Introduction to Computer Science 1 Functions Chapter 6, page 303.
1 Lecture 6 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Overview creating your own functions calling your own functions.
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.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Functions Modules in C++ are called functions and classes
Basic Elements of C++ Chapter 2.
Chapter 7 Functions.
Programming Functions: Passing Parameters by Reference.
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.
Call-by-Value vs. Call-by-Reference Call-by-value parameters are used for passing information from the calling function to the called function (input parameters).
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 Scope, Lifetime, and More on Functions. 2 Chapter 8 Topics  Local Scope vs. Global Scope of an Identifier  Detailed Scope Rules to Determine which.
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 9 Additional Control Structures Dale/Weems/Headington.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 5 Functions For All Subtasks. Void functions Do not return a value. Keyword void is used as the return type in the function prototype to show.
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.
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.
CPS120: Introduction to Computer Science Functions.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
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.
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.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
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.
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.
1 Scope Lifetime Functions (the Sequel) Chapter 8.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Functions CMSC 202. Topics Covered Function review More on variable scope Call-by-reference parameters Call-by-value parameters Function overloading Default.
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.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Chapter 8 Functions.
Modular Programming with Functions
Chapter Topics The Basics of a C++ Program Data Types
Bill Tucker Austin Community College COSC 1315
Basic Elements of C++.
Functions and an Introduction to Recursion
Basic Elements of C++ Chapter 2.
Chapter 9 Scope, Lifetime, and More on Functions
Additional Control Structures
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Functions and an Introduction to Recursion
Introduction to Problem Solving and Programming
Chapter 8 Functions.
CS1201: Programming Language 2
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 Lecture 10 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 l Using Function Arguments and Parameters l Differences between Value Parameters and Reference Parameters l Using Local Variables in a Function l Function Preconditions and Postconditions

3 Revision of Lecture 9 l Can a function call the main() function? l (yes, look at the following program: n #include n using namespace std; n void myown(); n void main() n {cout<<"I am going to call myown"<<endl; n myown();} n void myown() n {int mychoice; n cout >mychoice; n if (mychoice == 9) main();}

4 Revision of Lecture 9 l Why should we avoid calling main() from another function? l Is a variable or constant declared in main() accessible to other functions? l At what places do we use a function’s name in our program? l When calling a function with arguments, what should we check?

5 Revision of Lecture 9 l What is the benefit of using functions in our programs? l What is meant by hiding details? l What is meant by scope of variables? l Why should we avoid using the easiest type of variables i.e. global variables

6 Value Parameter Reference Parameter The value (25) of the argument is passed to the function when it is called. The memory address (4000) of the argument is passed to the function when it is called age In this case, the argument can be a variable identifier, constant, or expression. In this case, the argument must be a variable identifier. Argument in Calling Block

7 By default, parameters (of simple types like int, char, float, double) are always value parameters, unless you do something to change that. To get a reference parameter you need to place & after the type in the function heading and prototype.

8 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

9 Using a Reference Parameter l is like giving someone the key to your home l the key can be used by the other person to change the contents of your home!

10 MAIN PROGRAM MEMORY age If you pass only a copy of 25 to a function, it is called “pass-by-value” and the function will not be able to change the contents of age. It is still 25 when you return.

11 MAIN PROGRAM MEMORY BUT, if you pass 4000, the address of age to a function, it is called “pass- by-reference” and the function will be able to change the contents of age. It could be 23 or 90 when you return age

12 Pass-by-reference is also called... l pass-by-address, or l pass-by-location

13 Example of Pass-by-Reference We want to find 2 real roots for a quadratic equation with coefficients a,b,c. Write a prototype for a void function named GetRoots( ) with 5 parameters. The first 3 parameters are type float. The last 2 are reference parameters of type float.

14 void GetRoots ( float, float, float, float&, float& ); Now write the function definition using this information. This function uses 3 incoming values a, b, c from the calling block. It calculates 2 outgoing values root1 and root2 for the calling block. They are the 2 real roots of the quadratic equation with coefficients a, b, c. // prototype

15 void GetRoots( float a, float b, float c, float& root1, float& root2) { float temp; // local variable temp = b * b * a * c; root1 = (-b + sqrt(temp) ) / ( 2.0 * a ); root2 = (-b - sqrt(temp) ) / ( 2.0 * a ); return; } Function Definition

16 #include void GetRoots(float, float, float, float &, float & ); using namespace std; void main ( ) { float a, b, c, first, second; cin >> a >> b >> c; GetRoots(a, b, c, first, second); //call cout << a << b << c << first << second << endl; }

17 Pass-by-value CALLING BLOCK FUNCTION CALLED “incoming” value of argument

18 Pass-by-reference CALLING BLOCK FUNCTION CALLED “incoming” original value of argument “outgoing” changed value of argument OR,

19 Pass-by-reference CALLING BLOCK FUNCTION CALLED argument has no value yet when call occurs “outgoing” new value of argument

20 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

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

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

23 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

24 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

25 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; }

26 What is a driver? l It is a short main program whose only purpose is to call a function you wrote, so you can determine whether it meets specifications and works as expected. l write a driver for function GetRating( )

27 #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; }

28 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

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

30 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; }

31 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; }

32 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 ; }