w3resource

Kotlin Program: Fibonacci series up to a given number


Write a Kotlin program to print the Fibonacci series up to a given number.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Loops in Kotlin.
  • Fibonacci Series Concept.
  • Variable Initialization.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the Function.
  • Initialize Variables.
  • Print Initial Numbers.
  • Use a While Loop.
  • Update Variables.
  • Test with Different Limits.
  • Common Errors to Avoid:
    • Forgetting to update variables.
    • Not checking the limit condition.
    • Misplacing loop logic.

Sample Solution:

Kotlin Code:

 fun main() {
    val n = 30  

    println("Fibonacci series up to $n:")
    printFibonacciSeries(n)
}

fun printFibonacciSeries(n: Int) {
    var num1 = 0
    var num2 = 1

    print("$num1, $num2")
     
    while (num2 <= n) {   
        val nextNum = num1 + num2
        if (nextNum<=n)
        {
        print(", $nextNum")
        }
        num1 = num2
        num2 = nextNum
    }
}

Sample Output:

Fibonacci series up to 30:
0, 1, 1, 2, 3, 5, 8, 13, 21 

Explanation:

In the above exercise,

  • The "n" variable is declared and assigned a specific value, in this case, 20.
  • The printFibonacciSeries() function takes "n" as an argument and prints the Fibonacci series up to "n".
  • Inside the printFibonacciSeries() function, we initialize two variables num1 and num2 with the first two numbers of the Fibonacci series (0 and 1).
  • We print the initial numbers 0 and 1 using the print() function.
  • Using a while loop, we generate the next numbers in the series by adding num1 and num2 and store it in nextNum.
  • We print nextNum using print().
  • We update num1 with the value of num2 and num2 with the value of nextNum to generate the next numbers in the series.
  • The loop continues until num2 exceeds "n".

Go to:


PREV : Print Pascal's Triangle for a given number of rows.
NEXT : Calculate the sum of numbers between a given range.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.