Close
Register
Close Window

Data Structures & Algorithms

Chapter 5 Recursion and Dynamic Programming

Show Source |    | About   «  5.3. Code Completion Practice Exercises   ::   Contents   ::   5.5. Harder Code Completion Practice Exercises  »

5.4. Writing More Sophisticated Recursive Functions

Some recursive functions have only one base case and one recursive call. But it is common for there to be more than one of either or both.

The following is the general structure for a recursive function.

if ( base case 1 )
  // return some simple expression
else if ( base case 2 )
  // return some simple expression
else if ( base case 3 )
  // return some simple expression
else if ( recursive case 1 ) {
  // some work before 
  // recursive call 
  // some work after 
 }
else if ( recursive case 2 ) {
  // some work before 
  // recursive call 
  // some work after 
 }
else { // recursive case 3 
  // some work before 
  // recursive call 
  // some work after 
 }
if ( base case 1 ) {
  // return some simple expression
}
else if ( base case 2 ) {
  // return some simple expression
}
else if ( base case 3 ) {
  // return some simple expression
}
else if ( recursive case 1 ) {
  // some work before 
  // recursive call 
  // some work after 
 }
else if ( recursive case 2 ) {
  // some work before 
  // recursive call 
  // some work after 
 }
else { // recursive case 3 
  // some work before 
  // recursive call 
  // some work after 
 }
if (base case 1)
  // return some simple expression
else if (base case 2)
  // return some simple expression
else if (base case 3)
  // return some simple expression
else if (recursive case 1) {
  // some work before 
  // recursive call 
  // some work after 
 }
else if (recursive case 2) {
  // some work before 
  // recursive call 
  // some work after 
 }
else { // recursive case 3 
  // some work before 
  // recursive call 
  // some work after 
 }

   «  5.3. Code Completion Practice Exercises   ::   Contents   ::   5.5. Harder Code Completion Practice Exercises  »

Close Window