Algorithm


  1. Initialize two variables, a and b, to 0 and 1 respectively.
  2. Prompt the user for the number of terms in the sequence, let's call it n.
  3. Print the values of a and b (the first two terms).
  4. Use a loop to generate the next n-2 terms in the sequence. a. Calculate the next term, c, as the sum of a and b. b. Set a to the current value of b. c. Set b to the current value of c. d. Print the value of c.
  5. End.

 

Code Examples

#1 Code Example- Fibonacci Series Up to n Terms

Code - Javascript Programming

// program to generate fibonacci series up to n terms

// take input from the user
const number = parseInt(prompt('Enter the number of terms: '));
let n1 = 0, n2 = 1, nextTerm;

console.log('Fibonacci Series:');

for (let i = 1; i  < = number; i++) {
    console.log(n1);
    nextTerm = n1 + n2;
    n1 = n2;
    n2 = nextTerm;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter the number of terms: 4
Fibonacci Series:
0
1
1
2

#2 Code Example- Fibonacci Sequence Up to a Certain Number

Code - Javascript Programming

// program to generate fibonacci series up to a certain number

// take input from the user
const number = parseInt(prompt('Enter a positive number: '));
let n1 = 0, n2 = 1, nextTerm;

console.log('Fibonacci Series:');
console.log(n1); // print 0
console.log(n2); // print 1

nextTerm = n1 + n2;

while (nextTerm  < = number) {

    // print the next term
    console.log(nextTerm);

    n1 = n2;
    n2 = nextTerm;
    nextTerm = n1 + n2;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a positive number: 5
Fibonacci Series:
0
1
1
2
3
5
Advertisements

Demonstration


JavaScript Programing Example to Print the Fibonacci Sequence-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way