chapter 7 functions
DESCRIPTION
Chapter 7 Functions. Chapter 7 Topics. Review of functions VERY IMPORTANT NEW TOPIC: The difference between passing parameters by value, and passing parameters by reference. Functions. every C++ program must have a function called main program execution always begins with function main - PowerPoint PPT PresentationTRANSCRIPT
![Page 1: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/1.jpg)
Chapter 7
Functions
![Page 2: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/2.jpg)
2
Chapter 7 Topics
Review of functions VERY IMPORTANT NEW TOPIC:
The difference between passing parameters by value, and passing parameters by reference
![Page 3: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/3.jpg)
3
Functions
every C++ program must have a function called main
program execution always begins with function main
any other functions are subprograms and must be called
![Page 4: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/4.jpg)
4
Function Calls
One function calls another by using the name of the called function with parentheses ( ) enclosing an argument list.
A function call temporarily transfers control from the calling function to the called function.
![Page 5: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/5.jpg)
5
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
![Page 6: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/6.jpg)
6
Two Parts of Function Definition
int Cube ( int n ) heading{
body return n * n * n ;
}
![Page 7: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/7.jpg)
7
What is in a heading?
int Cube ( int n )
type of value returned name of
function
parameter list
![Page 8: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/8.jpg)
8
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.
int Cube( int ); // prototypeOR: int Cube (int x);You can put in any variable name(optional)
![Page 9: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/9.jpg)
9
Prototypes
Prototypes of system functions (such as cin, cout, sqrt, open) are contained in header files (like iostream, cmath, fstream)
You include the proper header file for system functions
You must provide prototypes for your functions
![Page 10: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/10.jpg)
10
To Compile Successfully,
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)
![Page 11: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/11.jpg)
11
When a function is called,
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.
![Page 12: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/12.jpg)
12
#include <iostream>int Cube ( int ) ; // prototypeusing 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 ;}
![Page 13: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/13.jpg)
13
A C++ function can return
at most 1 value of the type which was specified (called the return type) in its heading and prototype
but, a void-function cannot return any value
![Page 14: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/14.jpg)
14
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.”
![Page 15: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/15.jpg)
15
parameter
void DisplayMessage( int index )
{if ( index < 35 )
cout << “Pleasant”;else if ( index <= 60 )
cout << “Unpleasant”;else
cout << “Health Hazard”; // return statement optional with void function}
![Page 16: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/16.jpg)
16
#include <iostream>void DisplayMessage (int); // prototype//void DisplayMessage (int anyName); // legalusing namespace std;
int main ( ) argument{
int pollutionIndex;
cout << “Enter air pollution index”;cin >> pollutionIndex;DisplayMessage(pollutionIndex); // callreturn 0;
}
The Rest of the Program
16
![Page 17: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/17.jpg)
17
return;
Causes control to leave the function and immediately return to the calling block leaving any subsequent statements in the function body unexecuted
There can be multiple return statements in a function
A void function does not need a return statement
![Page 18: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/18.jpg)
18
void DisplayMessage( int index ){
if ( index < 35 ) {cout << “Pleasant”;
return; }
if ( index <= 60 ) {cout << “Unpleasant”;
return; }
cout << “Health Hazard”; return;}
Example of using multiple returns
18
![Page 19: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/19.jpg)
19
Program with Several Functions
Square function
Cube function
function prototypes
main function
![Page 20: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/20.jpg)
20
Value-returning Functions
#include <iostream>
int Square ( int ) ; // prototypesint Cube ( int ) ;using namespace std;
int main ( ){ cout << “The square of 27 is “
<< Square (27) << endl; // function call cout << “The cube of 27 is “ << Cube (27) << endl; // function call
return 0;}
20
![Page 21: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/21.jpg)
21
Rest of Program
int Square ( int n ) // header and body{ return n * n;}
int Cube ( int n ) // header and body{ return n * n * n;}
![Page 22: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/22.jpg)
22
A void function call stands alone
#include <iostream>
void DisplayMessage ( int ) ; // prototype
using namespace std;
int main ( ) argument{ DisplayMessage(15); // function call
cout << “Good Bye“ << endl;
return 0;} 22
![Page 23: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/23.jpg)
23
A void function does NOT return a value
parameter void DisplayMessage ( int n ){ cout << “I have liked math for “ << n << “ years” << endl ;
return ; // optional for void function}
![Page 24: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/24.jpg)
24
Pass by value or reference
Pass by value: The called function gets a copy of the variable. The variable in the caller cannot be changed.
Pass by reference: The called function gets the address (a reference) to the variable. If the called function changes the variable, it is changed in the caller.
![Page 25: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/25.jpg)
25
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.
![Page 26: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/26.jpg)
26
When to Use Reference Parameters
reference parameters should be used when you want your called function to change the value of a variable in the calling function
![Page 27: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/27.jpg)
27
Using a Reference Parameter
is like giving someone the key to your home
the key can be used by the other person to change the contents of your home!
![Page 28: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/28.jpg)
28
MAIN PROGRAM MEMORY
25
4000
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.
![Page 29: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/29.jpg)
29
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.
25
4000
age
![Page 30: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/30.jpg)
30
Pass-by-reference is also called . . .
pass-by-address, or
pass-by-location
![Page 31: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/31.jpg)
31
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 (a,b, c variables of the quadratic equation). The last 2 are reference parameters of type float (the roots).
![Page 32: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/32.jpg)
32
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
![Page 33: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/33.jpg)
33
void GetRoots( float a, float b, float c,
float& root1, float& root2) { float temp; // local variable temp = b * b - 4.0 * a * c; if (temp >= 0) { // if real root root1=(-b + sqrt(temp) ) / ( 2.0 * a ); root2=(-b - sqrt(temp) ) / ( 2.0 * a ); } else { root1 = 999; root2 = -999; } return;}
Function Definition
33
![Page 34: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/34.jpg)
34
#include <iostream>#include <cmath>void GetRoots(float, float, float, float&, float&);using namespace std;int main ( ){ float a, b, c, first, second; int count = 0; cout << "Enter a,b,c " <<endl; cin >> a >> b >> c; while ( a != 0) {
GetRoots(a, b, c, first, second); //call cout << "For variables: "; cout << a << " " << b << " " << c << endl;
cout << "Roots: " ; cout << first << " " << second << endl;
cout << "Enter a,b,c " <<endl; cin >> a >> b >> c; } return 0;}
34
![Page 35: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/35.jpg)
35
Calling a function to swap variables// Will Swap swap Number1,Number 2?int main() {int Number1, Number2;cin >> Number1 >> Number2;if (Number1 > Number2) {
Swap(Number1, Number2);// Swap?}cout << "The numbers swapped:" << Number1 << ", " << Number2 << endl;return 0;}
![Page 36: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/36.jpg)
36
Will Swap swap?
IF parameters passed by value: NO If parameters passes by reference:
YES
![Page 37: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/37.jpg)
37
Using Pass by Value
void Swap(int a, int b) {
int Temp = a;
a = b;
b = Temp;
return;
}
![Page 38: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/38.jpg)
Doesn’t change the caller’s variables!
![Page 39: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/39.jpg)
39
Same Call to Swap But…void Swap(int &a, int &b); int main() {int Number1, Number2;cin >> Number1 >> Number2;if (Number1 > Number2) {
Swap(Number1, Number2); }cout << "The numbers in sorted order: " << Number1 << ", " << Number2 << endl;return 0;}
![Page 40: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/40.jpg)
40
Swap defined as Pass by Reference
void Swap(int &a, int &b) {
int Temp = a;
a = b;
b = Temp;
return;
}
Return statement notnecessary for void functions
Passed by reference -- in aninvocation the address
is given ratherthan a copy
![Page 41: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/41.jpg)
41
Pass-by-value
CALLINGFUNCTION
FUNCTION CALLED
“incoming”
value ofargument
![Page 42: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/42.jpg)
42
Pass-by-reference
CALLINGFUNCTION FUNCTION
CALLED
“incoming”
original value ofPassed argument
“outgoing”
changed value ofpassed argument
![Page 43: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/43.jpg)
43
Returning a value from function
The returned value replaces the function name:
int Square1(int n); // prototype
…..
// Use function name like any int
temp = Square1(b) - 4 * a* c;
![Page 44: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/44.jpg)
44
Pass by reference
Pass by reference is sharing the variable
void Square2(int & n); // prototype
….
Square2(b); // Square modifies b in caller
temp = b - 4*a*c;
![Page 45: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/45.jpg)
45
Square return vs. pass by reference
int Square1(int n) // Square returns a value{ return n*n;}// Square modifies n in callervoid Square2(int &n) {n = n*n;}
![Page 46: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/46.jpg)
46
Questions
Why is a function used? To cut down on the amount of detail in your main
program (encapsulation). So that it can be called multiple times
Can one function call another function?
Yes Can a function even call itself?
Yes, that is called recursion. It is very useful (covered in CS 215).
![Page 47: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/47.jpg)
47
More Questions
Does it make any difference what names you use for passed parameters?NO. Just use them in function body.
Do the calling function and the called function have to use the same names for passed parameters?NO. Each function should use names meaningful to itself.
![Page 48: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/48.jpg)
48
Functions are written to specifications
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
the advantage is that teamwork can occur without knowing what the argument identifiers (names) will be
![Page 49: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/49.jpg)
49
Write prototype and function definition for
a void function called GetRating( ) with one reference parameter of type char
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
![Page 50: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/50.jpg)
50
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;
}
} 50
![Page 51: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/51.jpg)
51
#include <iostream>
void GetRating( char& ); // prototype
using namespace std;
int main( ){ char rating; rating = ‘X’;
GetRating(rating); // call
cout << “That was rating = “ << rating << endl;
return 0;}
51
![Page 52: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/52.jpg)
52
Preconditions and Postconditions
the precondition is an assertion describing everything that the function requires to be true at the moment the function is invoked
the postcondition describes the state at the moment the function finishes executing
the caller is responsible for ensuring the precondition, and the function code must ensure the postcondition
FOR EXAMPLE . . .
![Page 53: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/53.jpg)
53
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
53
![Page 54: Chapter 7 Functions](https://reader036.vdocuments.mx/reader036/viewer/2022062321/56812b88550346895d8fa499/html5/thumbnails/54.jpg)
54
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 passed
// && a != 0
// Postcondition: root1 and root2 are returned
// root1 and root2 are roots of quadratic with coefficients
// a, b, c
// If imaginary root, roots set to 999 and -999
54