Java supports recursion. Recursion is the process of defining something in terms of itself. recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive.
The best example of recursion is the computation of the factorial of a number.
/*Recursion function example in java*/
//programming789.blogspot.com/
class Factorial {
int fact(int n) //recursive function
{
int result;
if ( n ==1) return 1;
result = fact (n-1) * n;
return result;
}
}
class Recursion {
public static void main (String args[]) {
Factorial f =new Factorial();
System.out.println("Factorial of 1 is " + f.fact(1));
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
Factorial of 1 is 1
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
The best example of recursion is the computation of the factorial of a number.
/*Recursion function example in java*/
//programming789.blogspot.com/
class Factorial {
int fact(int n) //recursive function
{
int result;
if ( n ==1) return 1;
result = fact (n-1) * n;
return result;
}
}
class Recursion {
public static void main (String args[]) {
Factorial f =new Factorial();
System.out.println("Factorial of 1 is " + f.fact(1));
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
● Save the file as Recursion.java.
Output:
>java Recursion Factorial of 1 is 1
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120