Thursday, January 21, 2016

Topic 17: Recursion in Java

A method that calls itself is said to be recursive and process is called Recursion.


The following code fragment calculates factorial of a number by use of a recursive method. The factorial of a number N is the product of all the whole numbers between 1 and N:

// this is a recursive method
int fact(int n)
{
if(n==1)
return 1;
return fact(n-1) * n;
}

  • When a method calls itself, new local variables and parameters are allocated storage on the stack, and the method code is executed with these new variables from the start. 

  • As each recursive call returns, the old local variables and parameters are removed from the stack, and execution resumes at the point of the call inside the method. 

  • When writing recursive methods, we must have an if statement somewhere to force the method to return without the recursive call being executed. If we don’t do this, once we call the method, it will never return. 

 

Click for NEXT article.

 

Please feel free to correct me by commenting your suggestions and feedback.

No comments:

Post a Comment