Algorithm
- Initialize two variables,
a
andb
, to 0 and 1 respectively. - Prompt the user for the number of terms in the sequence, let's call it
n
. - Print the values of
a
andb
(the first two terms). - Use a loop to generate the next
n-2
terms in the sequence. a. Calculate the next term,c
, as the sum ofa
andb
. b. Seta
to the current value ofb
. c. Setb
to the current value ofc
. d. Print the value ofc
. - 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
Enter the number of terms: 4
Fibonacci Series:
0
1
1
2
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
Enter a positive number: 5
Fibonacci Series:
0
1
1
2
3
5
Fibonacci Series:
0
1
1
2
3
5
Demonstration
JavaScript Programing Example to Print the Fibonacci Sequence-DevsEnv