Credits

Monday, December 2, 2013

Recursion in Java

Recursion is an interesting block of codes to do as it can be quite confusing and powerful if used. Recursion can be used as an alternative to looping.

Since it can be quite confusing, the question is, should we use recursion  as often as we should? The general rule is if the programming language like Java allows looping commands like for statement, do . . while or while statements, then, the need for recursion isn't necessary.

However, some programming languages like Scheme or Dr. Racket, a variation of Scheme, only allows recursion.

So, we need to remember two things for recursion to function well:

1. there must be a base case or condition, so, our recursion shall stop.
2. recursion oftentimes return a value.

The code below demonstrate how to get the exponentiation of an integer using a set of looping command and an equivalent in recursive method.
the sample output shows looping and recursive methods having same result
The RECURSIVE  / LOOPING methods shall look below. The first two lines  show the method calls for looping and recursive methods.





AddThis