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:
- the problem must be expressed in recursive manner.
- there must be a condition which stops the recursion otherwise there would be a stack overflow.
Lets have an example of recursion in java:
public class recursion
public static void main(String args)
System.out.println("at last value of i= "+i);
static int increment(int 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.
at last value of i= 10
Understanding via image: