In this tutorial, you shall learn how to write a program to print the Fibonacci Series in Kotlin.

Kotlin – Fibonacci Series Program

Fibonacci series starts with zero and one and continues with the next elements where the current element is the sum of previous two elements.

To print first n elements of Fibonacci series in Kotlin, we use For loop statement.

Program

In the following program, we read a number from user and store it in count, then print the first count number of elements in the Fibonacci series.

Main.kt

</>
Copy
fun printFibonacciSeriesUntil(count: Int) {
    println("Fibonacci series")
    var t1 = 0
    var t2 = 1
    for (i in 1..count) {
        print("$t1 ")
        val sum = t1 + t2
        t1 = t2
        t2 = sum
    }
}

fun main() {
    print("Enter an integer : ")
    val num = readLine()!!.toInt()
    printFibonacciSeriesUntil(num)
}

Output #1

Enter an integer : 10
Fibonacci series
0 1 1 2 3 5 8 13 21 34 

Output #2

Enter an integer : 15
Fibonacci series
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 

Related tutorials for the above program

Conclusion

In this Kotlin Tutorial, we learned how to print the first specified number of elements in a Fibonacci Series.