Kotlin – Fibonacci Series using For loop

Fibonacci series using For loop in Kotlin

In this tutorial, we will learn how to generate the Fibonacci series using a For loop in Kotlin.

Examples

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.

Generating Fibonacci series

In this example, we will create a function that generates the Fibonacci series up to a given number of terms.

Kotlin Program

fun generateFibonacciSeries(terms: Int): List<Int> {
    val fibonacciSeries = mutableListOf(0, 1)
    for (i in 2 until terms) {
        val nextTerm = fibonacciSeries[i - 1] + fibonacciSeries[i - 2]
        fibonacciSeries.add(nextTerm)
    }
    return fibonacciSeries
}

fun main() {
    val numberOfTerms = 10
    val fibonacciSeries = generateFibonacciSeries(numberOfTerms)
    println("Fibonacci Series:")
    for (term in fibonacciSeries) {
        print("$term ")
    }
}

Output

Fibonacci Series:
0 1 1 2 3 5 8 13 21 34 

The function generateFibonacciSeries takes an integer terms as input and returns a list containing the first terms Fibonacci numbers. The for loop iterates from 2 to terms, calculating each Fibonacci number and adding it to the list.

Generating Fibonacci series up to a specific number

In this example, we will create a function that generates the Fibonacci series up to a specific number.

Kotlin Program

fun generateFibonacciSeriesUpToNumber(number: Int): List<Int> {
    val fibonacciSeries = mutableListOf(0, 1)
    for (i in 2 until number) {
        val nextTerm = fibonacciSeries[i - 1] + fibonacciSeries[i - 2]
        if (nextTerm <= number) {
            fibonacciSeries.add(nextTerm)
        } else {
            break
        }
    }
    return fibonacciSeries
}

fun main() {
    val number = 50
    val fibonacciSeries = generateFibonacciSeriesUpToNumber(number)
    println("Fibonacci Series up to $number:")
    for (term in fibonacciSeries) {
        print("$term ")
    }
}

Output

Fibonacci Series up to 50:
0 1 1 2 3 5 8 13 21 34 

The function generateFibonacciSeriesUpToNumber takes an integer number as input and returns a list containing the Fibonacci numbers up to and including number. The For loop iterates from 2 to number (exclusive), calculating each Fibonacci number and adding it to the list until the next number exceeds the given number. If the next term exceeds the given number, the loop is terminated using the break statement.

Summary

In this Kotlin tutorial, we learned how to generate the Fibonacci series using a For loop in Kotlin. We saw two examples: one to generate the series up to a given number of terms and another to generate the series up to a specific number.