How to print the Fibonacci sequence in Swift

1 Answer

0 votes
import Foundation

func fibonacci(_ n: Int) -> Int {
    if n == 0 {
        return 0
    } else if n == 1 {
        return 1
    } else {
        return fibonacci(n - 2) + fibonacci(n - 1)
    }
}

let n = 15

for i in 0...n {
    print(String(format: "%4d", fibonacci(i)), terminator: "")
}



/*
run:

   0   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610

*/

 



answered Jan 18, 2025 by avibootz
...