go to previous page   go to home page   go to next page

Answer:

Sure! Anything that can be done with iteration (looping) can be done with recursion.


Counting with Recursion

Usually you would use a counting loop (probably a for-loop) for this task. You would expect a loop that looks something like this:

// add integers from first to last
int sum = 0;
for ( int j=first; j<=last; j++ )
  sum += j;

However, you can write the equivalent of this loop with recursion.

To use recursion to add integers from first to last:

  1. The sum of integers from last to last is that integer: last.
  2. The sum of all the integers from first to last is the first integer added to the sum of the remaining integers.

Here is a method that implements this.


  static int sum( int first, int last )
  {
    if ( first==last )
      return last;
    else
      return first + sum ( first+1, last );
  }

QUESTION 10:

In adding the integers from 1 to 5, how many activations would there be?


go to previous page   go to home page   go to next page