Skip to content

Instantly share code, notes, and snippets.

@TheMuellenator
Created April 20, 2021 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheMuellenator/d7a51665386b12b11519fb43d33e1d12 to your computer and use it in GitHub Desktop.
Save TheMuellenator/d7a51665386b12b11519fb43d33e1d12 to your computer and use it in GitHub Desktop.
class Assignment {
func fibonacci(n: Int) {
// Write your code here 👇
var n1 = 0
var n2 = 1
if n == 0 {
print("Invalid")
} else if n == 1 {
print(n1)
} else if n == 2 {
print(n1, n2)
} else {
var array = [n1, n2]
for _ in 2..<n {
let n3 = n1 + n2
n1 = n2
n2 = n3
array.append(n3)
}
print(array)
}
}
}
// Test your function here for different values of n 👇
let test = Assignment()
test.fibonacci(n: 11)
@lakhvirk
Copy link

I came with this solution, I hope it looks okay ?

class Assignment {

    func fibonacci(n: Int) {

       var array: [Int] = []

        for index in 0..<n {
            if index > 1 {
                array.append(array[array.count - 1] + array[array.count - 2])
            } else {
                array.append(index)
            }
        }       
        print(array)   
    }   
}

@OsamaSaberB
Copy link

OsamaSaberB commented Apr 11, 2022

this was my way of solving.

func fibonacci(n: Int){
var array = [0,1]
var counter = 0
var numberToAdd = 0

while counter < n {
    numberToAdd = (array.last!) + array[counter]
    counter += 1
    array.append(numberToAdd)
}
array.removeLast(2) //to compensate for starting the array with 2 elements [0,1]
print(array)
}

@ilyamfaisal28
Copy link

ilyamfaisal28 commented Feb 7, 2024

This is my solution

func fibonacci(n: Int) {

    var array: [Int] = []
    for i in 0..<n {
        if i == 0 || i == 1 {
            array.append(i)
        } else {
            array.append(array[i-2] + array[i-1])
        }
    }
    print(array)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment