Write a Kotlin Program to Display Fibonacci Series

In Kotlin, the Fibonacci series can be generated using a loop or recursion.

Here’s how to generate the Fibonacci series using a loop in Kotlin:

fun main() {
    val n = 10
    var t1 = 0
    var t2 = 1
    print("First $n terms: ")

    for (i in 1..n) {
        print("$t1 + ")
        val sum = t1 + t2
        t1 = t2
        t2 = sum
    }
}

In this code, n is the number of terms you want to generate in the Fibonacci series. t1 and t2 are the first two terms of the series. The loop iterates n times, and on each iteration, the sum of t1 and t2 is calculated and printed. Then, t1 is updated to t2, and t2 is updated to the sum.

When you run this code, it will output the first 10 terms of the Fibonacci series:

First 10 terms: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 +

Alternatively, you can generate the Fibonacci series using recursion. Here’s how to do it:

fun main() {
    val n = 10
    print("First $n terms: ")
    for (i in 0 until n) {
        print("${fibonacci(i)} + ")
    }
}

fun fibonacci(n: Int): Int {
    return if (n <= 1)
        n
    else
        fibonacci(n - 1) + fibonacci(n - 2)
}

In this code, n is the number of terms you want to generate in the Fibonacci series.

The fibonacci function is a recursive function that takes an integer parameter n and returns the nth number in the Fibonacci series.

If n is less than or equal to 1, the function returns n. Otherwise, it returns the sum of the n-1th and n-2th numbers in the series.

When you run this code, it will output the first 10 terms of the Fibonacci series:

First 10 terms: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 +

In conclusion, the Fibonacci series can be generated in Kotlin using either a loop or recursion.

The loop method is generally faster, but the recursive method can be easier to understand and implement.