Thông tin tài liệu
C++ Programming Lecture 12 Functions – Part IV The Hashemite University Computer Engineering Department Adapted from the textbook slides Outline Introduction Recursion Reference parameters and variables Functions call by reference and call by value Examples The Hashemite University Recursion I Recursive functions Are functions that calls themselves Recursive functions know the solution for the simplest case called base case If the function is called with the base case the function returns a result else, 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 (recursive calls) 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 The recursion step executes while the original call to the function is still open (not finished yet) The Hashemite University Recursion II Example: factorial n! = n * ( n – ) * ( n – ) * … * Can be solved either iteratively or recursively: Iteratively: int factorial = 1; for (int count = n; count >= 1; count ) factorial *= count; int fact (int number) Recursively: Recursive relationship ( n! = n * ( n – )! ) 5! 4! 3! 2! 1! = = = = = * * * * 4! 3! 2! 1! { If ( number=2 (not base case) C++ code for fibonacci function long fibonacci( long n ) { if ( n == || n == ) // base case return n; else return fibonacci( n - ) + fibonacci( n – ); } The Hashemite University Example Using Recursion: The Fibonacci Series Diagram of Fibonacci function f( 3 ) return return f( 1 ) return 1 + f( 2 ) + f( 1 ) f( 0 ) return 1 return 0 The Hashemite University // Fig 3.15: fig03_15.cpp // Recursive fibonacci function #include using std::cout; using std::cin; using std::endl; unsigned long fibonacci( unsigned long ); 10 11 int main() 12 { 13 unsigned long result, number; 14 15 cout > number; 17 result = fibonacci( number ); 18 cout
Ngày đăng: 12/10/2021, 21:08
Xem thêm: