Recursion:
Recursion is
the technique of a method calling itself. This technique provides a way to break
complicated problems down into simple problems which are easier to solve.
Example 01:
package Recursion;
public class recursion {
public static void main(String[] args) {
int result = sum(10); //calling the sum method
System.out.println(result);
}
public static int sum(int k)//creating a static method
{
if (k > 0) //validating it with a condition
{
return k + sum(k - 1);
} else {
return 0;
}
}
}
Example 02:
package Recursion;
public class R_Fact {
public static void main(String[] args) {
int num = 6;
long factorial = multiplyNumbers(num);
System.out.println("Factorial of " + num + " = " + factorial);
}
public static long multiplyNumbers(int num)
{
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}
0 Comments