Chapter 3 - Functions

1 Chapter 3 - Functions Outline 3.12 Recursion 3.13 Example Using Recursion: The Fibonacci Series 3.14 Recursion vs. Iteration © 2003 Prentice Hall,...
Author: Norma Fleming
3 downloads 1 Views 43KB Size
1

Chapter 3 - Functions Outline 3.12 Recursion 3.13 Example Using Recursion: The Fibonacci Series 3.14 Recursion vs. Iteration

© 2003 Prentice Hall, Inc. All rights reserved.

2

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

3

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

4

// Fig. 3.14: fig03_14.cpp // Recursive factorial function. #include

Outline fig03_14.cpp (1 of 2)

using std::cout; using std::endl; #include using std::setw;

Data type unsigned long can hold an integer from 0 to 4 billion.

unsigned long factorial( unsigned long ); // function prototype int main() { // Loop 10 times. During each iteration, calculate // factorial( i ) and display result. for ( int i = 0; i