Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Chapter 3 - Functions
Outline
3.1 Introduction
3.2 Program Components in C++
3.3 Math Library Functions
3.4 Functions
3.5 Function Definitions
3.6 Function Prototypes
3.7 Header Files
3.8 Random Number Generation
3.9 Example: A Game of Chance and Introducing enum
3.10 Storage Classes
3.11 Scope Rules
3.12 Recursion
3.13 Example Using Recursion: The Fibonacci Series
3.14 Recursion vs. Iteration
3.15 Functions with Empty Parameter Lists
Chapter 3 - Functions
Outline
3.16 Inline Functions
3.17 References and Reference Parameters
3.18 Default Arguments
3.19 Unary Scope Resolution Operator
3.20Function Overloading
3.21Function Templates
3.1
Introduction
3.2
Programs written by
combining new functions with prepackaged
functions in the C++ standard library.
The standard library provides a rich collection
of functions.
3.2
3.2
Function definitions
3.3
Example
cout << sqrt( 900.0 );
3.3
Variables
sqrt( x );
Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );
3.4
Functions
Functions
Allow the programmer to modularize a program
Local variables
Known only in the function in which they are defined
All variables declared in function definitions are local
variables
Parameters
10
3.5
Function Definitions
Formatforfunctiondefinition:
returnvaluetypefunctionname( parameterlist )
{
declarationsandstatements
}
Example:
11
7
8 int square( int );
9
10 int main()
11 {
12
for ( int x = 1; x <= 10; x++ )
13
cout << square( x ) << " ";
14
15
cout << endl;
The function square is
16
return 0;
for x = 1, 2, 10
17 }
18
19 // Function definition
20 int square( int y )
Function definition
21 {
22
return y * y;
23 }
1
16
25
36
49
64
81
100
Outline
1. Function prototype
2. Loop
3. Function definition
called
Program Output
12
3.6
Function Prototypes
Function prototype
Function name
Parameters
Information, the function takes in
Return type
Takes in 3 ints
Returns an int
2000 Prentice Hall, Inc. All rights reserved.
13
// function
6 int main()
7 {
8
int a, b, c;
9
10
11
12
13
14
15
cout << "Maximum is: " << maximum( a, b, c ) <<
endl;
16
17
return 0;
18 }
Outline
1. Function prototype
(3 parameters)
2. Input values
2.1 Call function
14
Outline
Program Output
15
3.7
Header Files
Header files
Contain function prototypes for library functions
Load with #include <filename.h>
Example:
<stdlib.h> , <math.h>, etc.
#include "filename.h"
16
3.8
rand function
i = rand();
Load <stdlib.h>
srand function
Jumps to a seeded location in a "random" sequence
srand( seed );
srand( time( 0 ) ); //must include <time.h>
time( 0 )
The time at which the program was compiled
17
3.8
Scaling
Reduces random number to a certain range
Modulus ( % ) operator
Reduces number between 0 and RAND_MAX to a number
between 0 and the scaling factor
Example
i = rand() % 6 + 1;
Generates a number between 1 and 6
1
2
3
%
4
8 #include <iomanip.h>
9
10 #include <cstdlib>
Outline
1. Define loop
2. Output random
number
11
18
Notice rand() % 6 .
This returns a number between 0 and 5 (scaling).
12 int main()
13 {
Add 1 to get a number between 1 and 6.
14
for ( int i = 1; i <= 20; i++ ) {
15
16
17
18
19
20
21
22 }
return 0;
5
2
5
5
5
4
3
1
5
5
2
6
5
5
1
4
Program Output
19
1. Initialize seed
4 #include <cstdlib.h>
5 int main()
6 {
7
unsigned seed;
8
9
10
11
12
13
14
15
16
if ( i % 5 == 0 )
cout << endl;
17
18
19 }
return 0;
Outline
3. Generate and
output random
numbers
Enter seed: 67
1
5
6
6
5
3
1
1
4
2
2
5
6
1
4
4
3
4
1
1
4
2
Enter seed: 67
1
6
5
5
6
3
2000 Prentice Hall, Inc. All rights reserved.
Program Output
Outline
#include <iostream.h>
#include <stdlib.h>
fig05_08.c
(Part 1 of 3)
5
6
int main()
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
switch ( face ) {
Outline
25
26
27
case 1:
/* rolled 1 */
28
++frequency1;
break ;
29
30
31
case 2:
/* rolled 2 */
32
++frequency2;
break ;
33
34
35
case 3:
/* rolled 3 */
36
++frequency3;
break ;
37
38
39
case 4:
/* rolled 4 */
40
++frequency4;
break ;
41
42
43
case 5:
/* rolled 5 */
44
++frequency5;
break ;
45
fig05_08.c
(Part 2 of 3)
45
46
47
48
49
50
51
52
53
case 6 :
/* rolled 6 */
++frequency6;
break;
} /* end switch */
} /* end for */
Outline
fig05_08.c
(Part 3 of 3)
<<
<<
<<
<<
<<
<<
<<
\nFace<< setw( 13
1<< setw( 13 )
2<< setw( 13 )
3<< setw( 13 )
4<< setw( 13 )
5<< setw( 13 )
6<< setw( 13 )
) << Frequency\n;
<< frequency1<<\n;
<< frequency2<<\n;
<< frequency3<<\n;
<< frequency4<<\n;
<< frequency5<<\n;
<< frequency6<<\n;
61
62
return 0 ; /* indicates successful termination */
63
64 } /* end main */
Program
Output
2000 Prentice Hall, Inc. All rights reserved.
Outline
Face
1
2
3
4
5
6
Frequency
1003
1017
983
994
1004
999
24
Status enumVar;
enumVar = WON;
enumVar = 1;
cout<<enumVar;
//
//
//
//
create variable
set equal to WON
ERROR
What will print?
25
Introducing enum(II)
Enumeration constants can have values pre-set
26
What is an identifier?
An identifier is used for any variable, function, data definition etc.
Scope
Where object is referenced in program
Linkage
Where an identifier is known (i.e, which source file?)
auto
register
extern
mutable
static
27
register Storage Class: The register storage class is used to define local variables that
require quick access such as counters.
{
register int miles;
}
static Storage Class: The static storage class instructs the compiler to keep a local
variable in existence during the life-time of the program instead of creating and destroying
it each time it comes into and goes out of scope.
void fun() {
static int i = 10;
i++; cout << i; }
int main() {
fun(); // Output = 11
fun(); // Output = 12
fun(); // Output = 13 }
2000 Prentice Hall, Inc. All rights reserved.
28
global variable or function, which will be used in other files also, then extern will
be used in another file to give reference of defined variable or function.
29
Function scope
Can only be referenced inside a function body
Block scope
Declared inside a block. Begins at declaration, ends at }
Variables, function parameters (local variables of function)
Outer blocks hidden from inner blocks if same variable name
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
30
Outline
1. Function prototypes
void a( void );
void b( void );
void c( void );
// function prototype
// function prototype
// function prototype
int x = 1;
// global
int main()
{
int x = 5;
cout << "local x in outer scope of main is " << x << endl;
{
int x = 7;
cout << "local x in inner scope of main is " << x << endl;
// end new scope
3. Output results
cout << "local x in outer scope of main is " << x << endl;
a();
// a has automatic local x
b();
// b has static locallocal
x
x in outer scope of main is 5
c();
// c uses global x
local x in inner scope of main is 7
a();
// a reinitializes automatic
local
x scope of main is 5
local x in
outer
b();
// static local x retains its previous value
c();
// global x also retains its value
2000 Prentice Hall, Inc. All rights reserved.
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
31
}
void a( void )
{
int x = 25;
cout <<
<<
++x;
cout <<
<<
Outline
}
void b( void )
{
static int x = 50;
cout <<
<<
++x;
cout <<
<<
}
void c( void )
{
cout << endl << "global x is " << x
<< " on entering c" << endl;
x *= 10;
cout << "global x is " << x << " on exiting c" << endl;
} 2000 Prentice Hall, Inc. All rights reserved.
global x is 1 on entering c
global x is 10 on exiting c
32
local x in outer scope of main is 5
local x in inner scope of main is 7
local x in outer scope of main is 5
local x in a is 25 after entering a
local x in a is 26 before exiting a
local static x is 50 on entering b
local static x is 51 on exiting b
global x is 1 on entering c
global x is 10 on exiting c
local x in a is 25 after entering a
local x in a is 26 before exiting a
local static x is 51 on entering b
local static x is 52 on exiting b
global x is 10 on entering c
global x is 100 on exiting c
local x in main is 5
Outline
Program Output
#include<iostream.h>
#include<conio.h>
int x = 5;
void fun1();
void fun2();
void fun3(int x, int y);
void main(){
clrscr(); int x=10; int y = -1;
cout<<"\nmain( ): x: "<<x;
for (int i = 20; i <= 25; i++ ){
int x = i ;
cout<<"\nfor loop: x: "<<x;
}
cout<<"\nmain( ): x: "<<x;
fun1();
fun1(
cout<<"\nmain( ): x: "<<x;
fun2( );
fun2(
fun1( );
fun1(
fun2( );
fun2(
fun3(x,y);
cout<<"\n\nmain( ): x: "<<x;
cout<<"\n
y: "<<y;
getch();
}
2000 Prentice Hall, Inc. All rights reserved.
main( ): x: 10
for loop: x: 20
for loop: x: 21
for loop: x: 22
for loop: x: 23
for loop: x: 24
for loop: x: 25
): x: 20
main( ): x: 10
y: 6
main( ): x: 10
): x: 5
): x: 20
): x: 5
y: 9
main( ): x: 10
y: -1
35
3.12 Recursion
Recursive functions
Are functions that call themselves
Can only solve a base case
If not base case, the function breaks the problem into a
slightly smaller, slightly simpler, problem that resembles the
original problem and
Launches a new copy of itself to work on the smaller problem,
slowly converging towards the base case
Makes a call to itself inside the return statement
Eventually the base case gets solved and then that value
works its way back up to solve the whole problem
36
3.12 Recursion
Example: factorial
n! = n * ( n 1 ) * ( n 2 ) * * 1
Recursive relationship ( n! = n * ( n 1 )! )
5! = 5 * 4!
4! = 4 * 3!
Recursion
void print(int n)
{
if (n<1) return;
cout<<n;
print(n-1);
}
Recursion unrolled
What would be the output of print(5)?
print(5)
5 <1 ?
cout<<n;
5
print(4)
4 <1 ?
cout<<n;
4
print(3)
3 <1 ?
cout<<n; 3
print(2)
2<1 ?
cout<<n; 2
print(1)
1 <1 ?
cout<<n; 1
print(0)
0<1
return;
Recursion
void print(int n)
{
if (n<1) return;
print(n-1);
cout<<n;
}
Recursion unrolled
What would be the output of print(5)?
print(5)
5 <1 ?
print(4)
(4 <1) ?
print(3)
(3 <1) ?
print(2)
(2<1) ?
print(1)
(1 <1) ?
print(0)
(0 < 1) return
cout<<n; 1
cout<<n;
2
cout<<n; 3
cout<<n;
4
cout<<n; 5
Recursion
void print(int n)
{
if (n<1) {}
else
cout<<n;
print(n-1);
}
42
Recursive relationship ( n! = n * ( n 1 )! )
5! = 5 * 4!
4! = 4 * 3!
43
n = n*i;
return n;
}
int main(){
cout << factorial(5);
return 0;
}
44
return
return
f(1)
return1
f(2)
f(0)
return0
f(1)
return1
45
f(3)
return
return
f(1)
return1
f(2)
f(0)
f(1)
return1
return0
46
47
Outline
1. Function prototype
4 unsigned long fibonacci( unsigned long );
5 int main()
1.1 Initialize variables
6 {
7
unsigned long result, number;
2. Input an integer
8
2.1 Call function fibonacci
9
cout << "Enter an integer: ";
10
cin >> number;
2.2 Output results.
11
result = fibonacci( number );
12
cout << "Fibonacci(" << number << ") = " << result
3. Define fibonacci
13
return 0;
<< endl;
recursively
14 }
15
16 // Recursive definition of function fibonacci
Only the base cases return values. All
17 unsigned long fibonacci( unsigned long other
n ) cases call the fibonacci
18 {
function again.
19
if ( n == 0 || n == 1 ) // base case
20
return n;
21
else
// recursive case
22
return fibonacci( n - 1 ) + fibonacci( n - 2 );
23 }
Enter an integer: 0
Fibonacci(0) = 0
Enter an integer: 1
Fibonacci(1) = 1
Enter an integer: 2
Fibonacci(2) = 1
Enter an integer: 3
Fibonacci(3) = 2
Enter an integer: 4
Fibonacci(4) = 3
Enter an integer: 5
Fibonacci(5) = 5
Enter an integer: 10
Fibonacci(10) = 55
Enter an integer: 6
Fibonacci(6) = 8
Enter an integer: 20
Fibonacci(20) = 6765
Enter an integer: 30
Fibonacci(30) = 832040
Enter an integer: 35
Fibonacci(35) = 9227465
48
Outline
Program Output
49
Termination
Iteration: loop condition fails
Recursion: base case recognized
50
51
int main()
{
function1();
function2();
return 0;
Outline
1. Function prototypes
(take no
arguments)
2. Call the functions
3. Function definitions
}
void function1()
{
cout << "function1 takes no arguments" << endl;
}
void function2( void )
{
cout << "function2 also takes no arguments" << endl;
Program Output
}
function1 takes no arguments
function2 also takes no arguments
52
inline functions
Example 1:
inline double cube( const double s )
{ return s * s * s; }
Example 2
53
Call by reference
Function can directly access data
Changes affect original
25
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 agein the calling
block; it is still 25 when you return
Additional Terms
Pass-by-reference
is also called . . .
pass-by-address, or
pass-by-location
Pass-by-value
incoming
value of
argument
CALLING
BLOCK
FUNCTION
CALLED
Pass-by-reference
incoming
original value of
argument
CALLING
BLOCK
FUNCTION
CALLED
outgoing
changed value of
argument
OR,
Pass-by-reference
OR argument
has no value yet
when call occurs
CALLING
BLOCK
FUNCTION
CALLED
outgoing
new value of
argument
60
// with references.
Outline
#include <iostream.h>
int squareByValue( int );
void squareByReference( int & );
1. Function prototypes
1.1 Initialize variables
int main()
{
int x = 2, z = 4;
cout << "x = " << x << " before squareByValue\n"
<< "Value returned by squareByValue: "
<< squareByValue( x ) << endl
<< "x = " << x << " after squareByValue\n"<<endl;
cout << "z = " << z << " before squareByReference" <<
endl;
squareByReference( z );
cout << "z = " << z << " after squareByReference" <<
endl;
return 0;
return a *= a;
2. Print x
61
void squareByReference( int &cRef )
Outline
cRef *= cRef;
}
x = 2 before squareByValue
Value returned by squareByValue: 4
x = 2 after squareByValue
z = 4 before squareByReference
z = 16 after squareByReference
Outline
Example of Pass-by-Reference
Outline
// Prototype
voidGetRoots(float,float,float,
float&,float&);
Now write the function definition using this information
Outline
Function Definition
voidGetRoots(floata,floatb,floatc,
float&root1,float&root2)
{
floattemp;
//Localvariable
temp=b*b4.0*a*c;
root1=(b+sqrt(temp))/(2.0*a);
root2=(bsqrt(temp))/(2.0*a);
return;
}
64
2000 Prentice Hall, Inc. All rights reserved.
65
66
Outline
int boxVolume( int length = 1, int width = 1, int height = 1 ); 1. Function prototype
int main()
{
cout<< "The default box volume is: " << boxVolume()
<< "\n\nThe volume of a box with length 10,\n"
<< "width 1 and height 1 is: " << boxVolume( 10 )
<< "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height 1 is: " << boxVolume( 10, 5 )
<< "width 5 and height 2 is: " << boxVolume( 10, 5, 2 ) 2.3 Print with all
<< endl;
20
return 0;
}
// Calculate the volume of a box
int boxVolume( int length, int width, int height )
{
return length * width * height;
}
2000 Prentice Hall, Inc. All rights reserved.
parameters.
3. Function definition
67
The default box volume is: 1
Program Output
Outline
68
#include <iostream>
4
5
using std::cout;
using std::endl;
69
7
8
Outline
1. Define overloaded
function
2. Call function
9
10 double square( double y ) { return y * y; }
11
12 int main()
13 {
14
15
16
<< endl;
17
18
return 0;
19 }
Program Output
70
71
// Fig. 3.24: fig03_24.cpp
// Using the unary scope resolution operator
Outline
1. Define variables
#include <iostream.h>
2. Print variables
#include <iomanip.h>
int main()
{
const float PI = static_cast< float >( ::PI );
cout << setprecision( 20 )
<< "
Program Output
72
>
typename T >
)
value1;
// function template
#include <iostream.h>
template <class T>
T GetMax (T a, T b) {
T result;
result = (a>b)? a : b;
return (result);
}
int main () {
int i = 5, j = 6, k;
long l = 10, m = 5, n;
k = GetMax <int>(i , j);
n = GetMax <long>(l , m);
cout << k << endl;
cout << n << endl;
return
2000 Prentice
Hall, Inc. 0;
All }
rights reserved.