Fibonacci Series in Kotlin

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding numbers, starting from 0 and 1. The first few numbers in the series are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, …

The Fibonacci sequence is named after the Italian mathematician Leonardo of Pisa, who was also known as Fibonacci. The sequence appears in many areas of mathematics and science, and is frequently used in computer algorithms and programming.

Kotlin
fun main() {
    val n = 10 // number of Fibonacci numbers to generate
    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
    }
}

This code generates the first 10 numbers in the Fibonacci series. You can adjust the value of n to generate more or fewer numbers.

The output of this program will be:

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

This program uses a for loop to iterate over the desired number of terms in the series. It keeps track of the two previous terms (t1 and t2) and calculates the next term by adding them together. It then updates t1 and t2 to prepare for the next iteration. The program prints out each term as it is generated.

Leave a Comment