0% found this document useful (0 votes)
9 views56 pages

Chapter 3

The document discusses functions in C++. It defines functions as modular pieces of a program that can be reused. Functions contain local variables and parameters. Parameters provide outside information to functions. Functions are defined with a return type, name, and parameter list. When called, functions get a copy of the arguments passed, perform operations, and return a value. Well-defined functions help divide programs into smaller, more manageable pieces.

Uploaded by

tasneem.dawahdeh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views56 pages

Chapter 3

The document discusses functions in C++. It defines functions as modular pieces of a program that can be reused. Functions contain local variables and parameters. Parameters provide outside information to functions. Functions are defined with a return type, name, and parameter list. When called, functions get a copy of the arguments passed, perform operations, and return a value. Well-defined functions help divide programs into smaller, more manageable pieces.

Uploaded by

tasneem.dawahdeh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 56

Outline

Intro to Programming

Chapter 3:
Functions

 2003 Prentice Hall, Inc.


All rights reserved.
2

Introduction

• Divide and conquer


– Construct a program from smaller pieces or components
– Each piece more manageable than the original program

 2003 Prentice Hall, Inc. All rights reserved.


3

Program Components in C++

• Modules: functions and classes


• Programs use new and “prepackaged” modules
– User-defined: programmer-defined functions, classes
– Prepackaged: from the standard library
• Functions invoked by function call
– Function name and information (arguments) it needs
• Function definitions
– Only written once
– Hidden from other functions

 2003 Prentice Hall, Inc. All rights reserved.


4

Math Library Functions

• Perform common mathematical calculations


– Include the header file <cmath>
• Functions called by writing
– functionName (argument);
or
– functionName(argument1, argument2, …);
• Example
cout << sqrt( 900.0 );
– sqrt (square root) function The preceding statement would
print 30
– All functions in math library return a double

 2003 Prentice Hall, Inc. All rights reserved.


5

Math Library Functions

• Function arguments can be


– Constants
• sqrt( 4 );
– Variables
• sqrt( x );
– Expressions
• sqrt( sqrt( x ) ) ;
• sqrt( 3 – 6*x );

 2003 Prentice Hall, Inc. All rights reserved.


6
Me th o d De sc rip tio n Exa m p le
ceil( x ) rounds x to the smallest integer ceil( 9.2 ) is 10.0
not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential function ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( x ) absolute value of x fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0
not greater than x floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992
point number
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x sin( 0.0 ) is 0
(x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0
(x in radians)
Fig . 3.2 Ma th lib ra ry fu n c tio n s.

 2003 Prentice Hall, Inc. All rights reserved.


7

Functions

• Functions
– Modularize a program
– Software reusability
• Call function multiple times
• Local variables
– Known only in the function in which they are defined
– All variables declared in function definitions are local
variables
• Parameters
– Local variables passed to function when called
– Provide outside information

 2003 Prentice Hall, Inc. All rights reserved.


8

Function Definitions

• Function prototype
– Tells compiler argument type and return type of function
– int square( int );
• Function takes an int and returns an int
– Explained in more detail later

• Calling/invoking a function
– square(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result

 2003 Prentice Hall, Inc. All rights reserved.


9

Function Definitions

• Format for function definition


return-value-type function-name( parameter-list )
{
declarations and statements
}
– Parameter list
• Comma separated list of arguments
– Data type needed for each argument
• If no arguments, use void or leave blank
– Return-value-type
• Data type of result returned (use void if nothing returned)

 2003 Prentice Hall, Inc. All rights reserved.


10

Function Definitions

• Example function
int square( int y )
{

return y * y;
}
• return keyword
– Returns data, and control goes to function’s caller
• If no data to return, use return;
– Function ends when reaches right brace
• Control goes to caller
• Functions cannot be defined inside other functions
• Next: program examples
 2003 Prentice Hall, Inc. All rights reserved.
11
1 // Fig. 3.3: fig03_03.cpp
2 // Creating and using a programmer-defined function.
Outline
3 #include <iostream>
4 Function prototype: specifies fig03_03.cpp
5 using std::cout; data types of arguments and (1 of 2)
6 using std::endl; return values. square
7
expects and int, and returns
8 int square( int ); // function prototype
an int.
9
10 int main()
11 { Parentheses () cause function
12 // loop 10 times and calculate and output
to be called. When done, it
13 // square of x each time
returns the result.
14 for ( int x = 1; x <= 10; x++ )
15 cout << square( x ) << " "; // function call
16
17 cout << endl;
18
19 return 0; // indicates successful termination
20
21 } // end main
22

 2003 Prentice Hall, Inc.


All rights reserved.
12
23 // square function definition returns square of an integer
24 int square( int y ) // y is a copy of argument to function
Outline
25 {
26 return y * y; // returns square of y as an int
fig03_03.cpp
27
(2 of 2)
28 } // end function square
Definition of square. y is a
copy of the argument passed. fig03_03.cpp
1 4 9 16 25 36 49 64 81 100 Returns y * y, or y squared. output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
13
1 // Fig. 3.4: fig03_04.cpp
2 // Finding the maximum of three floating-point numbers.
Outline
3 #include <iostream>
4
fig03_04.cpp
5 using std::cout;
(1 of 2)
6 using std::cin;
7 using std::endl;
8
9 double maximum( double, double, double ); // function prototype
10
11 int main()
12 {
13 double number1;
Function maximum takes 3
14 double number2;
arguments (all double) and
15 double number3;
16
returns a double.
17 cout << "Enter three floating-point numbers: ";
18 cin >> number1 >> number2 >> number3;
19
20 // number1, number2 and number3 are arguments to
21 // the maximum function call
22 cout << "Maximum is: "
23 << maximum( number1, number2, number3 ) << endl;
24
25 return 0; // indicates successful termination

 2003 Prentice Hall, Inc.


All rights reserved.
14
26
27 } // end main
Outline
28 Comma separated list for
29 // function maximum definition; multiple parameters.
fig03_04.cpp
30 // x, y and z are parameters
(2 of 2)
31 double maximum( double x, double y, double z )
32 {
33 double max = x; // assume x is largest fig03_04.cpp
34 output (1 of 1)
35 if ( y > max ) // if y is larger,
36 max = y; // assign y to max
37
38 if ( z > max ) // if z is larger,
39 max = z; // assign z to max
40
41 return max; // max is largest value
42
43 } // end function maximum

Enter three floating-point numbers: 99.32 37.3 27.1928


Maximum is: 99.32

Enter three floating-point numbers: 1.1 3.333 2.22


Maximum is: 3.333

Enter three floating-point numbers: 27.9 14.31 88.99


Maximum is: 88.99

 2003 Prentice Hall, Inc.


All rights reserved.
15

Function Prototypes

• Function prototype contains


– Function name
– Parameters (number and data type)
– Return type (void if returns nothing)
– Only needed if function definition after function call
• Prototype must match function definition
– Function prototype
double maximum( double, double, double );
– Definition
double maximum( double x, double y, double z )
{

}

 2003 Prentice Hall, Inc. All rights reserved.


16

Function Prototypes

• Function signature
– Part of prototype with name and parameters
• double maximum( double, double, double );

Function signature
• Argument Coercion
– Force arguments to be of proper type
• Converting int (4) to double (4.0)
cout << sqrt(4)
– Conversion rules
• Arguments usually converted automatically
• Changing from double to int can truncate data
– 3.4 to 3
– Mixed type goes to highest type (promotion)
• int * double

 2003 Prentice Hall, Inc. All rights reserved.


17

Function Prototypes

Da ta typ e s
long double
double
float
unsigned long int (synonymous with unsigned long)
long int (synonymous with long)
unsigned int (synonymous with unsigned)
int
unsigned short int (synonymous with unsigned short)
short int (synonymous with short)
unsigned char
char
bool (false becomes 0, true becomes 1)
Fig . 3.5 Pro m o tio n h ie ra rc h y fo r b u ilt-in d a ta typ e s.

 2003 Prentice Hall, Inc. All rights reserved.


18

Functions with Empty Parameter Lists

• Empty parameter lists


– void or leave parameter list empty
– Indicates function takes no arguments
– Function print takes no arguments and returns no value
• void print();
• void print( void );

 2003 Prentice Hall, Inc. All rights reserved.


19
1 // Fig. 3.18: fig03_18.cpp
2 // Functions that take no arguments.
Outline
3 #include <iostream>
4
fig03_18.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 void function1(); // function prototype
9 void function2( void ); // function prototype
10
11 int main()
12 {
13 function1(); // call function1 with no arguments
14 function2(); // call function2 with no arguments
15
16 return 0; // indicates successful termination
17
18 } // end main
19

 2003 Prentice Hall, Inc.


All rights reserved.
20
20 // function1 uses an empty parameter list to specify that
21 // the function receives no arguments
Outline
22 void function1()
23 {
fig03_18.cpp
24 cout << "function1 takes no arguments" << endl;
(2 of 2)
25
26 } // end function1
27 fig03_18.cpp
28 // function2 uses a void parameter list to specify that output (1 of 1)
29 // the function receives no arguments
30 void function2( void )
31 {
32 cout << "function2 also takes no arguments" << endl;
33
34 } // end function2

function1 takes no arguments


function2 also takes no arguments

 2003 Prentice Hall, Inc.


All rights reserved.
21

Header Files

• Header files contain


– Function prototypes
– Definitions of data types and constants
• Header files ending with .h
– Programmer-defined header files
#include “myheader.h”
• Library header files
#include <cmath>

 2003 Prentice Hall, Inc. All rights reserved.


22

Storage Classes

• Variables have attributes


– Have seen name, type, size, value
– Storage class
• How long variable exists in memory
– Scope
• Where variable can be referenced in program

 2003 Prentice Hall, Inc. All rights reserved.


23

Storage Classes

• Automatic storage class


– Variable created when program enters its block
– Variable destroyed when program leaves block
– Only local variables of functions can be automatic
• Automatic by default
• keyword auto explicitly declares automatic

 2003 Prentice Hall, Inc. All rights reserved.


24

Storage Classes
• Static storage class
– Variables exist for entire program
• For functions, name exists for entire program
– May not be accessible, scope rules still apply (more later)
• static keyword
– Local variables in function
– Initialized to zero
– Keeps value between function calls
– Only known in own function

 2003 Prentice Hall, Inc. All rights reserved.


25

Scope Rules

• Scope
– Portion of program where identifier can be used
• File scope
– Defined outside a function, known in all functions
– Global variables, function definitions and prototypes
• Function scope
– Can only be referenced inside defining function

 2003 Prentice Hall, Inc. All rights reserved.


26

Scope Rules

• Block scope
– Begins at declaration, ends at right brace }
• Can only be referenced in this range
– Local variables, function parameters
• Function-prototype scope
– Parameter list of prototype
– Names in prototype optional
• Compiler ignores
– In a single prototype, name can be used once

 2003 Prentice Hall, Inc. All rights reserved.


27
#include <iostream>
using namespace std;
Outline

int i = 8;
fig03_12.cpp
int square(int i);
(1 of 5)
int main()
{
cout << "Value of i is: " << i << endl;
{
int i = 6;
cout << "Value of i is: " << i << endl;
}
int i = 7;
cout << "Value of i is: " << i << endl;
i = square(i);
cout << "Value of i is: " << i << endl;

return 0;
}

int square(int i){


//int i; Causes an error here because variable name I used two times with equivalent scope
cout << "Value of i is: " << i << endl;
return i*i; Value of i is: 8
} Value of i is: 6
Value of i is: 7
Value of i is: 7  2003 Prentice Hall, Inc.
Value of i is: 49 All rights reserved.
28
1 // Fig. 3.12: fig03_12.cpp
2 // A scoping example.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 void useLocal( void ); // function prototype
9 void useStaticLocal( void ); // function prototype
10 void useGlobal( void ); // function prototype
11
12 int x = 1; // global variable
13
14 int main()
15 {
16 int x = 5; // local variable to main
17
18 cout << "local x in main's outer scope is " << x << endl;
19
20 { // start new scope
21
22 int x = 7;
23
24 cout << "local x in main's inner scope is " << x << endl;
25
• } // end new scope
27
28 cout << "local x in main's outer scope is " << x << endl;
29
 2003 useLocal();
30 Prentice Hall, Inc. All rights
// reserved.
useLocal has local x
29
31 useStaticLocal(); // useStaticLocal has static local x
32 useGlobal(); // useGlobal uses global x
33 useLocal(); // useLocal reinitializes its local x
34 useStaticLocal(); // static local x retains its prior value
35 useGlobal(); // global x also retains its value
36
37 cout << "\nlocal x in main is " << x << endl;
38
39 return 0; // indicates successful termination
40
41 } // end main
42
43 // useLocal reinitializes local variable x during each call
44 void useLocal( void )
45 {
46 int x = 25; // initialized each time useLocal is called
47
48 cout << endl << "local x is " << x
49 << " on entering useLocal" << endl;
50 ++x;
51 cout << "local x is " << x
52 << " on exiting useLocal" << endl;
53
54 } // end function useLocal
55

 2003 Prentice Hall, Inc. All rights reserved.


30
56 // useStaticLocal initializes static local variable x only the
57 // first time the function is called; value of x is saved
58 // between calls to this function
59 void useStaticLocal( void )
60 {
61 // initialized only first time useStaticLocal is called
62 static int x = 50;
63
64 cout << endl << "local static x is " << x
65 << " on entering useStaticLocal" << endl;
66 ++x;
67 cout << "local static x is " << x
68 << " on exiting useStaticLocal" << endl;
69
70 } // end function useStaticLocal
71
72 // useGlobal modifies global variable x during each call
73 void useGlobal( void )
74 {
75 cout << endl << "global x is " << x
76 << " on entering useGlobal" << endl;
77 x *= 10;
78 cout << "global x is " << x
79 << " on exiting useGlobal" << endl;
80
81 } // end function useGlobal

 2003 Prentice Hall, Inc. All rights reserved.


31
local x in main's outer scope is 5
local x in main's inner scope is 7
local x in main's outer scope is 5

local x is 25 on entering useLocal


local x is 26 on exiting useLocal

local static x is 50 on entering useStaticLocal


local static x is 51 on exiting useStaticLocal

global x is 1 on entering useGlobal


global x is 10 on exiting useGlobal
local x is 25 on entering useLocal
local x is 26 on exiting useLocal

local static x is 51 on entering useStaticLocal


local static x is 52 on exiting useStaticLocal

global x is 10 on entering useGlobal


global x is 100 on exiting useGlobal

local x in main is 5

 2003 Prentice Hall, Inc. All rights reserved.


32

References and Reference Parameters

• Call by value
– Copy of data passed to function
– Changes to copy do not change original
– Prevent unwanted side effects
• Call by reference
– Function can directly access data
– Changes affect original

 2003 Prentice Hall, Inc. All rights reserved.


33

References and Reference Parameters

• Reference parameter
– Alias for argument in function call
• Passes parameter by reference
– Use & after data type in prototype
• void myFunction( int &data )
• Read “data is a reference to an int”
– Function call format the same
• However, original can now be changed

 2003 Prentice Hall, Inc. All rights reserved.


34
1 // Fig. 3.20: fig03_20.cpp
2 // Comparing pass-by-value and pass-by-reference
Outline
3 // with references.
4 #include <iostream>
fig03_20.cpp
5
(1 of 2)
6 using std::cout;
Notice the & operator,
7 using std::endl;
8
indicating pass-by-reference.
9 int squareByValue( int ); // function prototype
10 void squareByReference( int & ); // function prototype
11
12 int main()
13 {
14 int x = 2;
15 int z = 4;
16
17 // demonstrate squareByValue
18 cout << "x = " << x << " before squareByValue\n";
19 cout << "Value returned by squareByValue: "
20 << squareByValue( x ) << endl;
21 cout << "x = " << x << " after squareByValue\n" << endl;
22

 2003 Prentice Hall, Inc.


All rights reserved.
35
23 // demonstrate squareByReference
24 cout << "z = " << z << " before squareByReference" << endl;
Outline
25 squareByReference( z );
26 cout << "z = " << z << " after squareByReference" << endl;
fig03_20.cpp
27
(2 of 2)
28 return 0; // indicates successful termination
29 } // end main
Changes number, but
30
31 //
original parameter (x) is not
squareByValue multiplies number by itself, stores the
32 //result in number and returns the new valuemodified.
of number
33 int squareByValue( int number )
34 {
35 return number *= number; // caller's argument not modified
36
37 } // end function squareByValue
38 Changes numberRef, an
39 //squareByReference multiplies numberRef by itself and
alias for the original
40 //stores the result in the variable to which numberRef
parameter. Thus, z is
41 //refers in function main
changed.
42 void squareByReference( int &numberRef )
43 {
44 numberRef *= numberRef; // caller's argument modified
45
46 } // end function squareByReference

 2003 Prentice Hall, Inc.


All rights reserved.
36
x = 2 before squareByValue
Value returned by squareByValue: 4
Outline
x = 2 after squareByValue

fig03_20.cpp
z = 4 before squareByReference
output (1 of 1)
z = 16 after squareByReference

 2003 Prentice Hall, Inc.


All rights reserved.
37

References and Reference Parameters

• Pointers (chapter 5)
– Another way to pass-by-refernce
• References as aliases to other variables
– Refer to same variable
– Can be used within a function
int count = 1; // declare integer variable count
Int &cRef = count; // create cRef as an alias for count
++cRef; // increment count (using its alias)

• References must be initialized when declared


– Otherwise, compiler error
– Reference to undefined variable: reference to a variable
declared in a function, variable is discarded when function
terminates

 2003 Prentice Hall, Inc. All rights reserved.


38
1 // Fig. 3.21: fig03_21.cpp
2 // References must be initialized.
Outline
3 #include <iostream>
4
fig03_21.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 int main() fig03_21.cpp
9 { output (1 of 1)
10 int x = 3; y declared as a reference to x.
11
12 // y refers to (is an alias for) x
13 int &y = x;
14
15 cout << "x = " << x << endl << "y = " << y << endl;
16 y = 7;
17 cout << "x = " << x << endl << "y = " << y << endl;
18
19 return 0; // indicates successful termination
20
21 } // end main

x = 3
y = 3
x = 7
y = 7

 2003 Prentice Hall, Inc.


All rights reserved.
39
1 // Fig. 3.22: fig03_22.cpp
2 // References must be initialized.
Outline
3 #include <iostream>
4
fig03_22.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 int main() Uninitialized reference – fig03_22.cpp
9 { compiler error. output (1 of 1)
10 int x = 3;
11 int &y; // Error: y must be initialized
12
13 cout << "x = " << x << endl << "y = " << y << endl;
14 y = 7;
15 cout << "x = " << x << endl << "y = " << y << endl;
16
17 return 0; // indicates successful termination
18
19 } // end main

Borland C++ command-line compiler error message:


Error E2304 Fig03_22.cpp 11: Reference variable 'y' must be
initialized­in function main()

Microsoft Visual C++ compiler error message:


D:\cpphtp4_examples\ch03\Fig03_22.cpp(11) : error C2530: 'y' :
references must be initialized

 2003 Prentice Hall, Inc.


All rights reserved.
40

Default Arguments

• Function call with omitted parameters


– If not enough parameters, rightmost go to their defaults
– Default values
• Can be constants, global variables, or function calls
• Set defaults in function prototype
int myFunction( int x = 1, int y = 2, int z = 3 );
– myFunction(3)
• x = 3, y and z get defaults (rightmost)
– myFunction(3, 5)
• x = 3, y = 5 and z gets default

 2003 Prentice Hall, Inc. All rights reserved.


41
1 // Fig. 3.23: fig03_23.cpp
2 // Using default arguments.
Outline
3 #include <iostream>
4
5 using std::cout;
Set defaults in function fig03_23.cpp
6 using std::endl;
7
prototype. (1 of 2)
8 // function prototype that specifies default arguments
9 int boxVolume( int length = 1, int width = 1, int height = 1 );
10
11 int main()
12 {
13 // no arguments--use default values for all dimensions
Function calls with some
14 cout << "The default box volume is: " << boxVolume(); parameters missing – the
15 rightmost parameters get their
16 // specify length; default width and height defaults.
17 cout << "\n\nThe volume of a box with length 10,\n"
18 << "width 1 and height 1 is: " << boxVolume( 10 );
19
20 // specify length and width; default height
21 cout << "\n\nThe volume of a box with length 10,\n"
22 << "width 5 and height 1 is: " << boxVolume( 10, 5 );
23

 2003 Prentice Hall, Inc.


All rights reserved.
42
24 // specify all arguments
25 cout << "\n\nThe volume of a box with length 10,\n"
Outline
26 << "width 5 and height 2 is: " << boxVolume( 10, 5, 2 )
27 << endl;
fig03_23.cpp
28
(2 of 2)
29 return 0; // indicates successful termination
30
31 } // end main fig03_23.cpp
32 output (1 of 1)
33 // function boxVolume calculates the volume of a box
34 int boxVolume( int length, int width, int height )
35 {
36 return length * width * height;
37
38 } // end function boxVolume

The default box volume is: 1

The volume of a box with length 10,


width 1 and height 1 is: 10

The volume of a box with length 10,


width 5 and height 1 is: 50

The volume of a box with length 10,


width 5 and height 2 is: 100

 2003 Prentice Hall, Inc.


All rights reserved.
43

Function Overloading

• Function overloading
– Functions with same name and different parameters
– Should perform similar tasks
• I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }

• Overloaded functions distinguished by signature


– Based on name and parameter types (order matters)
– Name mangling
• Encodes function identifier with parameters
– Type-safe linkage
• Ensures proper overloaded function called

 2003 Prentice Hall, Inc. All rights reserved.


44
1 // Fig. 3.25: fig03_25.cpp
2 // Using overloaded functions.
Outline
3 #include <iostream>
4
fig03_25.cpp
5 using std::cout;
Overloaded functions have (1 of 2)
6 using std::endl;
7
the same name, but the
8 // function square for int values
different parameters
9 int square( int x ) distinguish them.
10 {
11 cout << "Called square with int argument: " << x << endl;
12 return x * x;
13
14 } // end int version of function square
15
16 // function square for double values
17 double square( double y )
18 {
19 cout << "Called square with double argument: " << y << endl;
20 return y * y;
21
22 } // end double version of function square
23

 2003 Prentice Hall, Inc.


All rights reserved.
45
24 int main()
25 {
Outline
26 int intResult = square( 7 ); // calls int version
27 double doubleResult = square( 7.5 ); // calls double version
fig03_25.cpp
28
(2 of 2)
29 cout << "\nThe square of integer 7 is " << intResult
The proper function is called
30 << "\nThe square of double 7.5 is " << doubleResult
31 << endl;
based upon the argument fig03_25.cpp
32 (int or double). output (1 of 1)
33 return 0; // indicates successful termination
34
35 } // end main

Called square with int argument: 7


Called square with double argument: 7.5

The square of integer 7 is 49


The square of double 7.5 is 56.25

 2003 Prentice Hall, Inc.


All rights reserved.
46

Recursion

• Recursive functions
– Functions that call themselves
– Can only solve a base case
• If not base case
– Break problem into smaller problem(s)
– Launch new copy of function to work on the smaller
problem (recursive call/recursive step)
• Slowly converges towards base case
• Function makes call to itself inside the return statement
– Eventually base case gets solved
• Answer works way back up, solves entire problem

 2003 Prentice Hall, Inc. All rights reserved.


47

Recursion

• Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
– Recursive relationship ( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
– Base case (1! = 0! = 1)

 2003 Prentice Hall, Inc. All rights reserved.


48
#include <iostream>
using namespace std;
Outline
int factorial(int number);

fig03_14.cpp
int main()
(1 of 2)
{
int x,y;
cin >> x;
y = factorial(x);
cout << "factorial " << x << " is " << y << endl;

return 0;
}

int factorial(int number)


{
cout << "Function call for number = " << number << endl;
if ( number <= 1 )
return 1;
// recursive step
else
return number * factorial( number - 1 );
}
4
Function call for number = 4
Function call for number = 3
Function call for number = 2
Function call for number = 1
Factorial 4 is : 24  2003 Prentice Hall, Inc.
All rights reserved.
49

Example Using Recursion: Fibonacci Series

• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...


– Each number sum of two previous ones
– Example of a recursive formula:
• fib(n) = fib(n-1) + fib(n-2)
• C++ code for Fibonacci function
long fibonacci( long n )
{
if ( n == 0 || n == 1 ) // base case
return n;
else
return fibonacci( n - 1 ) +
fibonacci( n – 2 );
}

 2003 Prentice Hall, Inc. All rights reserved.


50

Example Using Recursion: Fibonacci Series

f( 3 )

return f( 2 ) + f( 1 )

return f( 1 ) + f( 0 ) return 1

return 1 return 0

 2003 Prentice Hall, Inc. All rights reserved.


51

Example Using Recursion: Fibonacci Series

• Order of operations
– return fibonacci( n - 1 ) + fibonacci( n - 2 );

• Do not know which one executed first


– C++ does not specify
– Only &&, || and ?: guaranteed left-to-right evaluation
• Recursive function calls
– Each level of recursion doubles the number of function calls
• 30th number = 2^30 ~ 4 billion function calls
– Exponential complexity

 2003 Prentice Hall, Inc. All rights reserved.


52
1 // Fig. 3.15: fig03_15.cpp
2 // Recursive fibonacci function.
Outline
3 #include <iostream>
4
fig03_15.cpp
5 using std::cout; The Fibonacci numbers get (1 of 2)
6 using std::cin;
large very quickly, and are all
7 using std::endl;
non-negative integers. Thus,
8
9
we use the unsigned
unsigned long fibonacci( unsigned long ); // function prototype
10 long data type.
11 int main()
12 {
13 unsigned long result, number;
14
15 // obtain integer from user
16 cout << "Enter an integer: ";
17 cin >> number;
18
19 // calculate fibonacci value for number input by user
20 result = fibonacci( number );
21
22 // display result
23 cout << "Fibonacci(" << number << ") = " << result << endl;
24
25 return 0; // indicates successful termination

 2003 Prentice Hall, Inc.


All rights reserved.
53
26
27 } // end main
Outline
28
29 // recursive definition of function fibonacci
fig03_15.cpp
30 unsigned long fibonacci( unsigned long n )
(2 of 2)
31 {
32 // base case
33 if ( n == 0 || n == 1 ) fig03_15.cpp
34 return n; output (1 of 2)
35
36 // recursive step
37 else
38 return fibonacci( n - 1 ) + fibonacci( n - 2 );
39
40 } // end function fibonacci

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

 2003 Prentice Hall, Inc.


All rights reserved.
54
Enter an integer: 4
Fibonacci(4) = 3
Outline

Enter an integer: 5
fig03_15.cpp
Fibonacci(5) = 5
output (2 of 2)
Enter an integer: 6
Fibonacci(6) = 8

Enter an integer: 10
Fibonacci(10) = 55

Enter an integer: 20
Fibonacci(20) = 6765

Enter an integer: 30
Fibonacci(30) = 832040

Enter an integer: 35
Fibonacci(35) = 9227465

 2003 Prentice Hall, Inc.


All rights reserved.
55

Recursion vs. Iteration

• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance between performance (iteration) and good
software engineering (recursion)

 2003 Prentice Hall, Inc. All rights reserved.


56

Recursion vs. Iteration (Assignment)

• Assignment:
– Rewrite the fibonacci series program without using recursion
(using iterations):

• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...


– Each number sum of two previous ones
– Example of a recursive formula:
• fib(n) = fib(n-1) + fib(n-2)

 2003 Prentice Hall, Inc. All rights reserved.

You might also like