Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem to exit a procedure

 
Komlavi Ekouevi
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I have a recusrive function and I am trying to exit with the return statement but for some reasons the return statement continue to call the recursive function. Here it is how my function looks like

public void Solve ()
{
if ( Stopping Condition )
return;

Solve();
}

How can I exit this function? Thanks
 
Paul Clapham
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JsuperJeeck Koffi wrote:for some reasons the return statement continue to call the recursive function.


No, that isn't what is happening. A return statement doesn't call any methods. What is happening is, your "Stopping Condition" is never true.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48968
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

A recursion is usually only useful if it returns a value. The calling method uses that value. Look at this factorial function, where the method calls itself.

Also a recursion should have a base case. That means if a certain value is found (in the case of factorial, 0), a predetermined result is returned, in this case 1. The recursion should converge towards its base case, otherwise it is liable to go on for ever (or at least until it exhausts your stack space or memory available).
Note there are also exclusions; negative values don't have factorials, and values > 21 (I think) give arithmetic overflow. Hence the Exceptions.
Note the letter L to make the 1 into a long.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic