How can I code a Fibonacci sequence iteratively

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tlalzo
    New Member
    • Jul 2009
    • 1

    #1

    How can I code a Fibonacci sequence iteratively

    how can I write a fibonnaci sequence up n iteratively where n is given by the user and the program must display all the numbers of the sequence up to n.
  • MikeTheBike
    Recognized Expert Contributor
    • Jun 2007
    • 640

    #2
    Originally posted by tlalzo
    how can I write a fibonnaci sequence up n iteratively where n is given by the user and the program must display all the numbers of the sequence up to n.
    Hi

    I'm not sure if this is whay you want but this writes the sequence down the spreadsheet coulmn up to n.
    Code:
    Sub FibonnaciNos(ByVal n As Long)
        Dim i As Long
        Dim iRow As Long
        Dim PrevNo As Long
        Dim LastNo As Long
        iRow = 1
        i = 0
        If n >= i Then Cells(iRow, 1) = i
        i = i + 1
        iRow = iRow + 1
        If n >= i Then Cells(iRow, 1) = i
        iRow = iRow + 1
        If n >= i Then Cells(iRow, 1) = i
        iRow = iRow + 1
        PrevNo = i
        LastNo = i
    
        i = LastNo + PrevNo
        Do Until i > n
            
            Cells(iRow, 1) = i
            
            PrevNo = LastNo
            LastNo = i
            i = LastNo + PrevNo
            iRow = iRow + 1
        Loop
    End Sub
    
    Sub test()
        FibonnaciNos 145
    End Sub
    ??

    The numbers 0, 1,1 are straigh code but it didn't seem worth finding a 'clever way' to do that bit !!

    MTB

    Comment

    Working...