RECURSION IN JAVA
A java, in which a function calls itself is called as recursive function. Using recursive algorithm, certain problems can be solved programs easily.
Recursion is a process in which a method can calls itself continuously is known as recursion in java.
Syntax:
returntype methodname()
{
//code to be executed
methodname();//calling same method
}
Example:1
public class Recursion
{
public static int factorial(int n)
{
if (n == 0)
{
return 1;
}
else
{
return n * factorial(n-1);
}
}
public static void main(String[] args)
{
int n = 5;
System.out.println("Factorial of " + n + " is " + factorial(n));
}
}
Output:
Factorial of 5 is 120
Example:2
public class Main
{
public static void main(String[] args)
{
int result = sum(20);
System.out.println(result);
}
public static int sum(int k)
{
if (k > 0)
{
return k + sum(k - 1);
}
else
{
return 0;
}
}
}
Output:
210