JavaScript(JS) JS print the fibonacci sequence
Here's an example of how to print the Fibonacci sequence in JavaScript:
function fibonacci(num) { if (num <= 1) { return num; } else { return fibonacci(num - 1) + fibonacci(num - 2); } } function printFibonacciSequence(count) { for (let i = 0; i < count; i++) { console.log(fibonacci(i)); } } printFibonacciSequence(10); // Output: 0 1 1 2 3 5 8 13 21 34Source:www.theitroad.com
In the above example, we define a function called fibonacci
that takes a number num
as its argument. If num
is 0
or 1
, we simply return the value of num
. Otherwise, we recursively call fibonacci
with arguments of num - 1
and num - 2
, and add the results together to get the nth Fibonacci number.
We then define a function called printFibonacciSequence
that takes a number count
as its argument. We use a for
loop to iterate count
times. For each iteration, we call the fibonacci
function with the current iteration number i
and log the result to the console using console.log()
.
Once the loop finishes, we have printed the first count
numbers of the Fibonacci sequence to the console.
We then call the printFibonacciSequence
function with an argument of 10
, which prints the first 10
numbers of the Fibonacci sequence to the console in order. You can replace the value of the argument with any other number to print a different number of Fibonacci numbers.