Kotlin Program: Fibonacci series up to a given number
Write a Kotlin program to print the Fibonacci series up to a given number.
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".
Kotlin Editor:
Previous: Print Pascal's Triangle for a given number of rows.
Next: Calculate the sum of numbers between a given range.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics