Recursion in JAVA

The process when a function calls itself in the body of the program itself is known as recursion. Many times, recursion leads to very long or sometimes indefinite program statements too.  In such cases, the programmer can end the program by using a base case.

Just like the for loop and the while loop in an iteration, recursion is also a loop. However, there are certain cases where we need to use recursion instead of an iteration loop. This happens in cases where the problem can be solved by a simpler method and the code can be reduced to a large extent.

Every recursion statement should possess the following characteristics.

  1. It should have a simple base case comprising of for and a return value.
  2. A recursion statement should be able to devise a method for solving the problem in a simple manner that it comes closer to the base case.
  3. Lastly, it should make a recursive call to the program that passes the simpler problem back into the method.

Just like the loop, we need to change some value in the recursion statement taking it closer to the base loop incrementally.

The following function shows example of the Recursive statement:

Void example_recursion_program (int counter_var_1)
{
if(counter_var_1 == 0)
return;
else
{
System.out.println(“Value passed is = “+ counter_var_1);
example_recursion_program  (–counter_var_1);
return;
}
}

Continue reading Recursion in JAVA