Method returned wrong value

I have following recursive method. It adds all individual integers in a numeric and returns an integer.
With input “123456789” the AddUp value becomes “9” (after a recursive call) checked in the debugger. But the method returns 0. How is that possible?

Function NineProof(Token as Integer) As Integer
  'Convert numeric to string for counting
  Var StringToken As String
  Var Addup As Integer
  StringToken = Token.ToString
  
  'add every single integer
  For I As Integer = 0 To StringToken.Length-1
    Addup = Addup + StringToken.Middle(I,1).ToInteger
  Next
  
  If AddUp > 9 Then 'total is more than 1 integer
    Token = NineProof(AddUp)
  Else
    Return AddUp
  End if
  
  
End Function

I think you want this:

'Convert numeric to string for counting
Var StringToken As String
Var Addup As Integer
StringToken = Token.ToString

'add every single integer
For I As Integer = 0 To StringToken.Length-1
  Addup = Addup + StringToken.Middle(I,1).ToInteger
Next

while AddUp > 9 'loop if total is more than 1 integer
  AddUp = NineProof(AddUp)
wend
Return AddUp

Thanks Jeff.

Further than Jeff’s answer, it’s worth pointing out the flaws in the code. The quoted line tries to assign a value to Token, which unless declared as ByRef, won’t change (it’s a parameter).
Also, Token is forgotten at the end of the method (there’s no return statement when AddUp > 9).
IMO, both flaws comes because you thought you could use Token to call NineProof again and store the result in that.

Even if you had declared Token with ByRef to return the result in it, you’d have one path returning the result with Return (i.e. obtained using result=NineProof(value)) and the other path returning the result to a parameter (i.e. obtained using x=NineProof(ValueAndResult)). You could use either approaches (while I’d tend to say the former is better), but mixing them that way will make troubles (the result being stored in either of two places based on a criterion).

You’re absolutely right. Never used recursion before, read about it and tried to figure it out. Thanks for your observations.

Recursion, when a method calls itself, means that a fresh set of variables (all those local Var) are created on the stack.

Indeed, it’s a learning path many have had to pass by :wink:

You’re welcome.

I read that later… :slight_smile:

Recursion (noun) : see Recursion

1 Like

I first came across that as a small boy, reading a story called “The Gryphon and the Minor Canon”. The Canon is trying to find out how to defeat the Gryphon, and looks “Gryphon” up in his encyclopedia. The entry reads “Gryphon: see Basilisk”. He duly follows the link, only to find that the entry for “Basilisk” reads “Basilisk: see Gryphon”. I thought that was pretty funny at the time.

1 Like