Programming with JavaScript

⌘K
  1. Home
  2. Docs
  3. Programming with JavaScri...
  4. Practice Programs
  5. Fibonacci series via Recursive Function

Fibonacci series via Recursive Function

Example: 3B

Write a recursive function in JavaScript to print Fibonacci series (prompt the input from user.

Script

function generateFibonacciSeries(numTerms) {
  const series = [];

  if (numTerms >= 1) {
    series.push(0); // First term of the Fibonacci series
  }
  if (numTerms >= 2) {
    series.push(1); // Second term of the Fibonacci series
  }

  for (let i = 2; i < numTerms; i++) {
    const nextTerm = series[i - 1] + series[i - 2];
    series.push(nextTerm);
  }

  return series;
}
const numTerms = 5;
const fibonacciSeries = generateFibonacciSeries(numTerms);
console.log(`Fibonacci series (${numTerms} terms): ${fibonacciSeries}`);

Output

Loading

Views: 9

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments