Docsity

Recursion: A Method Calling Itself - Examples and Factorial Calculation - Prof. Joseph Gui, Study notes of Computer Science

Partial preview of the text

Download Recursion: A Method Calling Itself - Examples and Factorial Calculation - Prof. Joseph Gui and more Study notes Computer Science in PDF only on Docsity!

For some problems, it’s useful to have a method call

itself.

 (^) Known as a recursive method.  (^) Can call itself either directly or indirectly through another method. 

Figure 18.1 summarizes the recursion examples and

exercises in this book.

The recursion step normally includes a return statement,

because its result will be combined with the portion of the

problem the method knew how to solve to form a result that

will be passed back to the original caller.

The recursion step executes while the original method call is

still active.

For recursion to eventually terminate, each time the method

calls itself with a simpler version of the original problem,

the sequence of smaller and smaller problems must

converge on a base case.

 (^) When the method recognizes the base case, it returns a result to the previous copy of the method.  (^) A sequence of returns ensues until the original method call returns the final result to the caller.

A recursive method may call another method, which

may in turn make a call back to the recursive method.

 (^) This is known as an indirect recursive call or indirect recursion.

We use type long so the program can calculate

factorials greater than 12!.

The factorial method produces large values so

quickly that we exceed the largest long value when we

attempt to calculate 21!.

Both iteration and recursion can occur infinitely:

 (^) An infinite loop occurs with iteration if the loop-continuation test never becomes false  (^) Infinite recursion occurs if the recursion step does not reduce the problem each time in a manner that converges on the base case, or if the base case is not tested.

Recursion repeatedly invokes the mechanism, and

consequently the overhead, of method calls.

 (^) Can be expensive in terms of both processor time and memory space. 

Each recursive call causes another copy of the method

(actually, only the method’s variables, stored in the

activation record) to be created

 (^) this set of copies can consume considerable memory space. 

Since iteration occurs within a method, repeated

method calls and extra memory assignment are

avoided.