English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin prints and displays the Fibonacci sequence

Comprehensive Collection of Kotlin Examples

In this program, you will learn to use for and while loops to display the Fibonacci sequence in Kotlin. You will learn how to display the sequence until a specific term or number is displayed.

The Fibonacci sequence is a series in which the next term is the sum of the two preceding ones. The first two terms of the Fibonacci sequence are 0, followed by1.

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...

Example1Use a for loop to display the Fibonacci sequence

fun main(args: Array<String>) {}}
    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
    }
}

When running the program, the output is:

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

In the above program, the first term (t1) and the second term (t2) are initialized to 0 and1are the first two terms.

Unlike Java, we use the range and in operators to iterate until n (number of items) and display the stored in variable t1is the sum of the first two terms.

The following is equivalent Java code:Java program to display the Fibonacci series.

You can also use a while loop in Kotlin to generate the Fibonacci sequence.

Example2Use a while loop to display the Fibonacci sequence

fun main(args: Array<String>) {}}
    var i = 1
    val n = 10
    var t1 = 0
    var t2 = 1
    print("First $n terms:")
    while (i <= n) {
        print("$t1 + 
        val sum = t1 + t2
        t1 = t2
        t2 = sum
        i++
    }
}

The output is the same as the above program.

In the above program, unlike the for loop, we must increase the value of i inside the loop.

Although both programs are technically correct, it is best to use a for loop in this case. This is because the number of iterations (from1to n) is known.

Example3shows the Fibonacci sequence with the most given numbers (not items)

fun main(args: Array<String>) {}}
    val n = 100
    var t1 = 0
    var t2 = 1
    print("Upto $n: ")
    while (t1 <= n) {
        print("$t1 + 
        val sum = t1 + t2
        t1 = t2
        t2 = sum
    }
}

When running the program, the output is:

Upto 100: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 +

This program will display the sequence up to the given number (100), rather than displaying the sequence until the specified number.

For this, we only need to compare the last two numbers (t1) and n.

If t1Output t if less than or equal to n1Otherwise, we have completed the display of all terms.

Comprehensive Collection of Kotlin Examples