<h1>
Guessing Game
</h1>
<h3>
Enter a number between 1 and 1000
</h3>
<p>
Enter your number:
<input type="textbox" id="tbGuess" value="100"/>
</p>
<input type="button" id="btnGuess" value="Guess!" onclick="guess()"/>
<div id="output">
</div>
<div id="o">
</div>
JavaScript
//Global variable for array
var array = [];
//function that guesses the number in the textbox
function guess(){
//variable to hold output
var d = "";
//for loop to fill array from 1-1000
for(var i = 0; i <= 1000; i++){
array[i] = i;
}
//variables for counter, min, max, and textbox guess
var counter = 1;
var min = 0;
var max = 999;
var num = parseInt(document.getElementById("tbGuess").value);
//if else loop to text that the guess is inside the bounds of 1-1000
if (num < 1 || num > 1000){
alert("Please insert a number between 1 and 1000");
return;
}
else{
//while loop that consists of binary search algorithm
while (min<=max){
var cpuGuess = Math.ceil((min+max)/2);
if (cpuGuess<num){
d += "Guessed " + cpuGuess + " - too low. </br>";
min = cpuGuess + 1;
}
else if (cpuGuess>num){
d += "Guessed " + cpuGuess + " - too high. </br>";
max = cpuGuess - 1;
}
else if (cpuGuess==num){
d += "Guessed " + cpuGuess + " - Got It! </br> It took me " + counter + " Tries. </br>";
document.getElementById("output").innerHTML = d;
return;
}
counter++;
}
}
}
function addNode(){
var
}
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.