Javascript - Coding an application that will calculate and display the Fibonacci sequence up to a maximum
Question:
Javascript - Coding an application that will calculate and display the Fibonacci sequence up to a maximum number of iterations
For Chapter 5, we will be coding an application that will calculate and display the Fibonacci sequence up to a maximum number of iterations that the user types in. If you are not familiar with the Fibonacci sequence, you can read more about it at:
https://en.wikipedia.org/wiki/Fibonacci_number
Essentially it is a sequence of numbers that begins with 0 and 1, and every following number is the sum of the previous 2 numbers, i.e. 0 + 1 = 1, 1 + 1 =2, 1 + 2 =3, and so on.
<!DOCTYPE html>
<html>
<head>
<title>Week 5 Programming Assignment</title>
</head>
<body>
<p>Registration Form</p>
<label for="txtIterations">Number of Iterations:</label>
<br/>
<input type="text" id="txtIterations" placeholder="Number of Iterations">
<br/>
<br/>
<button id="btnCompute">Compute</button>
<br/>
<br/>
<br/>
<div id="outputSequence">
</div>
<script>
function Compute_Fibonacci() {
//Create a variable for the output element, and empty any previous HTML in the element.
var output = document.getElementById('outputSequence');
output.innerHTML = '';
//0 and 1 are the first two numbers of the sequence. We will begin with those and use these variables to compute our sequence.
var number_1 = 0;
var number_2 = 1;
//Create a placeholder variable for adding the previous 2 numbers of the sequence together.
var sum = 0;
//Create a variable for the number of iterations we want, and remove 2 from it to account for the first two
//numbers of the sequence that we declared above.
var number_of_iterations = parseInt(document.getElementById('txtIterations').value);
number_of_iterations -= 2;
//Add the first two numbers of the sequence to our output.
//You can copy and paste one of these lines to add your output to the div, by replacing number_1 with sum
output.innerHTML += '<p>' + number_1 + '</p>';
output.innerHTML += '<p>' + number_2 + '</p>';
//Create your loop here. Don't forget to add the result of your calculation to the output.
}
/*************************************************************************
* The Function Below is to assign event handlers to the
* button on the page. You will not need to make any changes
* to this function
* *********************************************************************/
function init() {
var btnCompute = document.getElementById('btnCompute');
btnCompute.onclick = Compute_Fibonacci;
}
window.onload = init;
</script>
</body>
</html>
Management Science The Art of Modeling with Spreadsheets
ISBN: 978-1118582695
4th edition
Authors: Stephen G. Powell, Kenneth R. Baker