Recursion in java, understand recursion and implementation

How to implement recursion using java, an article with coding example


Category: Java J2SE Tags: Java J2SE


Introduction

      Recursion is a programming technique in which a function calls itself for a number of times until a particular condition is satisfied. It is a very important technique to understand a one understood many long listening of code can be reduce to few number of lines.Two things should be in mind when using recursion:

  1. the problem must be expressed in recursive manner.
  2. there must be a condition which stops the recursion otherwise there would be a stack overflow.

Lets have an example of recursion in java:


import java.io.*;
import java.awt.*;
public class recursion
{
public static void main(String args[])
{
int i=0;
i=increment(i);
System.out.println("at last value of i= "+i);
}
static int increment(int x)
{
if(x<10)
{
System.out.println("round "+x);
++x;
return increment(x);
}
return x;
}
}

Explanation: Here you can see in class recursion we defined a function increment, which increments the value x and print the x, and also returns with a call itself with argument x. Here we also defined a if condition which terminates the recursion when x will reach to 10.

        So the the function calling here itself 9 times called recursion.after that when x=10 the condition will be false so it will return simply x (no more self call) and we will get the last value of x is 10.


Output:


round 0

round 1

round 2

round 3

round 4

round 5

round 6

round 7

round 8

round 9

at last value of i= 10


Understanding via image:



  



Like 1 Person
Last modified on 11 October 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 132
Questions: 9
Given Best Solutions: 9 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x