FANDOM


We'll discuss two possible approaches to make the Fibonacci function:

This section makes use of Simulating Parameters in Small Basic and Simulating Local Variables in Small Basic. Please see those articles for details.

' Call Fib( 13 )
Stack.PushValue( "p", 13 )
Fib()
TextWindow.WriteLine( Stack.PopValue( "p" ) )

Sub Fib ' n
  Fib_Locals = Fib_Locals + 1
  
  'Set up params:
  Array.SetValue( Text.Append( "Fib", Fib_Locals), "n", Stack.PopValue( "p" ) )

  If Array.GetValue( Text.Append( "Fib", Fib_Locals), "n") < 2 Then
    ' Return n
    Stack.PushValue( "p", Array.GetValue( Text.Append( "Fib", Fib_Locals), "n") )
    Goto Fib_Exit
  Else
    'n1 = Fib( n - 1 )
    Stack.PushValue( "p", Array.GetValue( Text.Append( "Fib", Fib_Locals), "n") - 1 )
    Fib()
    Array.SetValue( Text.Append( "Fib", Fib_Locals), "n1", Stack.PopValue( "p" ) )
    
    'n2 = Fib( n - 2 )
    Stack.PushValue( "p", Array.GetValue( Text.Append( "Fib", Fib_Locals), "n") - 2 )
    Fib()
    Array.SetValue( Text.Append( "Fib", Fib_Locals), "n2", Stack.PopValue( "p" ) )
    
    'Return n1 + n2
    Stack.PushValue( "p", Array.GetValue( Text.Append( "Fib", Fib_Locals), "n1") + Array.GetValue( Text.Append( "Fib", Fib_Locals), "n2") )
    Goto Fib_Exit
  EndIf
  
Fib_Exit:
  Fib_Locals = Fib_Locals - 1
EndSub

Originally posted on http://wiki.smallbasic.com/Fibonacci.ashx

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.