rakesh830566

Fibonacci Series

Jun 2nd, 2020
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Take input a number from user
  2. var numberRegEx = /[+-]?([0-9]*[.])?[0-9]+/;
  3. var bool = true;
  4. var ahead = true;
  5. while (bool) {
  6.     var userInput = Number(prompt('Enter number of terms to print Fibonacci Series...'));
  7.     if (numberRegEx.test(userInput)) {
  8.         bool = false;
  9.     } else {
  10.         window.alert('Number is not valid!!');
  11.         bool = window.confirm('Do you want to enter again..');
  12.         ahead = bool;
  13.     }
  14. }
  15. if (ahead) {
  16.  
  17.     // Displaying number which is entered by user
  18.     document.write('Entered number by you = <strong>' + userInput + '</strong><br><br>');
  19.  
  20.     // Displaying Fibonacci series
  21.     var firstTerm = 0;
  22.     var secondTerm = 1;
  23.     var temp;
  24.     for (var i = 0; i <= userInput; i++) {
  25.         document.write(firstTerm); // here print the term of fibonacci series
  26.         if (i < userInput) {
  27.             document.write(', '); // here print "," (comma) if next term is exist otherwise not
  28.         }
  29.         temp = firstTerm; // here first term is stored in temporary variable
  30.         firstTerm = secondTerm; // here second term stored in first term
  31.         secondTerm = temp + firstTerm; // here add previous values of first and second term in second term
  32.     }
  33. }
Add Comment
Please, Sign In to add comment