Calculate and Print the Sum of the Fibonacci Series Less than 100 in JavaScript

  • Post author:
  • Post comments:0 Comments
  • Reading time:15 mins read

In this program, we will be calculating and print the sum of the Fibonacci series less than 100. The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, starting with 0 and 1. For example, the first 10 numbers in the Fibonacci series are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. Using a while loop, we will iterate through the series, adding up the numbers that are less than 100 and printing the final sum to the console. Let’s get started!

Here is a JavaScript program that will calculate and print the sum of the Fibonacci series less than 100:


function sumFibonacci() {
  let sum = 0;
  let current = 1;
  let previous = 0;

  while (current < 100) {
    sum += current;
    let temp = current;
    current += previous;
    previous = temp;
  }

  console.log(sum);
}

sumFibonacci();

Now let’s understand How the program works

This function first declares and initializes three variables: sum, current, and previous. sum will be used to store the sum of the Fibonacci numbers less than 100, current will keep track of the current Fibonacci number, and previous will keep track of the previous Fibonacci number.

The function then enters a while loop that continues until current is greater than or equal to 100. On each iteration of the loop, it adds the value of current to sum and updates the values of current and previous to be the sum of the two previous numbers.

After the while loop completes, the function prints the value of sum to the console.

Publisher

Publisher

Publisher @ideasorblogs

Leave a Reply