• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Problem to exit a procedure

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic