Table of Contents
show
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
Views: 9