Simple_Recursion1
  • A recursive method is a method that calls itself either directly or indirectly
  • Both iteration and recursion are based on a control structure: Iteration uses a repetition structure; recursion uses a selection structure.
  • Both iteration and recursion involve repetition: Iteration explicitly uses a repetition structure; recursion achieves repetition through repeated method calls.
  • Iteration and recursion each involve a termination test: Iteration terminates when the loop-continuation condition fails; recursion terminates when a base case is recognized.
     
  • Base Case: the termination condition is defined.
  • A function that has no pending statements following the recursive call, is known as
 
Code:

package javatemplate1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaTemplate1
{
public static void main(String[] args) throws IOException {
System.out.println("main block executing");
// Launching Application where Satge equals to window
//scene will contain children nodes using a container class
// like Group or Pane Class
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Type a number :");
String str = "";
str = br.readLine();
int y = Integer.parseInt(str);
for(int counter =0; counter <=y; counter++)
{
System.out.printf("%d ! = %d\n", counter, factorial(counter));
}
}
public static long factorial(long number)
{
if(number <=1) // test base case
{
return 1;
}
else
{
// test recursive
return number * factorial(number-1);
}
}
}
 

Runtime displays: