<h4>4. Write a function that will calculate the sum of the first 12 even
Fibonacci numbers</h4>
<p>Recall that the Fibonacci sequence is a series that begins with two
integers: 0, 1. The next number in the sequence is derived by adding the
previous two numbers, so the Fibonacci sequence looks like this: 0, 1,
1, 2, 3, 5, 8, 13, 21, 34, ... </p>
<p>The button below will run your function, called twelveEvenFibonacciSum()
and print its result in the space provided. All you have to do is write
the function, which accepts no arguments, and returns the sum of the
first 12 even Fibonacci numbers. Your code will go in
js/hw2TwelveEvenFib.js </p>
<p>Hint: First you'll need a loop that generates Fibonacci numbers. You'll
need a way to test each one for whether it's even or odd. And you'll
need to sum up the even ones, counting them as you go. Count zero as the
first even number in the sequence. </p>
<button id="sumFib">Get the Sum!</button>
<br>
The sum of the first 12 even Fibonacci numbers is: <span class="" id="sumFibResult"></span>
<br>
<br>
JavaScript
"use strict";
console.clear();
// find first 12 even numbers
var totalToFind = 12;
var totalFound = 0;
var currentIndex = 0;
var sum =0;
var numbers = [];
while (totalFound < totalToFind) {
// check if even
if (currentIndex % 2==0) {
numbers.push(currentIndex);
totalFound++; // bump for next loop
sum+=currentIndex;
}
currentIndex++; // bum for next loop
}
console.log(numbers.length);
console.log(numbers);
var len = numbers.length;
var sumFib = 0;
for (var i = 0; i < len; i++) {
sum += numbers[i];
}
console.log(sum);
// first we get the HTML for the button
var getFibSum = document.getElementById("sumFib");
//then we set the event handler for when the button is clicked
getFibSum.onclick = function(){
function twelveEvenFibonacciSum(){
document.getElementById("sumFibResult").innerHTML = "sumFib";
}
// twelveEvenFibonacciSum
/*function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}*/
//
// return twelveEvenFibonacciSum;
//}
/*
* twelveEvenFibonacciSum - calulates the sum of the first 12 even fibonacci numbers, with 0, 1 being the first two numbers of the sequence
*
* @returns {integer} The sum of the first 12 even Fibonacci numbers
*/
/// WRITE YOUR CODE HERE
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.