Friday, August 11, 2017

Recursion



The idea of calling one function from another immediately suggests the possibility of a function calling itself. The function-call mechanism in Java supports this possibility, which is known as recursion.

Syntax:

returntype methodname()

{  

//code to be executed  

methodname();//calling same method  

}  

Example

public class RecursionExample
{
   int factorial(int n)
 {
  if(n==1)
   return 1;
  else
 return(n * factorial(n-1));
}
public static void main(String[] args)
{
RecursionExample ob=new RecursionExample();
 System.out.println("Factorial of 5 is:"+ob.factorial(5));
}
}

No comments:

Post a Comment