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.

Slides:



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

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Dale/Weems/Headington
1 Lecture 10 Chapter 7 Functions Dale/Weems/Headington.
1 CIS 205 Practice Test George Lamperti A word that has a predefined meaning in a C++ program and cannot be used as a variable name is known as.
1 Lecture 6 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
Chapter 6: User-Defined Functions I
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
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.
Chapter 6: User-Defined Functions I
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Functions Modules in C++ are called functions and classes
Chapter 7 Functions.
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&
Chapter 6 Looping.
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 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
1 C++ Syntax and Semantics, and the Program Development Process.
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.
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.
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.
CPS120: Introduction to Computer Science Functions.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
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.
1 Looping. 2 Chapter 6 Topics  While Statement Syntax  Phases of Loop Execution  Two Types of Loops: Count-Controlled Loops &Event-Controlled Loops.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
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.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
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.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
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 Chapter 9 Scope, Lifetime, and More on Functions.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
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.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
Chapter 8 Functions.
Modular Programming with Functions
Chapter 6: User-Defined Functions I
User-Defined Functions
Chapter 9 Scope, Lifetime, and More on Functions
User Defined Functions
Introduction to Problem Solving and Programming
Introduction to Problem Solving and Programming
COMS 261 Computer Science I
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:

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

Chapter 8 Topics l Differences between Value Parameters and Reference Parameters l Using Local Variables in a Function l Function Preconditions and Postconditions

Functions Every C++ program must have a function called main Program execution always begins with function main l Any other functions are subprograms that must be explicitly called

Function Calls One function calls another by using the name of the called function followed by ()s that enclose an argument list, which may be empty A function call temporarily transfers control from the calling function to the called function

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

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

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

Prototypes A prototype looks like a heading but must end with a semicolon, and its parameter list needs only to contain the type of each parameter int Cube(int ); // Prototype

Function Calls When a function is called, temporary memory is allocated for:  its value parameters;  any local variables; and  for the function’s name if the return type is not void Flow of control then passes to the first statement in the function’s body

Function Calls The called function’s statements are executed until a return statement (with or without a return value) or the closing brace of the function body is encountered Then control goes back to where the function was called

#include int Cube(int);// prototype using namespace std; void main() { int yourNumber; 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; } arguments

Successful Function Compilation Before a function is called in your program, the compiler must have previously processed either:  the function’s prototype or  the function’s definition (heading and body)

Return Values In C++, a value-returning function returns in its identifier one value of the type specified in its heading and prototype (called the return type) In contrast, a void-function cannot return any value in its identifier

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

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

#include void DisplayMessage(int); // Prototype using namespace std; int main() { The Rest of the Program

The Rest of the Program, cont... cout << “Enter air pollution index”; cin >> pollutionIndex; DisplayMessage(pollutionIndex); // Call return 0; } argument

Return Statement return; // No value to return l Is valid only in the body block of a void function l Causes control to leave the function and immediately return to the calling block, leaving any subsequent statements in the function body unexecuted

Header Files Header Files contain n Named constants like const int INT_MAX = 32767; n Function prototypes like float sqrt(float); n Classes like string, ostream, istream n Objects like cin, cout

Program with Several Functions Square function Cube function function prototypes main function

Value-Returning Functions #include int Square(int); // Prototypes int Cube(int); using namespace std; int main() { cout << “The square of 27 is “ << Square(27) << endl; cout << “The cube of 27 is “ << Cube(27) << endl; return 0; } function calls

Rest of Program int Square(int n)// Header and body { return n * n; } int Cube(int n) // Header and body { return n * n * n; }

Void Functions Stand Alone #include void DisplayMessage(int);// Prototype using namespace std; int main() argument { DisplayMessage(15);// Function call cout << “Good Bye“ << endl; return 0; }

Parameters parameter void DisplayMessage(int n) { cout << “I have liked math for “ << n << “ years” << endl; return; }

Parameter List A parameter list is the means used for a function to share information with the block containing the call

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

Different Terms Some C++ books l Use the term “actual parameters” for arguments l Those books then refer to parameters as “formal parameters”

Value Parameter Reference Parameter The value of the argument (25) 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 29

Default Parameters l Simple types, structs, and classes are value parameters by default l Arrays are always reference parameters l Other reference parameters are marked as such by having an ampersand (&) beside their type

Use of Reference Parameters  Reference parameters should be used when the function is to assign a value to, or  When the function is to change the value of, a variable from the calling block without an assignment statement in the calling block

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!

Main Program Memory age If you pass a copy of age to a function, it is called “pass-by-value” and the function will not be able to change the contents of age in the calling block; it is still 25 when you return

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 in the calling block; it could be 23 or 90 when you return age

Additional Terms l Pass-by-reference is also called... n pass-by-address, or n pass-by-location Can you explain why?

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.

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

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 38

#include // Prototype void GetRoots(float, float, float, float&, float&); using namespace std; void main() {

ifstream myInfile; ofstream myOutfile; float a, b, c, first, second; int count = 0; // Open files while(count < 5) { myInfile >> a >> b >> c; // Call GetRoots(a, b, c, first, second); myOutfile << a << b << c << first << second << endl; count++; } // Close files }

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

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

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

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

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

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

Functions are written to specifications l The specifications state: l the return type; l the parameter types; l whether any parameters are “outgoing” and l 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

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

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

An Assertion An assertion 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

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

Function with Postconditions void GetRating(/* out */ char& letter) // Precondition: None // Postcondition: User has been // prompted to enter a letter // && letter == one of these // input values: E,G,A, or P

Function with Postconditions, continued { 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; }

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

Function with Preconditions and Postconditions, continued... { float temp; temp = b * b * a * c; root1 =(-b + sqrt(temp)) /(2.0 * a); root2 =(-b - sqrt(temp)) /(2.0 * a); return; }

Another Function with Preconditions and Postconditions void Swap( /* inout */ int& firstInt, /* inout */ int& secondInt) // Precondition: firstInt and secondInt // are assigned // Postcondition: firstInt == // && secondInt ==

Another Function with Preconditions and Postconditions, cont... { int temporaryInt; temporaryInt = firstInt; firstInt = secondInt; secondInt = temporaryInt; }