0

I am trying to build a basic fibonacci sequence using a while loop in Swift.

The condition I am using in the while loop is while var next <= var maxNum, where next is an integer containing the newest element in the array to be appended, and maxNum is an integer that represents the largest element to be contained in the array (to test the while loop, I hardcoded it to ten).

Getting the following error when running the below code in playground: "Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"

The while loop runs 90 times before this happens, letting me know that my condition is breaking down...var next should be greater than 10 after a few loops....not sure what's going on.

import UIKit

var myArray = [0,1]

var maxNum = 10
var next = 0

while next <= maxNum{
    var last = myArray.last!
    var lastLast = myArray[myArray.count-2]
    var next = last + lastLast
    myArray.append(next)
}


println(myArray)
println(myArray.last!)
2
  • 2
    Have you stepped through your code at all? Or have you outputted values from your while loop? What have you done to try to debug this? Commented Oct 8, 2014 at 17:25
  • Don't know swift that well, but aren't you declaring a new next variable inside the loop? That would cause the outer next to remain 0. Commented Oct 8, 2014 at 17:28

1 Answer 1

3

The problem is that you are redeclaring next inside the body of your loop:

var next = last + lastLast

should be

next = last + lastLast

Once you make this correction, your code runs fine, producing the result below:

[0, 1, 1, 2, 3, 5, 8, 13]
13

Demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.