Kotlin Program to Display Fibonacci Series


In this article, we will understand how to find even sum of Fibonacci series till number N. A Fibonacci series is sequence of numbers formed by the sum of its two previous integers. An even Fibonacci series is all the even numbers of the Fibonacci series.

A Fibonacci series till number N i.e., 10 can look like this −

0 1 1 2 3 5 8 13 21 34

Below is a demonstration of the same −

Suppose our input is 

The input : 15

The desired output would be −

The Fibonacci series till 15 terms:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Algorithm

  • Step 1 − START

  • Step 2 − Declare three variables namely myInput, temp1 and temp2

  • Step 3 − Define the values

  • Step 4 − Use a for loop to iterate through the integers from 1 to N and assign the sum of consequent two numbers as the current Fibonacci number

  • Step 5 − Display the result

  • Step 6 − Stop

Example 1

In this example, we will calculate and display the Fibonacci Series using for loop. First, declare and initialize variables for the input, and two temporary variables. These two variables temp1 and temp2 will store the 1st and 2nd values of a Fibonacci.

val myInput = 15
var temp1 = 0
var temp2 = 1

Now, get the Fibonacci using for loop −

for (i in 1..myInput) {
   print("$temp1 ")
   val sum = temp1 + temp2
   temp1 = temp2
   temp2 = sum
}

Let us now display the Fibonacci Series −

fun main() { val myInput = 15 var temp1 = 0 var temp2 = 1 println("The number is defined as: $myInput") println("The Fibonacci series till $myInput terms:") for (i in 1..myInput) { print("$temp1 ") val sum = temp1 + temp2 temp1 = temp2 temp2 = sum } }

Output

The number is defined as: 15
The Fibonacci series till 15 terms:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 

Example 2

In this example, we will display a Fibonacci Series 

fun main() { val myInput = 15 println("The number is defined as: $myInput") fibonacciSeries(myInput) } fun fibonacciSeries(myInput: Int) { var temp1 = 0 var temp2 = 1 println("The fibonacci series till $myInput terms:") for (i in 1..myInput) { print("$temp1 ") val sum = temp1 + temp2 temp1 = temp2 temp2 = sum } }

Output

The number is defined as: 15
The fibonacci series till 15 terms:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 

Updated on: 17-Oct-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements