Guess the number/With feedback: Difference between revisions

(Can't just add links to arbitrary code. If its your code and you want to add it to RC and it is sufficiently innovative compard to what is already here then please add your code (in the RC style).)
 
(80 intermediate revisions by 38 users not shown)
Line 15:
*   [[Guess the number/With Feedback (Player)]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V (target_min, target_max) = (1, 100)
 
print("Guess my target number that is between #. and #. (inclusive).\n".format(target_min, target_max))
V target = random:(target_min..target_max)
V (answer, i) = (target_min - 1, 0)
L answer != target
i++
V txt = input(‘Your guess(#.): ’.format(i))
X.try
answer = Int(txt)
X.catch ValueError
print(‘ I don't understand your input of '#.' ?’.format(txt))
L.continue
I answer < target_min | answer > target_max
print(‘ Out of range!’)
L.continue
I answer == target
print(‘ Ye-Haw!!’)
L.break
I answer < target {print(‘ Too low.’)}
I answer > target {print(‘ Too high.’)}
 
print("\nThanks for playing.")</syntaxhighlight>
 
{{out}}
<pre>
Guess my target number that is between 1 and 100 (inclusive).
 
Your guess(1): kk
I don't understand your input of 'kk' ?
Your guess(2): 0
Out of range!
Your guess(3): 100
Too high.
Your guess(4): 101
Out of range!
Your guess(5): 50
Too high.
Your guess(6): 25
Too high.
Your guess(7): 13
Too low.
Your guess(8): 16
Too low.
Your guess(9): 18
Too low.
Your guess(10): 20
Too low.
Your guess(11): 23
Too low.
Your guess(12): 24
Ye-Haw!!
 
Thanks for playing.
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
BYTE x,n,min=[1],max=[100]
 
PrintF("Try to guess a number %B-%B: ",min,max)
x=Rand(max-min+1)+min
DO
n=InputB()
IF n<min OR n>max THEN
Print("The input is incorrect. Try again: ")
ELSEIF n<x THEN
Print("My number is higher. Try again: ")
ELSEIF n>x THEN
Print("My number is lower. Try again: ")
ELSE
PrintE("Well guessed!")
EXIT
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Guess_the_number_with_feedback.png Screenshot from Atari 8-bit computer]
<pre>
Try to guess a number 1-100: 50
My number is lower. Try again: 25
My number is lower. Try again: 12
My number is higher. Try again: 19
My number is lower. Try again: 15
My number is lower. Try again: 14
Well guessed!
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
procedure Guess_Number_Feedback is
function Get_Int (Prompt : in String) return Integer is
begin
loop
Ada.Text_IO.Put (Prompt);
declare
Response : constant String := Ada.Text_IO.Get_Line;
begin
if Response /= "" then
return Integer'Value (Response);
end if;
exception
when others =>
Ada.Text_IO.Put_Line ("Invalid response, not an integer!");
end;
end loop;
end Get_Int;
procedure Guess_Number (Lower_Limit : Integer; Upper_Limit : Integer) is
subtype Number is Integer range Lower_Limit .. Upper_Limit;
package Number_IO is new Ada.Text_IO.Integer_IO (Number);
package Number_RNG is new Ada.Numerics.Discrete_Random (Number);
Generator : Number_RNG.Generator;
My_Number : Number;
Your_Guess : NumberInteger;
begin
Number_RNG.Reset (Generator);
Line 33 ⟶ 139:
Ada.Text_IO.Put_Line ("Guess my number!");
loop
Ada.Text_IO.PutYour_Guess := Get_Int ("Your guess: ");
Number_IO.Get (Your_Guess);
exit when Your_Guess = My_Number;
if Your_Guess > My_Number then
Line 44 ⟶ 149:
Ada.Text_IO.Put_Line ("Well guessed!");
end Guess_Number;
package Int_IO is new Ada.Text_IO.Integer_IO (Integer);
Lower_Limit : Integer;
Upper_Limit : Integer;
begin
loop
Ada.Text_IO.PutLower_Limit := Get_Int ("Lower Limit: ");
Int_IO.GetUpper_Limit := Get_Int (Lower_Limit"Upper Limit: ");
Ada.Text_IO.Put ("Upper Limit: ");
Int_IO.Get (Upper_Limit);
exit when Lower_Limit < Upper_Limit;
Ada.Text_IO.Put_Line ("Lower limit must be lower!");
end loop;
Guess_Number (Lower_Limit, Upper_Limit);
end Guess_Number_Feedback;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># simple guess-the-number game #
 
main:(
Line 107 ⟶ 209:
OD;
print( ( "That's correct!", newline ) )
)</langsyntaxhighlight>
{{out}}
<pre>
Line 133 ⟶ 235:
=={{header|AppleScript}}==
 
<langsyntaxhighlight AppleScriptlang="applescript">-- defining the range of the number to be guessed
property minLimit : 1
property maxLimit : 100
Line 171 ⟶ 273:
end try
end repeat
end run</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">n: random 1 10
while ø [
try? [
num: to :integer input "Guess the number: " n
case [num]
when? [=n][print "\tWell Guessed! :)", exit]
when? [>n][print "\tHigher than the target..."]
when? [<n][print "\tLess than the target..."]
else []
]
else -> print "\tInvalid input!"
]</syntaxhighlight>
 
{{out}}
 
<pre>Guess the number: 3
Less than the target...
Guess the number: 9
Higher than the target...
Guess the number: something
Invalid input!
Guess the number: 5
Less than the target...
Guess the number: 7
Well Guessed! :)</pre>
 
=={{header|AutoHotkey}}==
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">MinNum = 1
MaxNum = 99999999999
 
Line 205 ⟶ 335:
}
TotalTime := Round((A_TickCount - TotalTime) / 1000,1)
MsgBox, 64, Correct, The number %RandNum% was guessed in %Tries% tries, which took %TotalTime% seconds.</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f GUESS_THE_NUMBER_WITH_FEEDBACK.AWK
BEGIN {
Line 237 ⟶ 367:
exit(0)
}
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">100 L% = 1
110 U% = 10
120 N% = RND(1) * (U% - L% + 1) + L%
Line 255 ⟶ 384:
210 Q = G% = N%
220 NEXT
230 PRINT "THE GUESS WAS EQUAL TO THE TARGET."</langsyntaxhighlight>
 
==={{header|BASIC256}}===
{{works with|BASIC256 }}
<langsyntaxhighlight lang="basic256">Min = 5: Max = 15
Min = 5: Max = 15
chosen = int(rand*(Max-Min+1)) + Min
print "Guess a whole number between "+Min+" and "+Max
Line 273 ⟶ 401:
if guess = chosen then print "Well guessed!"
end if
until guess = chosen</syntaxhighlight>
</lang>
Output:(example)
<pre>Guess a whole number between 5 and 15
<pre>
Guess a whole number between 5 and 15
Enter your number 10
Sorry, your number was too high
Line 283 ⟶ 409:
Sorry, your number was too low
Enter your number 8
Well guessed!</pre>
 
</pre>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="vbnet">100 cls
110 nmax = 20
120 chosen = int(rnd(1)*nmax)+1
130 print "Guess a whole number between 1 a ";nmax;chr$(10)
140 do
150 input "Enter your number: ",guess
160 if guess < n or guess > nmax then
170 print "That was an invalid number"
180 exit do
190 else
200 if guess < chosen then print "Sorry, your number was too low"
210 if guess > chosen then print "Sorry, your number was too high"
220 if guess = chosen then print "Well guessed!"
230 endif
240 loop until guess = chosen
250 end</syntaxhighlight>
 
==={{header|Gambas}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Public Sub Main()
Randomize
Dim guess As Integer, max As Integer = 20
Dim n As Integer = Int(Rnd * max) + 1
Print "Guess which number I've chosen in the range 1 to "; max; Chr(10)
Do
Print " Your guess : "
Input guess
If guess > n And guess <= 20 Then
Print "Your guess is higher than the chosen number, try again"
Else If guess = n Then
Print "Correct, well guessed!"
Break
Else If guess < n And guess >= 1 Then
Print "Your guess is lower than the chosen number, try again"
Else
Print "Your guess is inappropriate, try again"
End If
Loop
 
End</syntaxhighlight>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
<syntaxhighlight lang="qbasic">100 CLS
110 RANDOMIZE 1
120 L = 20
130 X = INT(RND(1)*L)+1
140 PRINT "Guess a whole number between 1 a ";L;CHR$(10)
150 'do
160 INPUT "Enter your number: ", N
170 IF N < N OR N > L THEN PRINT "That was an invalid number" : GOTO 230
180 'else
190 IF N < X THEN PRINT "Sorry, your number was too low"
200 IF N > X THEN PRINT "Sorry, your number was too high"
210 IF N = X THEN PRINT "Well guessed!"
220 IF N <> X THEN GOTO 150
230 END</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Guess.bas"
110 RANDOMIZE
120 LET UP=10:LET LO=1 ! Limits
Line 303 ⟶ 492:
240 PRINT "Well guessed! Numner of tips:";COUNT
250 END SELECT
260 LOOP UNTIL NR=GU</langsyntaxhighlight>
 
==={{header|Minimal BASIC}}===
{{trans|Tiny Craft Basic}}
<syntaxhighlight lang="qbasic">100 RANDOMIZE
110 LET T = 0
120 LET N = 20
130 LET R = INT(RND*N)+1
140 PRINT "GUESS A WHOLE NUMBER BETWEEN 1 AND";N
150 LET T = T+1
160 PRINT "ENTER YOUR NUMBER ";
170 INPUT G
180 IF G <> R THEN 210
190 PRINT "YOU GUESSED IT IN";T;"TRIES."
200 GOTO 310
210 IF G > R THEN 240
220 IF G < 1 THEN 240
230 PRINT "SORRY, YOUR NUMBER WAS TOO LOW"
240 IF G < R THEN 270
250 IF G > 100 THEN 270
260 PRINT "SORRY, YOUR NUMBER WAS TOO HIGH"
270 IF G >= 1 THEN 300
280 IF G <= 100 THEN 300
290 PRINT "THAT WAS AN INVALID NUMBER"
300 IF G <> R THEN 140
310 END</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="qbasic">100 CLS
120 L = 20
130 X = INT(RND(1)*L)+1
140 PRINT "Guess a whole number between 1 a ";L;CHR$(10)
150 'do
160 INPUT "Enter your number: "; N
170 IF N < N OR N > L THEN PRINT "That was an invalid number" : GOTO 230
180 'else
190 IF N < X THEN PRINT "Sorry, your number was too low"
200 IF N > X THEN PRINT "Sorry, your number was too high"
210 IF N = X THEN PRINT "Well guessed!"
220 IF N <> X THEN GOTO 150
230 END</syntaxhighlight>
 
==={{header|QB64}}===
Note that <code>INPUT</code> only allows the user to type things that can fit in the variable it's storing to. Since we're storing to a byte, we don't have to worry about the user typing any non-numbers.
<syntaxhighlight lang="qbasic">DIM secretNumber AS _BYTE ' the secret number
DIM guess AS _BYTE ' the player's guess
 
RANDOMIZE TIMER ' set a seed based on system time
secretNumber%% = INT(RND * 10) + 1 ' a random value between 1 and 10
PRINT "The computer has chosen a secret number between 1 and 10."
DO
PRINT "What is your guess";
INPUT guess%%
SELECT CASE guess%%
CASE IS < 1, IS > 10
PRINT "Please enter a number between 1 and 10!"
_CONTINUE
CASE IS < secretNumber%%
PRINT "Your guess is LOWER than the target."
CASE IS > secretNumber%%
PRINT "Your guess is HIGHER than the target."
END SELECT
LOOP UNTIL guess%% = secretNumber%%
PRINT "You won!"; secretNumber%%; "was the secret number!"</syntaxhighlight>
{{out}}
<pre>The computer has chosen a secret number between 1 and 10.
What is your guess? -1
Please enter a number between 1 and 10!
What is your guess? 11
Please enter a number between 1 and 10!
What is your guess? 1
Your guess is LOWER than the target.
What is your guess? 10
Your guess is HIGHER than the target.
What is your guess? 5
Your guess is HIGHER than the target.
What is your guess? 3
Your guess is HIGHER than the target.
What is your guess? 2
You won! 2 was the secret number!</pre>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">CLS
RANDOMIZE TIMER ' set a seed based on system time
nmax = 20
chosen = INT(RND * nmax) + 1
 
PRINT "Guess a whole number between 1 a"; nmax; CHR$(10)
DO
INPUT "Enter your number"; guess
IF guess < n OR guess > nmax THEN
PRINT "That was an invalid number"
EXIT DO
ELSE
IF guess < chosen THEN PRINT "Sorry, your number was too low"
IF guess > chosen THEN PRINT "Sorry, your number was too high"
IF guess = chosen THEN PRINT "Well guessed!"
END IF
LOOP UNTIL guess = chosen
END</syntaxhighlight>
 
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
<syntaxhighlight lang="vb">nmin = 5
nmax = 15
chosen = int( rnd( 1) * (nmax-nmin+1)) +nmin
print "Guess a whole number between "; nmin; " and "; nmax
[loop]
input "Enter your number "; guess
if guess < nmin or guess > nmax then
print "That was an invalid number"
end
else
if guess < chosen then print "Sorry, your number was too low"
if guess > chosen then print "Sorry, your number was too high"
if guess = chosen then print "Well guessed!": end
end if
if guess <> chosen then [loop]</syntaxhighlight>
 
==={{header|True BASIC}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">RANDOMIZE
LET nmax = 20
LET chosen = int(rnd*nmax)+1
PRINT "Guess a whole number between 1 a"; nmax; chr$(10)
DO
INPUT prompt "Enter your number ": guess
IF guess < n or guess > nmax then
PRINT "That was an invalid number"
EXIT DO
ELSE
IF guess < chosen then PRINT "Sorry, your number was too low"
IF guess > chosen then PRINT "Sorry, your number was too high"
IF guess = chosen then PRINT "Well guessed!"
END IF
LOOP until guess = chosen
END</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="vb">nmin = 5
nmax = 15
chosen = int(ran(nmax-nmin+1)) + nmin
print "Guess a whole number between ", nmin, " and ", nmax
repeat
input "Enter your number " guess
if guess < nmin or guess > nmax then
print "That was an invalid number"
end
else
if guess < chosen print "Sorry, your number was too low"
if guess > chosen print "Sorry, your number was too high"
if guess = chosen print "Well guessed!"
fi
until guess = chosen</syntaxhighlight>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
 
:A
Line 322 ⟶ 668:
echo You won! The number was %number%
pause>nul
goto A</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> Min% = 1
Max% = 10
chosen% = RND(Max%-Min%+1) + Min% - 1
Line 343 ⟶ 689:
ENDCASE
UNTIL FALSE
END</langsyntaxhighlight>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
static $( randstate = ? $)
 
let rand(min,max) = valof
$( let x = ?
let range = max-min
let mask = 1
while mask < range do mask := (mask << 1) | 1
$( randstate := random(randstate)
x := (randstate >> 6) & mask
$) repeatuntil 0 <= x < range
resultis x + min
$)
 
let readguess(min,max) = valof
$( let x = ?
writes("Guess? ")
x := readn()
if min <= x < max then resultis x
writes("Invalid input.*N")
$) repeat
 
let play(min,max,secret) be
$( let tries, guess = 0, ?
$( guess := readguess(min,max)
if guess < secret then writes("Too low!*N")
if guess > secret then writes("Too high!*N")
tries := tries + 1
$) repeatuntil guess = secret
writef("Correct! You guessed it in %N tries.*N", tries)
$)
 
let start() be
$( let min, max = ?, ?
writes("Guess the number*N*N")
writes("Random seed? ") ; randstate := readn()
$( writes("Lower bound? ") ; min := readn()
writes("Upper bound? ") ; max := readn() + 1
test max-1 > min break or writes("Invalid bounds.*N")
$) repeat
wrch('*N')
play(min, max, rand(min, max))
$)</syntaxhighlight>
{{out}}
<pre>Guess the number
 
Random seed? 12345
Lower bound? 1
Upper bound? 100
 
Guess? 0
Invalid input.
Guess? 101
Invalid input.
Guess? 50
Too low!
Guess? 75
Too high!
Guess? 62
Too high!
Guess? 56
Too high!
Guess? 53
Too high!
Guess? 52
Correct! You guessed it in 6 tries.</pre>
=={{header|Befunge}}==
 
The number range is hardcoded at the start of the program (<tt>1:"d"</tt> being 1 to 100), but can easily be changed.
 
<langsyntaxhighlight lang="befunge">1:"d">>048*"neewteb rebmun a sseuG">:#,_$\:.\"d na",,\,,:.55+,\-88+0v
<*2\_$\1+%+48*">",,#v>#+:&#>#5-:!_0`00p0"hgih"00g>_0"wol"00g!>_48vv1?
\1-:^v"d correctly!"<^,,\,+55,". >"$_,#!>#:<"Your guess was too"*<>+>
:#,_@>"ess" >"eug uoY"></langsyntaxhighlight>
 
{{out}}
Line 366 ⟶ 779:
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">number = random 10
 
p "Guess a number between 1 and 10."
Line 382 ⟶ 795:
}
}
}</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <time.h>
Line 399 ⟶ 812:
 
printf( "Guess the number between %d and %d: ", lower_limit, upper_limit );
fflush(stdout); // Flush the output buffer
 
while( scanf( "%d", &guess ) == 1 ){
Line 409 ⟶ 823:
 
return 0;
}</langsyntaxhighlight>
 
Demonstration:
Line 426 ⟶ 840:
Try again: 59
You guessed correctly!</pre>
 
=={{header|C++}}==
<lang cpp>#include <iostream>
#include <cstdlib>
#include <ctime>
 
int main()
{
std::srand(std::time(0));
int lower, upper, guess;
std::cout << "Enter lower limit: ";
std::cin >> lower;
std::cout << "Enter upper limit: ";
std::cin >> upper;
int random_number = lower + std::rand() % ((upper + 1) - lower);
 
do
{
std::cout << "Guess what number I have: ";
std::cin >> guess;
if (guess > random_number)
std::cout << "Your guess is too high\n";
else if (guess < random_number)
std::cout << "Your guess is too low\n";
else
std::cout << "You got it!\n";
} while (guess != random_number);
 
return 0;
}</lang>
Output:
<pre>Enter lower limit: 1
Enter upper limit: 100
Guess what number I have: 50
Your guess is too high
Guess what number I have: 40
Your guess is too high
Guess what number I have: 25
Your guess is too high
Guess what number I have: 10
Your guess is too high
Guess what number I have: 2
Your guess is too low
Guess what number I have: 4
Your guess is too high
Guess what number I have: 3
You got it!</pre>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 514 ⟶ 881:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>The number is between 1 and 10. Make a guess: 1
Line 531 ⟶ 898:
Press any key to exit.
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <cstdlib>
#include <ctime>
 
int main()
{
std::srand(std::time(0));
int lower, upper, guess;
std::cout << "Enter lower limit: ";
std::cin >> lower;
std::cout << "Enter upper limit: ";
std::cin >> upper;
int random_number = lower + std::rand() % ((upper + 1) - lower);
 
do
{
std::cout << "Guess what number I have: ";
std::cin >> guess;
if (guess > random_number)
std::cout << "Your guess is too high\n";
else if (guess < random_number)
std::cout << "Your guess is too low\n";
else
std::cout << "You got it!\n";
} while (guess != random_number);
 
return 0;
}</syntaxhighlight>
Output:
<pre>Enter lower limit: 1
Enter upper limit: 100
Guess what number I have: 50
Your guess is too high
Guess what number I have: 40
Your guess is too high
Guess what number I have: 25
Your guess is too high
Guess what number I have: 10
Your guess is too high
Guess what number I have: 2
Your guess is too low
Guess what number I have: 4
Your guess is too high
Guess what number I have: 3
You got it!</pre>
 
=={{header|Caché ObjectScript}}==
<syntaxhighlight lang="caché objectscript">GUESSNUM
; get a random number between 1 and 100
set target = ($random(100) + 1) ; $r(100) gives 0-99
; loop until correct
set tries = 0
for {
write !,"Guess the integer between 1 and 100: "
read "",guess ; gets input following write
; validate input
if (guess?.N) && (guess > 0) && (guess < 101) {
; increment attempts
set tries = tries + 1
; evaluate the guess
set resp = $select(guess < target:"too low.",guess > target:"too high.",1:"correct!")
; display result, conditionally exit loop
write !,"Your guess was "_resp
quit:resp="correct!"
}
else {
write !,"Please enter an integer between 1 and 100."
}
} ; guess loop
write !!,"You guessed the number in "_tries_" attempts."
quit</syntaxhighlight>
 
{{out}}<pre>SAMPLES>do ^GUESSNUM^
 
Guess the integer between 1 and 100: 50
Your guess was too low.
Guess the integer between 1 and 100: 75
Your guess was too high.
Guess the integer between 1 and 100: 60
Your guess was too low.
Guess the integer between 1 and 100: 65
Your guess was too low.
Guess the integer between 1 and 100: 70
Your guess was too low.
Guess the integer between 1 and 100: 73
Your guess was too low.
Guess the integer between 1 and 100: 74
Your guess was correct!
 
You guessed the number in 7 attempts.</pre>
 
=={{header|Ceylon}}==
Line 536 ⟶ 1,000:
In you module.ceylon file put import ceylon.random "1.3.1";
 
<langsyntaxhighlight lang="ceylon">import ceylon.random {
DefaultRandom
}
Line 572 ⟶ 1,036:
}
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn guess-run []
(let [start 1
end 100
Line 590 ⟶ 1,054:
:else true)
(println "Correct")
(recur (inc i)))))))</langsyntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">read_number = proc (prompt: string) returns (int)
po: stream := stream$primary_output()
pi: stream := stream$primary_input()
while true do
stream$puts(po, prompt)
return(int$parse(stream$getl(pi)))
except when bad_format:
stream$putl(po, "Invalid number.")
end
end
end read_number
read_limits = proc () returns (int,int)
po: stream := stream$primary_output()
while true do
min: int := read_number("Lower limit? ")
max: int := read_number("Upper limit? ")
if min >= 0 cand min < max then return(min,max) end
stream$putl(po, "Invalid limits, try again.")
end
end read_limits
 
read_guess = proc (min, max: int) returns (int)
po: stream := stream$primary_output()
while true do
guess: int := read_number("Guess? ")
if min <= guess cand max >= guess then return(guess) end
stream$putl(po, "Guess must be between "
|| int$unparse(min) || " and " || int$unparse(max) || ".")
end
end read_guess
play_game = proc (min, max, secret: int)
po: stream := stream$primary_output()
guesses: int := 0
while true do
guesses := guesses + 1
guess: int := read_guess(min, max)
if guess = secret then break
elseif guess < secret then stream$putl(po, "Too low!")
elseif guess > secret then stream$putl(po, "Too high!")
end
end
stream$putl(po, "Correct! You got it in " || int$unparse(guesses) || " tries.")
end play_game
start_up = proc ()
po: stream := stream$primary_output()
d: date := now()
random$seed(d.second + 60*(d.minute + 60*d.hour))
stream$putl(po, "Guess the number\n----- --- ------\n")
min, max: int := read_limits()
secret: int := min + random$next(max - min + 1)
play_game(min, max, secret)
end start_up</syntaxhighlight>
{{out}}
<pre>Guess the number
----- --- ------
 
Lower limit? 1
Upper limit? 100
Guess? 50
Too high!
Guess? 25
Too high!
Guess? 12
Too low!
Guess? 18
Too low!
Guess? 22
Too high!
Guess? 20
Too low!
Guess? 21
Correct! You got it in 7 tries.</pre>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Guess-With-Feedback.
 
Line 622 ⟶ 1,164:
GOBACK
.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun guess-the-number-feedback (&optional (min 1) (max 100))
(let ((num-guesses 0)
(num (+ (random (1+ (- max min))) min))
Line 641 ⟶ 1,183:
(= guess num)))
(format t "You got the number correct on the ~:r guess!~%" num-guesses)))
</syntaxhighlight>
</lang>
Output:
<pre>CL-USER> (guess-the-number-feedback 1 1024)
Line 663 ⟶ 1,205:
You got the number correct on the eighth guess!
</pre>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">let n = int(rnd * 100) + 1
 
do
 
let t = t + 1
 
input "guess the number between 1 and 100", g
 
if g < n then
 
alert "guess higher"
 
endif
 
if g > n then
 
alert "guess lower"
 
endif
 
loop g <> n
 
alert "you guessed the number in ", t, " tries"</syntaxhighlight>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<syntaxhighlight lang="ruby">number = rand(1..10)
 
puts "Guess the number between 1 and 10"
 
loop do
begin
user_number = gets.to_s.to_i
if user_number == number
puts "You guessed it."
break
elsif user_number > number
puts "Too high."
else
puts "Too low."
end
rescue ArgumentError
puts "Please enter an integer."
end
end</syntaxhighlight>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.typecons, std.conv, std.string,
std.range;
 
Line 696 ⟶ 1,285:
writeln(answer < target ? " Too low." : " Too high.");
}
}</langsyntaxhighlight>
Sample game:
<pre>Guess my target number that is between 1 and 100 (inclusive).
Line 718 ⟶ 1,307:
Your guess #9: 83
Well Guessed.</pre>
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ rnd = f$extract( 21, 2, f$time() )
$ count = 0
$ loop:
Line 733 ⟶ 1,323:
$ if guess .gt. rnd then $ write sys$output "too large"
$ if guess .ne. rnd then $ goto loop
$ write sys$output "it only took you ", count, " guesses"</langsyntaxhighlight>
{{out}}
<pre>$ @guess
Line 755 ⟶ 1,345:
=={{header|Delphi}}==
 
<langsyntaxhighlight Delphilang="delphi">program GuessTheNumber;
 
{$APPTYPE CONSOLE}
Line 840 ⟶ 1,430:
 
end.
</syntaxhighlight>
</lang>
 
=={{header|EasyLang}}==
<syntaxhighlight>
print "Guess a number between 1 and 100!"
n = randint 100
repeat
g = number input
write g
if error = 1
print "You must enter a number!"
elif g > n
print " is too high"
elif g < n
print " is too low"
.
until g = n
.
print " is correct"
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
;;(read <default-value> <prompt>) prompts the user with a default value using the browser dialog box.
;; we play sounds to make this look like an arcade game
Line 862 ⟶ 1,470:
(play-sound 'ok )
" 🔮 Well played!! 🍒 🍇 🍓")
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
 
<langsyntaxhighlight lang="ela">open string datetime random core monad io
 
guess () = do
Line 901 ⟶ 1,509:
ask ()
 
guess () ::: IO</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 36.4x :
<langsyntaxhighlight lang="elena">import extensions.;
public program()
{
[
int randomNumber := randomGenerator eval.nextInt(1,10).;
console .printLine("I'm thinking of a number between 1 and 10. Can you guess it?").;
bool numberCorrect := false.;
until(numberCorrect)
[{
console .print("Guess: ").;
int userGuess := console .readLine; toInt().toInt();
if (randomNumber == userGuess)
[{
numberCorrect := true.;
console .printLine("Congrats!! You guessed right!")
];}
else if (randomNumber < userGuess)
[{
console .printLine("Your guess was too high")
];}
[else
{
console printLine("Your guess was too low")
console.printLine("Your guess was too low")
]
] }
}
]</lang>
}</syntaxhighlight>
{{out}}
<pre>
Line 942 ⟶ 1,552:
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<langsyntaxhighlight lang="elixir">defmodule GuessingGame do
def play(lower, upper) do
play(lower, upper, Enum.random(lower .. upper))
Line 961 ⟶ 1,571:
end
GuessingGame.play(1, 100)</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(let* ((min 1)
<lang Lisp>
(let ((num (1+ (randommax 100))))
(number (+ (random (1+ (- max min))) min))
(princ "Guess the no: ")
guess done)
(loop
(message "Guess the number between %d and %d" min max)
(setq guess (read))
(while (condnot done)
((not (numberpsetq guess)) (printread-number "Please enter a number "))
(cond
((eq guess num)
((< guess number)
(progn (princ-list "Guess was right! " num)
(returnmessage "Too low!")))
((> guess numnumber)
(printmessage "Too Highhigh!"))
((<= guess numnumber)
(printsetq "Too low!"))) )done t)</lang>
(message "Well guessed!")))))</syntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(guess_number).
-export([main/0]).
Line 1,007 ⟶ 1,618:
guess(N)
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>1> c(guess_number).
Line 1,027 ⟶ 1,638:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include get.e
 
constant lower_limit = 0, upper_limit = 100
Line 1,045 ⟶ 1,656:
puts(1,"You guessed to low.\nTry again: ")
end if
end while</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
open System
 
[<EntryPoint>]
let main argv =
let aim =
let from = 1
let upto = 100
let rnd = System.Random()
Console.WriteLine("Hi, you have to guess a number between {0} and {1}",from,upto)
rnd.Next(from,upto)
 
let mutable correct = false
while not correct do
 
let guess =
Console.WriteLine("Please enter your guess:")
match System.Int32.TryParse(Console.ReadLine()) with
| true, number -> Some(number)
| false,_ -> None
 
match guess with
| Some(number) ->
match number with
| number when number > aim -> Console.WriteLine("You guessed to high!")
| number when number < aim -> Console.WriteLine("You guessed to low!")
| _ -> Console.WriteLine("You guessed right!")
correct <- true
| None -> Console.WriteLine("Error: You didn't entered a parsable number!")
0
</syntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING:
formatting
fry
Line 1,073 ⟶ 1,718:
[ unparse "Number in range %s, your guess?\n" printf flush ]
[ random '[ _ game-step ] loop ]
bi ;</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,114 ⟶ 1,759:
}
}
</syntaxhighlight>
</lang>
 
Sample game:
Line 1,140 ⟶ 1,785:
Well guessed!
</pre>
 
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.01 S T=0
01.02 A "LOWER LIMIT",L
01.03 A "UPPER LIMIT",H
01.04 I (H-L)1.05,1.05,1.06
01.05 T "INVALID RANGE",!;G 1.02
01.06 S S=FITR(L+FRAN()*(H-L+1))
01.10 A "GUESS",G
01.11 I (H-G)1.13,1.12,1.12
01.12 I (G-L)1.13,1.14,1.14
01.13 T "OUT OF RANGE",!;G 1.1
01.14 S T=T+1
01.15 I (G-S)1.16,1.17,1.18
01.16 T "TOO LOW!",!;G 1.1
01.17 T "CORRECT! GUESSES",%4,T,!;Q
01.18 T "TOO HIGH!",!;G 1.1</syntaxhighlight>
 
{{out}}
 
<pre>LOWER LIMIT:1
UPPER LIMIT:100
GUESS:0
OUT OF RANGE
GUESS:101
OUT OF RANGE
GUESS:50
TOO LOW!
GUESS:75
TOO LOW!
GUESS:87
TOO LOW!
GUESS:94
TOO HIGH!
GUESS:90
CORRECT! GUESSES= 5</pre>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program Guess_a_number
implicit none
Line 1,169 ⟶ 1,850:
end if
end do
end program</langsyntaxhighlight>
Output
<pre>I have chosen a number bewteen 1 and 100 and you have to try to guess it.
Line 1,187 ⟶ 1,868:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Randomize
Line 1,208 ⟶ 1,889:
End If
Loop
End</langsyntaxhighlight>
 
Sample input/output
Line 1,222 ⟶ 1,903:
Correct, well guessed!
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">// Guess a Number with feedback.
target = random[1,100] // Min and max are both inclusive for the random function
guess = 0
println["Welcome to guess a number! I've picked a number between 1 and 100. Try to guess it!"]
while guess != target
{
guessStr = input["What is your guess?"]
guess = parseInt[guessStr]
if guess == undef
{
println["$guessStr is not a valid guess. Please enter a number from 1 to 100."]
next
}
if guess < target
println["My number is higher than $guess."]
if guess > target
println["My number is lower than $guess."]
if guess == target
println["$guess is correct! Well guessed!"]
}
</syntaxhighlight>
{{out}}
Including an example with a non-integer entered.
<pre>Welcome to guess a number! I've picked a number between 1 and 100. Try to guess it!
My number is lower than 50.
My number is higher than 25.
ABC is not a valid guess. Please enter a number from 1 to 100.
My number is lower than 37.
My number is higher than 31.
34 is correct! Well guessed!
</pre>
 
=={{header|FTCBASIC}}==
<syntaxhighlight lang="basic">rem Hilo number guessing game
rem compile with FTCBASIC to 704 bytes com program file
 
use time.inc
use random.inc
 
define try = 0, tries = 0, game = 0
 
gosub systemtime
 
let randseed = loworder
let randlimit = 100
 
do
 
gosub intro
gosub play
gosub continue
 
loop try = 0
 
end
 
sub intro
 
bell
cls
print "Hilo game"
crlf
 
return
 
sub play
 
gosub generaterand
 
+1 rand
0 tries
let game = 1
 
print "Guess the number between 1 and 100"
crlf
 
do
 
+1 tries
 
input try
crlf
 
if try = rand then
 
let game = 0
 
print "You guessed the number!"
print "Tries: " \
print tries
 
endif
 
if game = 1 then
 
if try > rand then
 
print "Try lower..."
 
endif
 
if try < rand then
 
print "Try higher..."
 
endif
 
endif
 
crlf
 
loop game = 1
 
return
 
sub continue
 
print "Enter 0 to play again or 1 to EXIT to DOS"
input try
 
return</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
Short n // We'll just do 1..10 to get the idea
 
void local fn BuildInterface
Short i
window 1, @"Guess the number", ( 0, 0, 340, 120 )
for i = 1 to 10
button i,,, fn StringWithFormat(@"%d", i), ( 26 * i, 60, 40, 22 )
ButtonSetBordered( i, No )
next
button 11,,, @"Quit", ( 38, 10, 95, 32 )
button 12,,, @"Again", ( 200, 10, 95, 32 )
textlabel 13, @"Guess the number:", ( 112, 85, 200, 22 )
textlabel 14,, ( 158, 30, 100, 22 ) // Hints here
filemenu 1 : menu 1, -1, No // Build but disable File menu
editmenu 2 : menu 2, -1, No // Build but disable Edit menu
end fn
 
void local fn newGame
CFRange r = fn RangeMake( 1, 10 )
ControlRangeSetEnabled( r, Yes ) // Enable number buttobns
button 11, No // Disable Quit button
button 12, No // Disable Again button
n = rnd( 10 ) // Choose a random number
textlabel 14, @"🔴" // Not found yet
end fn
 
void local fn DoDialog( evt as Long, tag as Long )
CFRange r = fn RangeMake( 1, 10 )
select evt
case _btnClick
button tag, No
select tag
case 11 : end // Quit
case 12 : fn newGame // Again
case n : textlabel 14, @"🟢" // Found
ControlRangeSetEnabled( r, No )
button 11, Yes
button 12, Yes
case < n : textlabel 14, @"➡️"
case > n : textlabel 14, @"⬅️"
end select
case _windowWillClose : end
end select
end fn
 
fn buildInterface
fn newGame
on dialog fn DoDialog
handleevents
 
</syntaxhighlight>
 
 
=={{header|Genie}}==
<syntaxhighlight lang="genie">[indent=4]
/*
Number guessing with feedback, in Genie
from https://wiki.gnome.org/Projects/Genie/AdvancedSample
 
valac numberGuessing.gs
./numberGuessing
*/
class NumberGuessing
 
prop min:int
prop max:int
construct(m:int, n:int)
self.min = m
self.max = n
def start()
try_count:int = 0
number:int = Random.int_range(min, max)
stdout.printf("Welcome to Number Guessing!\n\n")
stdout.printf("I have thought up a number between %d and %d\n", min, max)
stdout.printf("which you have to guess. I will give hints as we go.\n\n")
while true
stdout.printf("Try #%d, ", ++try_count)
stdout.printf("please enter a number between %d and %d: ", min, max)
line:string? = stdin.read_line()
if line is null
stdout.printf("bailing...\n")
break
 
input:int64 = 0
unparsed:string = ""
converted:bool = int64.try_parse(line, out input, out unparsed)
if not converted or line is unparsed
stdout.printf("Sorry, input seems invalid\n")
continue
 
guess:int = (int)input
if number is guess
stdout.printf("Congratulations! You win.\n")
break
else
stdout.printf("Try again. The number in mind is %s than %d.\n",
number > guess ? "greater" : "less", guess)
 
init
var game = new NumberGuessing(1, 100)
game.start()</syntaxhighlight>
 
{{out}}
<pre>prompt$ valac numberGuessing.gs
prompt$ ./numberGuessing
Welcome to Number Guessing!
 
I have thought up a number between 1 and 100
which you have to guess. I will give hints as we go.
 
Try #1, please enter a number between 1 and 100: 50
Try again. The number in mind is greater than 50.
Try #2, please enter a number between 1 and 100: abc
Sorry, input seems invalid
Try #3, please enter a number between 1 and 100: 75
Try again. The number in mind is greater than 75.
Try #4, please enter a number between 1 and 100: 88
Try again. The number in mind is less than 88.
Try #5, please enter a number between 1 and 100: 81
Try again. The number in mind is greater than 81.
Try #6, please enter a number between 1 and 100: 84
Try again. The number in mind is less than 84.
Try #7, please enter a number between 1 and 100: 82
Try again. The number in mind is greater than 82.
Try #8, please enter a number between 1 and 100: 83
Congratulations! You win.
 
prompt$ ./numberGuessing
Welcome to Number Guessing!
 
I have thought up a number between 1 and 100
which you have to guess. I will give hints as we go.
 
Try #1, please enter a number between 1 and 100: 50
Try again. The number in mind is greater than 50.
Try #2, please enter a number between 1 and 100: bailing...</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,252 ⟶ 2,199:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Based on the Java implementation
<langsyntaxhighlight lang="groovy">
def rand = new Random() // java.util.Random
def range = 1..100 // Range (inclusive)
Line 1,277 ⟶ 2,224:
}
}
</syntaxhighlight>
</lang>
Example:
<syntaxhighlight lang="text">
The number is in 1..100
Guess the number: ghfvkghj
Line 1,295 ⟶ 2,242:
Guess the number: 92
Your guess is spot on!
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">
import Control.Monad
import System.Random
Line 1,322 ⟶ 2,269:
putStrLn "Try to guess my secret number between 1 and 100."
ask `until_` answerIs ans
</syntaxhighlight>
</lang>
 
=={{header|HolyC}}==
<langsyntaxhighlight lang="holyc">U8 n, *g;
U8 min = 1, max = 100;
 
Line 1,344 ⟶ 2,291:
if (Str2I64(g) > n)
Print("Your guess was too high.\nTry again: ");
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
 
<syntaxhighlight lang="icon">
<lang Icon>
procedure main()
smallest := 5
Line 1,369 ⟶ 2,316:
}
end
</syntaxhighlight>
</lang>
 
Output:
Line 1,387 ⟶ 2,334:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">require 'misc'
game=: verb define
assert. y -: 1 >. <.{.y
Line 1,397 ⟶ 2,344:
smoutput (*x-n){::'You win.';'Too high.';'Too low.'
end.
)</langsyntaxhighlight>
 
Note: in computational contexts, J programmers typically avoid loops. However, in contexts which involve progressive input and output and where event handlers are too powerful (too complicated), loops are probably best practice.
Line 1,403 ⟶ 2,350:
Example use:
 
<syntaxhighlight lang="text"> game 100
Guess my integer, which is bounded by 1 and 100
Guess: 64
Line 1,414 ⟶ 2,361:
Too low.
Guess: 44
You win.</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight Javalang="java">import java.util.Random;
import java.util.Scanner;
public class Main
Line 1,444 ⟶ 2,391:
} while (guessedNumber != randomNumber);
}
}</langsyntaxhighlight>
Demonstration:
<pre>The number is between 1 and 100.
Line 1,461 ⟶ 2,408:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="html4strict"><p>Pick a number between 1 and 100.</p>
<form id="guessNumber">
<input type="text" name="guess">
Line 1,467 ⟶ 2,414:
</form>
<p id="output"></p>
<script type="text/javascript"></langsyntaxhighlight>
<langsyntaxhighlight lang="javascript">var number = Math.ceil(Math.random() * 100);
function verify() {
Line 1,488 ⟶ 2,435:
}
 
document.getElementById('guessNumber').onsubmit = verify;</langsyntaxhighlight>
<syntaxhighlight lang ="html4strict"></script></langsyntaxhighlight>
 
=== Spidermonkey Version ===
<langsyntaxhighlight lang="javascript">#!/usr/bin/env js
 
function main() {
Line 1,536 ⟶ 2,483:
 
main();
</syntaxhighlight>
</lang>
 
Example session:
Line 1,552 ⟶ 2,499:
Your guess: 57
You got it in 6 tries.
 
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq.'''
 
In the following, a time-based PRNG is used as that is sufficient for
the task. For a different PRNG, see e.g. [[Guess_the_number#jq]]
<syntaxhighlight lang=jq>
# $min and $max can be specified on the command line but for illustrative purposes:
def minmax: [0, 20];
 
# low-entropy PRNG in range($a;$b) i.e. $a <= prng < $b
# (no checking)
def prng($a;$b): $a + ((now * 1000000 | trunc) % ($b - $a) );
 
def play:
# extract a number if possible
def str2num:
try tonumber catch null;
 
minmax as [$min, $max]
| prng($min; $max) as $number
| "The computer has chosen a whole number between \($min) and \($max) inclusive.",
"Please guess the number or type q to quit:",
(label $out
| foreach inputs as $guess (null;
if $guess == "q" then null, break $out
else ($guess|str2num) as $g
| if $g == null or $g < 0 then "Please enter a non-negative integer or q to quit"
elif $g < $min or $g > $max then "That is out of range. Try again"
elif $g > $number then "Too high"
elif $g < $number then "Too low"
else true, break $out
end
end)
| if type == "string" then .
elif . == true then "Spot on!", "Let's start again.\n", play
else empty
end );
 
play
</syntaxhighlight>
'''Transcript:'''
<pre>
$ jq -nRr -f guess-the-number-with-feedback.jq
The computer has chosen a whole number between 0 and 20 inclusive.
Please guess the number or type q to quit:
10
Too low
16
Too high
14
Too high
12
Too high
11
Spot on!
Let's start again.
 
The computer has chosen a whole number between 0 and 20 inclusive.
Please guess the number or type q to quit:
19
Too high
q
Please enter a non-negative integer or q to quit
q
$</pre>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function guesswithfeedback(n::Integer)
number = rand(1:n)
print("I choose a number between 1 and $n\nYour guess? ")
Line 1,570 ⟶ 2,584:
end
 
guesswithfeedback(10)</langsyntaxhighlight>
 
{{out}}
Line 1,582 ⟶ 2,596:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">import kotlin.random.Random
<lang scala>// version 1.1.2
 
fun main(args: Array<String>) {
val rand = java.util.Random()
val n = 1 + rand.nextInt(20)
var guess :Int
println("Guess which number I've chosen in the range 1 to 20\n")
while (true) {
print(" Your guess : ")
val guess = readLine()!!?.toInt()
when (guess) {
n -> { println("Correct, well guessed!") ; return }
Line 1,599 ⟶ 2,611:
}
}
}</langsyntaxhighlight>
Sample inout/output
{{out}}
Line 1,613 ⟶ 2,625:
Your guess : 2
Correct, well guessed!
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def game
 
{def game.rec // recursive part
{lambda {:n :l :h}
{let { {:n :n} {:l :l} {:h :h} // :n, :l, :h redefined
{:g {round {/ {+ :l :h} 2}}}} // :g is the middle
{if {< :g :n}
then {br}:g too low!
{game.rec :n {+ :g 1} :h} // do it again higher
else {if {> :g :n}
then {br}:g too high!
{game.rec :n :l {- :g 1}} // do it again lower
else {br}{b :g Got it!} }} }}} // bingo!
 
{lambda {:n}
{let { {:n :n} // :n redefined
{:N {floor {* :n {random}}}}} // compute a random number
Find {b :N} between 0 and :n {game.rec :N 0 :n}
}}}
 
{game {pow 2 32}} // 2**32 = 4294967296
</syntaxhighlight>
 
Sample inout/output
{{out}}
<pre>
Find 2037303041 between 0 and 4294967296
2147483648 too high!
1073741824 too low!
1610612736 too low!
1879048192 too low!
2013265920 too low!
2080374784 too high!
2046820352 too high!
2030043136 too low!
2038431744 too high!
2034237440 too low!
2036334592 too low!
2037383168 too high!
2036858880 too low!
2037121024 too low!
2037252096 too low!
2037317632 too high!
2037284864 too low!
2037301248 too low!
2037309440 too high!
2037305344 too high!
2037303296 too high!
2037302272 too low!
2037302784 too low!
2037303040 too low!
2037303168 too high!
2037303104 too high!
2037303072 too high!
2037303056 too high!
2037303048 too high!
2037303044 too high!
2037303042 too high!
2037303041 Got it!
</pre>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">#!/usr/bin/lasso9
 
local(
Line 1,648 ⟶ 2,723:
#status = true
}
}</langsyntaxhighlight>
 
With range value 8 and 73. Correct number 13
Line 1,664 ⟶ 2,739:
 
=={{header|LFE}}==
<langsyntaxhighlight lang="lisp">
(defmodule guessing-game
(export (main 0)))
Line 1,686 ⟶ 2,761:
(: random uniform 10)
(get-player-guess)))
</syntaxhighlight>
</lang>
 
From the LFE REPL (assuming the above code was saved in the file "guessing-game.lfe"):
 
<langsyntaxhighlight lang="lisp">
> (slurp '"guessing-game.lfe")
#(ok guessing-game)
Line 1,705 ⟶ 2,780:
ok
>
</syntaxhighlight>
</lang>
 
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
[start]
target = int( rnd( 1) * 100) +1
Line 1,726 ⟶ 2,800:
if c >target then print " Your guess was too high."
wend
</syntaxhighlight>
</lang>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">command guessTheNumber lowN highN
local tNumber, tguess, tmin, tmax
if lowN is empty or lowN < 1 then
Line 1,759 ⟶ 2,831:
end if
end repeat
end guessTheNumber</langsyntaxhighlight>
Test
<langsyntaxhighlight LiveCodelang="livecode">command testGuessNumber
guessTheNumber --defaults to 1-10
guessTheNumber 9,12
end testGuessNumber</langsyntaxhighlight>
 
 
=={{header|Locomotive Basic}}==
 
<langsyntaxhighlight lang="locobasic">10 CLS:RANDOMIZE TIME
20 PRINT "Please specify lower and upper limits":guess=0
30 INPUT " (must be positive integers) :", first, last
Line 1,781 ⟶ 2,852:
110 INPUT "That's correct! Another game (y/n)? ", yn$
120 IF yn$="y" THEN 20
</syntaxhighlight>
</lang>
 
Output:
Line 1,789 ⟶ 2,860:
=={{header|Logo}}==
{{trans|UNIX Shell}}
<langsyntaxhighlight lang="logo">to guess [:max 100]
local "number
make "number random :max
Line 1,814 ⟶ 2,885:
]
end
</syntaxhighlight>
</lang>
 
Sample run:<pre>? guess
Line 1,831 ⟶ 2,902:
=={{header|Lua}}==
 
<langsyntaxhighlight Lualang="lua">math.randomseed(os.time())
me_win=false
my_number=math.random(1,10)
Line 1,853 ⟶ 2,924:
end
end
</syntaxhighlight>
</lang>
 
<pre>
Line 1,868 ⟶ 2,939:
That was correct.
</pre>
 
=={{header|M2000 Interpreter}}==
{{trans|BASIC256}}
<syntaxhighlight lang="m2000 interpreter">
Module GuessNumber {
Read Min, Max
chosen = Random(Min, Max)
print "guess a whole number between ";Min;" and ";Max
do {
\\ we use guess so Input get integer value
\\ if we press enter without a number we get error
do {
\\ if we get error then we change line, checking the cursor position
If Pos>0 then Print
Try ok {
input "Enter your number " , guess%
}
} until ok
Select Case guess%
case min to chosen-1
print "Sorry, your number was too low"
case chosen+1 to max
print "Sorry, your number was too high"
case chosen
print "Well guessed!"
else case
print "That was an invalid number"
end select
} until guess% = chosen
}
GuessNumber 5, 15
</syntaxhighlight>
 
{{out}}
same as BASIC256
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">GuessANumber := proc(low, high)
local number, input;
randomize():
Line 1,886 ⟶ 2,992:
end if;
end do:
end proc:</langsyntaxhighlight>
<syntaxhighlight lang Maple="maple">GuessANumber(2,5);</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">guessnumber[min_, max_] :=
Module[{number = RandomInteger[{min, max}], guess},
While[guess =!= number,
Line 1,899 ⟶ 3,005:
ToString@max <> "."]]];
CreateDialog[{"Well guessed!", DefaultButton[]}]];
guessnumber[1, 10]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
{{untested|Octave}}
Tested in MATLAB. Untested in Octave.
<langsyntaxhighlight MATLABlang="matlab">function guess_a_number(low, high)
 
if nargin < 1 || ~isnumeric(low) || length(low) > 1 || isnan(low)
Line 1,929 ⟶ 3,035:
gs = '';
end
end</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
Range = [1,100]
randomNumber = (random Range.x Range.y) as integer
Line 1,947 ⟶ 3,054:
)
)
</syntaxhighlight>
</lang>
 
Output:
<syntaxhighlight lang="maxscript">
<lang MAXSCRIPT>
Enter a number between 1 and 100: 5
Too low!
Line 1,964 ⟶ 3,071:
Well guessed!
OK
</syntaxhighlight>
</lang>
 
=={{header|Mirah}}==
<langsyntaxhighlight lang="mirah">def getInput:int
s = System.console.readLine()
Integer.parseInt(s)
Line 1,992 ⟶ 3,099:
puts "Please enter an integer."
end
end</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE guessf;
 
IMPORT InOut, Random, NumConv, Strings;
Line 2,034 ⟶ 3,141:
InOut.WriteString ("Thank you for playing; have a nice day!");
InOut.WriteLn
END guessf.</langsyntaxhighlight>
<pre>I have chosen a number below 1000; please try to guess it.
Enter your guess : 500
Line 2,047 ⟶ 3,154:
Your guess is spot on!
Thank you for playing; have a nice day!</pre>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">import Nanoquery.Util
 
random = new(Random)
inclusive_range = {1, 100}
 
print format("Guess my target number that is between %d and %d (inclusive).\n",\
inclusive_range[0], inclusive_range[1])
target = random.getInt(inclusive_range[1]) + inclusive_range[0]
answer = 0
i = 0
while answer != target
i += 1
print format("Your guess(%d): ", i)
txt = input()
 
valid = true
try
answer = int(txt)
catch
println format(" I don't understand you input of '%s' ?", txt)
value = false
end
 
if valid
if (answer < inclusive_range[0]) or (answer > inclusive_range[1])
println " Out of range!"
else if answer = target
println " Ye-Haw!!"
else if answer < target
println " Too low."
else if answer > target
println " Too high."
end
end
end
 
println "\nThanks for playing."</syntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 2,075 ⟶ 3,221:
} while (guess != secret)
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,140 ⟶ 3,286:
 
return
</syntaxhighlight>
</lang>
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">; guess-number-feedback.lsp
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Guess_the_number/With_feedback
Line 2,170 ⟶ 3,316:
(println "\nWell guessed! Congratulations!")
 
(exit)</langsyntaxhighlight>
 
Sample output:
Line 2,188 ⟶ 3,334:
 
=={{header|Nim}}==
<syntaxhighlight lang ="nim">import random, rdstdin, strutils
 
randomize()
Line 2,195 ⟶ 3,341:
 
echo "Guess my target number that is between ", iRange.a, " and ", iRange.b, " (inclusive)."
let target = randomrand(iRange)
var answer, i = 0
while answer != target:
inc i
letstdout.write txt = readLineFromStdin("Your guess ", & $i &, ": ")
let txt = stdin.readLine()
try: answer = parseInt(txt)
except ValueError:
echo " I don't understand your input of '", txt, "'"
continue
if answer <notin iRange.a or answer > iRange.b: echo " Out of range!"
elif answer < target: echo " Too low."
elif answer > target: echo " Too high."
else: echo " Ye-Haw!!"
 
echo "Thanks for playing."</langsyntaxhighlight>
 
Output:
=={{header|NS-HUBASIC}}==
<pre>Guess my target number that is between 1 and 100 (inclusive).
<syntaxhighlight lang="ns-hubasic">10 NUMBER=RND(10)+1
Your guess 1: 50
20 INPUT "I'M THINKING OF A NUMBER BETWEEN 1 AND 10. WHAT IS IT? ",GUESS
Too high.
30 IF GUESS>NUMBER THEN PRINT "MY NUMBER IS LOWER THAN THAT.": GOTO 20
Your guess 2: 300
40 IF GUESS<NUMBER THEN PRINT "MY NUMBER IS HIGHER THAN THAT.": GOTO 20
Out of range!
50 PRINT "THAT'S THE CORRECT NUMBER."</syntaxhighlight>
Your guess 3: -10
Out of range!
Your guess 4: foo
I don't understand your input of 'foo'
Your guess 5: 35
Too low.
Your guess 6: 42
Too high.
Your guess 7: 38
Too low.
Your guess 8: 40
Too low.
Your guess 9: 41
Ye-Haw!!
Thanks for playing.</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use IO;
 
bundle Default {
Line 2,267 ⟶ 3,400:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let rec _read_int() =
try read_int()
with _ ->
Line 2,305 ⟶ 3,438:
loop ()
in
loop ()</langsyntaxhighlight>
 
Playing the game:
Line 2,338 ⟶ 3,471:
 
=={{header|Octave}}==
<langsyntaxhighlight Octavelang="octave">function guess_a_number(low,high)
% Guess a number (with feedback)
% http://rosettacode.org/wiki/Guess_the_number/With_feedback
Line 2,364 ⟶ 3,497:
end
end
disp('Well guessed!')</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">import: console
 
: guessNumber(a, b)
Line 2,378 ⟶ 3,511:
g n == ifTrue: [ "You found it !" .cr return ]
g n < ifTrue: [ "Less" ] else: [ "Greater" ] . "than the target" .cr
again ;</langsyntaxhighlight>
 
=={{header|Ol}}==
<syntaxhighlight lang="ol">
<lang ol>
(import (otus random!))
 
Line 2,408 ⟶ 3,541:
((= guess number)
(print "Well guessed!")))))
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<lang parigp>guess_the_number(N=10)={
a=random(N);
print("guess the number between 0 and "N);
for(x=1,N,
if(x>1,
if(b>a,
print("guess again lower")
,
print("guess again higher")
);
b=input();
if(b==a,break())
);
print("You guessed it correctly")
};</lang>
 
=={{header|ooRexx}}==
Line 2,435 ⟶ 3,551:
entering ? shows the number we are looking for
This program should, of course, also work with all other Rexxes
<syntaxhighlight lang="oorexx">
<lang ooRexx>
/*REXX program that plays the guessing (the number) game. */
low=1 /*lower range for the guessing game.*/
Line 2,492 ⟶ 3,608:
 
ser: say; say '*** error ! ***'; say arg(1); say; return
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">guess_the_number(N=10)={
a=random(N);
print("guess the number between 0 and "N);
for(x=1,N,
if(x>1,
if(b>a,
print("guess again lower")
,
print("guess again higher")
);
b=input();
if(b==a,break())
);
print("You guessed it correctly")
};</syntaxhighlight>
 
=={{header|Pascal}}==
See [[Guess_the_number#Delphi | Delphi]]
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">sub prompt {
my $prompt = shift;
while (1) {
Line 2,515 ⟶ 3,649:
while ($_ = $tgt <=> prompt "Your guess");
 
print "Correct! You guessed it after $tries tries.\n";</langsyntaxhighlight>
 
=={{header|Perl 6}}==
 
<lang perl6>my $maxnum = prompt("Hello, please give me an upper boundary: ");
until 0 < $maxnum < Inf {
say "Oops! The upper boundary should be > 0 and not Inf";
$maxnum = prompt("Please give me a valid upper boundary: ");
}
 
my $count = 0;
my $number = (1..$maxnum).pick;
 
say "I'm thinking of a number from 1 to $maxnum, try to guess it!";
repeat until my $guessed-right {
given prompt("Your guess: ") {
when /^[e|q]/ { say 'Goodbye.'; exit; }
when not 1 <= $_ <= $maxnum {
say "You really should give me a number from 1 to $maxnum."
}
$count++;
when $number { $guessed-right = True }
when $number < $_ { say "Sorry, my number is smaller." }
when $number > $_ { say "Sorry, my number is bigger." }
}
}
say "Great you guessed right after $count attempts!";</lang>
 
<pre>Hello, please give me an upper boundary: 10
I'm thinking of a number from 1 to 10, try to guess it!
Your guess: 5
Sorry, my number is bigger.
Your guess: 7
Sorry, my number is smaller.
Your guess: 6
Great you guessed right after 3 attempts!</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant lower_limit = 0, upper_limit = 100
<span style="color: #000080;font-style:italic;">--
integer secret = rand(upper_limit-(lower_limit-1))+lower_limit-1
-- demo\rosetta\Guess_the_number3.exw
printf(1,"Guess the number between %d and %d: ", lower_limit & upper_limit)
--</span>
while 1 do
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer guess = prompt_number("", lower_limit & upper_limit)
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.1"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (VALUECHANGED_CB fix)</span>
if guess=secret then exit end if
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
printf(1,"Your guess is too %s.\nTry again: ",{iff(guess>secret?"high":"low")})
end while
<span style="color: #008080;">constant</span> <span style="color: #000000;">lower_limit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">upper_limit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100</span><span style="color: #0000FF;">,</span>
puts(1,"You got it!\n")</lang>
<span style="color: #000000;">secret</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand_range</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lower_limit</span><span style="color: #0000FF;">,</span><span style="color: #000000;">upper_limit</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Enter your guess, a number between %d and %d"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">prompt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">lower_limit</span><span style="color: #0000FF;">,</span><span style="color: #000000;">upper_limit</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">label</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">input</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">state</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">valuechanged_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*input*/</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">guess</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;"><</span><span style="color: #000000;">secret</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"Too low"</span><span style="color: #0000FF;">:</span>
<span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">=</span><span style="color: #000000;">secret</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"You got it!"</span><span style="color: #0000FF;">:</span>
<span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">></span><span style="color: #000000;">secret</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"Too high"</span><span style="color: #0000FF;">:</span>
<span style="color: #008000;">"uh?"</span><span style="color: #0000FF;">)))</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">state</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">label</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prompt</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">input</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"VALUE=0, EXPAND=HORIZONTAL, MASK="</span><span style="color: #0000FF;">&</span><span style="color: #004600;">IUP_MASK_INT</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">state</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"EXPAND=HORIZONTAL"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttributes</span><span style="color: #0000FF;">({</span><span style="color: #000000;">label</span><span style="color: #0000FF;">,</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #000000;">state</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"PADDING=0x15"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUECHANGED_CB"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"valuechanged_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">valuechanged_cb</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">label</span><span style="color: #0000FF;">,</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #000000;">state</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"MARGIN=15x15"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">`TITLE="Guess the number"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
<?php
 
Line 2,615 ⟶ 3,744:
</body>
</html>
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
{{trans|PureBasic}}
<langsyntaxhighlight PicoLisplang="picolisp">(de guessTheNumber ()
(use (Low High Guess)
(until
Line 2,637 ⟶ 3,766:
"Your guess is too "
(if (> Number Guess) "low" "high")
"." ) ) ) ) )</langsyntaxhighlight>
Output:
<pre>: (guessTheNumber)
Line 2,649 ⟶ 3,778:
You got it!</pre>
 
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">The low number is 1.
 
The high number is 100.
 
To run:
Start up.
Play the guessing game.
Wait for the escape key.
Shut down.
 
To play the guessing game:
Pick a secret number between the low number and the high number.
Write "I chose a secret number between " then the low number then " and " then the high number then "." then the return byte on the console.
Loop.
Ask the user for a number.
If the number is the secret number, break.
If the number is less than the secret number, write " Too low." on the console.
If the number is greater than the secret number, write " Too high." on the console.
Repeat.
Write " Well guessed!" on the console.
 
To ask the user for a number:
Write "Your guess? " to the console without advancing.
Read a string from the console.
If the string is not any integer, write " Guess must be an integer." on the console; repeat.
Convert the string to the number.
If the number is less than the low number, write " Guess can't be lower than " then the low number then "." on the console; repeat.
If the number is greater than the high number, write " Guess can't be higher than " then the high number then "." on the console; repeat.</syntaxhighlight>
{{out}}
<pre>
I chose a secret number between 1 and 100.
 
Your guess? apple
Guess must be an integer.
Your guess? 3.14159
Guess must be an integer.
Your guess? -50
Guess can't be lower than 1.
Your guess? 150
Guess can't be higher than 100.
Your guess? 50
Too high.
Your guess? 25
Too low.
Your guess? 37
Too low.
Your guess? 43
Too low.
Your guess? 46
Too low.
Your guess? 48
Well guessed!
</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-Guess
{
Line 2,697 ⟶ 3,880:
 
Write-Host ("The number was {0} and it took {1} guesses to find it." -f $answer.Number, $answer.Guesses.Count)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,717 ⟶ 3,900:
The number was 73 and it took 6 guesses to find it.
</pre>
 
=={{header|PureBasic}}==
<lang PureBasic>OpenConsole()
 
Repeat
; Ask for limits, with sanity check
Print("Enter low limit : "): low =Val(Input())
Print("Enter high limit: "): High =Val(Input())
Until High>low
 
TheNumber=Random(High-low)+low
Debug TheNumber
Repeat
Print("Guess what number I have: "): Guess=Val(Input())
If Guess=TheNumber
PrintN("You got it!"): Break
ElseIf Guess < TheNumber
PrintN("Your guess is to low.")
Else
PrintN("Your guess is to high.")
EndIf
ForEver</lang>
 
=={{header|Prolog}}==
Line 2,744 ⟶ 3,905:
{{works with|SWI-Prolog|6}}
 
<langsyntaxhighlight lang="prolog">main :-
play_guess_number.
 
Line 2,780 ⟶ 3,941:
; Guess > N -> writeln('Your guess is too high.')
; Guess =:= N -> writeln("Correct!")
).</langsyntaxhighlight>
 
 
Input in the standard Prolog top level is terminated with a `.`: E.g.,
 
<langsyntaxhighlight lang="prolog">?- main.
Guess an integer between 1 and 10.
Guess the number: a.
Invalid input.
Guess the number: 3.
Your guess is too low.</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">OpenConsole()
 
Repeat
; Ask for limits, with sanity check
Print("Enter low limit : "): low =Val(Input())
Print("Enter high limit: "): High =Val(Input())
Until High>low
 
TheNumber=Random(High-low)+low
Debug TheNumber
Repeat
Print("Guess what number I have: "): Guess=Val(Input())
If Guess=TheNumber
PrintN("You got it!"): Break
ElseIf Guess < TheNumber
PrintN("Your guess is to low.")
Else
PrintN("Your guess is to high.")
EndIf
ForEver</syntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import random
 
inclusive_range = (1, 100)
Line 2,818 ⟶ 4,001:
if answer > target: print(" Too high.")
 
print("\nThanks for playing.")</langsyntaxhighlight>
 
'''Sample Game'''
Line 2,852 ⟶ 4,035:
I don't understand your input of 'Howdy' ?
Your guess(4): </pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ say "Guess the number (1-100 inclusive.)"
cr cr
100 random 1+
[ $ "Your guess... " input
trim reverse trim reverse
$->n
not iff
[ drop
say "That is not a number." cr ]
again
2dup != while
over < iff
[ say "Too small." cr ]
again
say "Too large." cr
again ]
say "Well done! "
echo say " is correct. " cr
drop ] is guess-the-number ( --> )</syntaxhighlight>
 
{{out}}
 
In the Quackery shell.
 
<pre>/O> guess-the-number
...
Guess the number (1-100 inclusive.)
 
Your guess... eleventy thruppence
That is not a number.
Your guess... 50
Too small.
Your guess... 75
Too small.
Your guess... 83
Too large.
Your guess... 79
Too large.
Your guess... 77
Too large.
Your guess... 76
Well done! 76 is correct.
 
Stack empty.
 
/O></pre>
 
=={{header|R}}==
The previous solution lacked the required checks for if the input was appropriate, was bugged if low==high (R's sample function works differently if the input is of length 1), and behaved very strangely if low or high weren't whole numbers.
<lang R>GuessANumber <- function( low, high ) {
 
print( sprintf("Guess a number between %d and %d until you get it right", low, high ) );
This solution works on the assumption that the number to be found is an integer and also assumes that the upper and lower bounds are distinct integers used inclusively. For example, this means that low=4 and high=5 should be a solvable case, but low=high=4 will throw an error. See [[Talk:Guess the number/With feedback|Talk page]] entry dated 1st June 2020.
X <- low:high;
 
number <- sample( X, 1 );
<syntaxhighlight lang="rsplus">guessANumber <- function(low, high)
repeat {
{
input <- as.numeric(readline());
boundryErrorCheck(low, high)
if (input > number) {
goal <- printsample("Too low:high, trysize again"= 1); }
guess <- getValidInput(paste0("I have a whole number between ", low, " and ", high, ". What's your guess? "))
else if (input < number) {
while(guess != goal)
print("Too low, try again");}
else {
if(guess < low || guess > high){guess <- getValidInput("Out of range! Try again "); next}
print("Correct!");
if(guess > goal){guess <- getValidInput("Too high! Try again "); next}
break; }
if(guess < goal){guess <- getValidInput("Too low! Try again "); next}
}
"Winner!"
}</lang>
}
 
boundryErrorCheck <- function(low, high)
{
if(!is.numeric(low) || as.integer(low) != low) stop("Lower bound must be an integer. Try again.")
if(!is.numeric(high) || as.integer(high) != high) stop("Upper bound must be an integer. Try again.")
if(high < low) stop("Upper bound must be strictly greater than lower bound. Try again.")
if(low == high) stop("This game is impossible to lose. Try again.")
invisible()
}
 
#R's system for checking if numbers are integers is lacking (e.g. is.integer(1) returns FALSE)
#so we need this next function.
#A better way to check for integer inputs can be found in is.interger's docs, but this is easier to read.
#Note that readline outputs the user's input as a string, hence the need for type.convert.
getValidInput <- function(requestText)
{
guess <- type.convert(readline(requestText))
while(!is.numeric(guess) || as.integer(guess) != guess){guess <- type.convert(readline("That wasn't an integer! Try again "))}
as.integer(guess)
}</syntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (guess-number min max)
Line 2,889 ⟶ 4,143:
 
(guess-number 1 100)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" line>my $maxnum = prompt("Hello, please give me an upper boundary: ");
until 0 < $maxnum < Inf {
say "Oops! The upper boundary should be > 0 and not Inf";
$maxnum = prompt("Please give me a valid upper boundary: ");
}
 
my $count = 0;
my $number = (1..$maxnum).pick;
 
say "I'm thinking of a number from 1 to $maxnum, try to guess it!";
repeat until my $guessed-right {
given prompt("Your guess: ") {
when /^[e|q]/ { say 'Goodbye.'; exit; }
when not 1 <= $_ <= $maxnum {
say "You really should give me a number from 1 to $maxnum."
}
$count++;
when $number { $guessed-right = True }
when $number < $_ { say "Sorry, my number is smaller." }
when $number > $_ { say "Sorry, my number is bigger." }
}
}
say "Great you guessed right after $count attempts!";</syntaxhighlight>
 
<pre>Hello, please give me an upper boundary: 10
I'm thinking of a number from 1 to 10, try to guess it!
Your guess: 5
Sorry, my number is bigger.
Your guess: 7
Sorry, my number is smaller.
Your guess: 6
Great you guessed right after 3 attempts!</pre>
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">: high|low ( gn-g$ )
over > [ "high" ] [ "low" ] if ;
 
Line 2,907 ⟶ 4,197:
think [ getToken toNumber checkGuess ] while
"You got it!\n" puts ;
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
To make the program more engaging, randomized words for the hint are used.
<langsyntaxhighlight lang="rexx">/*REXX program plays guess the number game with a human; the computer picks the number*/
low= 1 1 /*the lower range for the guessing game*/
high=100 100 /* " upper " " " " " */
try= 0 0 /*the number of valid (guess) attempts.*/
r= random(1low, 100high) /*get a random number (low ───► high).*/
lows= 'too_low too_small too_little below under underneath too_puny'
highs= 'too_high too_big too_much above over over_the_top too_huge'
erm= '***error***'
@gtn= "guess the number, it's between"
prompt= centre(@gtn low 'and' high '(inclusive) ───or─── Quit:', 79, "─")
/* [↓] BY 0 ─── used to LEAVE a loop*/
do ask=0 by 0; say; say prompt; say; pull g; g= space(g); say
do validate=0 by 0 /*DO index required; LEAVE instruction.*/
select
when g=='' then iterate ask
when abbrev('QUIT', g, 1) then exit /*what a whoos.*/
when words(g) \==1 1 then say erm 'too many numbers entered:' g
when \datatype(g, 'N') then say erm g "isn't numeric"
when \datatype(g, 'W') then say erm g "isn't a whole number"
Line 2,937 ⟶ 4,227:
end /*validate*/
 
try= try + 1
if g=r then leave
if g>r then what= word(highs, random(1, words(highs) ) )
else what= word( lows, random(1, words( lows) ) )
say 'your guess of' g "is" translate(what'.', , "_").
end /*ask*/
/*stick a fork in it, we're all done. */
 
if try==1 then say 'Gadzooks!!! You guessed the number right away!'
else say 'Congratulations!, you guessed the number in ' try " tries."</syntaxhighlight>
/*stick a fork in it, we're all done. */</lang>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">fr = 1 t0 = 10
while true
see "Hey There,
Line 2,979 ⟶ 4,268:
d = random(e)
if d >= s return d ok
end</langsyntaxhighlight>
 
=={{header|Ruby}}==
{{trans|Mirah}}
<langsyntaxhighlight lang="ruby">number = rand(1..10)
 
puts "Guess the number between 1 and 10"
Line 3,001 ⟶ 4,290:
puts "Please enter an integer."
end
end</langsyntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand}}
<syntaxhighlight lang ="rust">use std::iorand::stdinRng;
use randstd::{Rng, thread_rng}cmp::Ordering;
use std::io;
 
const LOWEST: u32 = 1;
extern crate rand;
const HIGHEST: u32 = 100;
 
const LOWEST: isize = 1;
const HIGHEST: isize = 100;
 
fn main() {
let mut rngsecret_number = rand::thread_rng().gen_range(1..101);
 
println!("I have chosen my number between {} and {}. Guess the number!", LOWEST, HIGHEST);
 
loop {
println!("Please input your guess.");
let number: isize = rng.gen_range(LOWEST, HIGHEST + 1);
let mut num_guesses = 0;
 
let mut guess = String::new();
println!("I have chosen my number between {} and {}. You know what to do", LOWEST, HIGHEST);
 
loop {io::stdin()
num_guesses.read_line(&mut += 1;guess)
.expect("Failed to read line");
 
let mutguess: lineu32 = String::newmatch guess.trim();.parse() {
let resOk(num) => stdin().read_line(&mut line);num,
Err(_) => continue,
let input: Option<isize> = res.ok().map_or(None, |_| line.trim().parse().ok());
};
 
println!("You guessed: {}", match input {guess);
 
None => println!("numbers only, please"),
match Someguess.cmp(n&secret_number) if n == number => {
Ordering::Less => println!("youToo got it in {} triessmall!"), num_guesses);
Ordering::Greater => println!("Too break;big!"),
Ordering::Equal => }{
Some(n) if n < number => println!("tooYou lowwin!"),;
Some(n) if n > number => println!("too high!"),break;
Some(_) => println!("something went wrong")
}
}
}
}</langsyntaxhighlight>
<pre>I have chosen my number between 01 and 100. YouGuess knowthe what to donumber!
Please input your guess.
5
You guessed: 5
Too small!
Please input your guess.
50
You guessed: 50
too high!
Too small!
25
Please input your guess.
too high!
80
12
You guessed: 80
too low!
Too big!
18
Please input your guess.
too low!
67
21
You guessed: 67
too low!
Too big!
23
Please input your guess.
you got it in 6 tries!</pre>
57
You guessed: 57
Too small!
Please input your guess.
63
You guessed: 63
Too small!
Please input your guess.
65
You guessed: 65
Too small!
Please input your guess.
66
You guessed: 66
You win!</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import java.util.Random
import java.util.Scanner
 
Line 3,073 ⟶ 4,383:
else if (guessedNumber < randomNumber) println("Your guess is too low!")
else println("You got it!")
} while (guessedNumber != randomNumber)</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{works with|Chicken Scheme}}
{{works with|Guile}}
<langsyntaxhighlight lang="scheme">(define maximum 5)
(define minimum -5)
(define number (+ (random (- (+ maximum 1) minimum)) minimum))
Line 3,094 ⟶ 4,405:
(if (< guess number)
(display "Too low!\n> ")))))
(display "Correct!\n")</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const integer: lower_limit is 0;
Line 3,123 ⟶ 4,434:
writeln("You gave up!");
end if;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">var number = rand(1..10);
say "Guess the number between 1 and 10";
 
Line 3,136 ⟶ 4,447:
default { say "Too high" }
}
}</langsyntaxhighlight>
 
=={{header|Small Basic}}==
<langsyntaxhighlight Smalllang="small Basicbasic">number=Math.GetRandomNumber(10)
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
While guess<>number
Line 3,150 ⟶ 4,461:
EndIf
EndWhile
TextWindow.WriteLine("You win!")</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
 
{{works with|Pharo|7.0.3}}
 
To load:
Save the example. In a Pharo image, go to "Tools" -> "File Browser" -> Select the file... -> Filein.
To play: run "GuessingGame playFrom: 1 to: 100" on a Workspace (Tools -> Workspace)
 
<syntaxhighlight lang="smalltalk">
'From Pharo7.0.3 of 12 April 2019 [Build information: Pharo-7.0.3+build.158.sha.0903ade8a6c96633f07e0a7f1baa9a5d48cfdf55 (64 Bit)] on 30 October 2019 at 4:24:17.115807 pm'!
Object subclass: #GuessingGame
instanceVariableNames: 'min max uiManager tries'
classVariableNames: ''
poolDictionaries: ''
category: 'GuessingGame'!
 
!GuessingGame methodsFor: 'initialization' stamp: 'EduardoPadoan 10/26/2019 23:51'!
initialize
uiManager := UIManager default.
tries := 0! !
 
 
!GuessingGame methodsFor: 'services' stamp: 'EduardoPadoan 10/26/2019 23:40'!
alert: aString
uiManager alert: aString! !
 
 
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
max
^ max! !
 
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
min
^ min! !
 
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
min: anObject
min := anObject! !
 
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
max: anObject
max := anObject! !
 
 
!GuessingGame methodsFor: 'playing-main' stamp: 'EduardoPadoan 10/27/2019 00:18'!
play
| toGuess |
toGuess := self selectNumber.
[ :break |
| choice |
[
choice := self getGuessOrExitWith: break.
choice
ifNil: [ self alert: 'Invalid Input' ]
ifNotNil: [
self incrementTries.
choice = toGuess
ifTrue: [ self congratulateForGuess: choice andExitWith: break ]
ifFalse: [ choice > toGuess ifTrue: [ self alert: 'Too high' ]
ifFalse: [ self alert: 'Too low' ] ]
]
] repeat.
] valueWithExit.! !
 
 
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:39'!
makeRequest: aString
^ uiManager request: aString! !
 
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:48'!
getGuessOrExitWith: anExitBlock
^ [(self makeRequest: 'Guess number a between , min,' and ', max, '.') asInteger]
on: MessageNotUnderstood "nil"
do: [
self sayGoodbye.
anExitBlock value ].! !
 
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:51'!
incrementTries
tries := tries + 1! !
 
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/27/2019 00:05'!
sayGoodbye
self alert: 'Gave up? Sad.'.! !
 
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/27/2019 00:15'!
congratulateForGuess: anInteger andExitWith: anExitBlock
self alert: 'Correct!! The value was indeed ', anInteger asString, '. Took you only ', tries asString, ' tries.'.
^ anExitBlock value! !
 
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:35'!
selectNumber
^ (min to: max) atRandom ! !
 
"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!
 
GuessingGame class
slots: { }!
 
!GuessingGame class methodsFor: 'creating' stamp: 'EduardoPadoan 10/27/2019 00:15'!
playFrom: aMinNumber to: aMaxNumber
self new
min: aMinNumber;
max: aMaxNumber;
play! !
 
</syntaxhighlight>
 
=={{header|Sparkling}}==
<langsyntaxhighlight lang="sparkling">printf("Lower bound: ");
let lowerBound = toint(getline());
 
Line 3,179 ⟶ 4,598:
break;
}
}</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Cocoa
 
var found = false
Line 3,203 ⟶ 4,623:
println("Good try but the number is less than that!")
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set from 1
set to 10
set target [expr {int(rand()*($to-$from+1) + $from)}]
Line 3,225 ⟶ 4,645:
break
}
}</langsyntaxhighlight>
Sample output:
<pre>
Line 3,244 ⟶ 4,664:
Well done! You guessed it.
</pre>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
Line 3,266 ⟶ 4,687:
IF (round==7) PRINT/ERROR "You've lost: luckynumber was: ",luckynumber
ENDLOOP
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,293 ⟶ 4,714:
{{works with|Public Domain Korn SHell}}
{{works with|Z SHell}}
<langsyntaxhighlight lang="sh">function guess {
[[ -n $BASH_VERSION ]] && shopt -s extglob
[[ -n $ZSH_VERSION ]] && set -o KSH_GLOB
Line 3,318 ⟶ 4,739:
fi
done
}</langsyntaxhighlight>
 
Sample run:
Line 3,337 ⟶ 4,758:
=={{header|Ursa}}==
{{trans|Python}}
<langsyntaxhighlight lang="ursa">decl int high low
set low 0
set high 100
Line 3,366 ⟶ 4,787:
end while
 
out endl "Thanks for playing." endl console</langsyntaxhighlight>
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">
void main(){
const int from = 1;
Line 3,401 ⟶ 4,822:
}//while
} // main
</syntaxhighlight>
</lang>
 
Shorter but no error checking
<langsyntaxhighlight lang="vala">int main() {
int guess, x = Random.int_range(1, 10);
stdout.printf("Make a guess (1-10): ");
Line 3,412 ⟶ 4,833:
stdout.printf("Got it!\n");
return 0;
}</langsyntaxhighlight>
 
=={{header|VBA Excel}}==
The Application.InputBox display a message when input is inappropriate.
<langsyntaxhighlight lang="vb">Sub GuessTheNumberWithFeedback()
Dim Nbc&, Nbp&, m&, n&, c&
 
Line 3,433 ⟶ 4,854:
Loop
MsgBox "Well guessed!" & vbCrLf & "You find : " & Nbc & " in " & c & " guesses!"
End Sub</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Dim max,min,secretnum,numtries,usernum
max=100
Line 3,463 ⟶ 4,884:
End If
Loop
</syntaxhighlight>
</lang>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import rand.seed
import rand
import os
const (
lower = 1
upper = 100
)
fn main() {
rand.seed(seed.time_seed_array(2))
n := rand.intn(upper-lower+1) or {0} + lower
for {
guess := os.input("Guess integer number from $lower to $upper: ").int()
if guess < n {
println("Too low. Try again: ")
} else if guess > n {
println("Too high. Try again: ")
} else {
println("Well guessed!")
return
}
}
}</syntaxhighlight>
 
=={{header|VTL-2}}==
<syntaxhighlight lang="vtl2">10 ?="Minimum? ";
20 L=?
30 ?="Maximum? ";
40 H=?
50 #=L<H*80
60 ?="Minimum must be lower than maximum."
70 #=10
80 S='/(H-L+1)*0+L+%
90 T=0
100 ?="Guess? ";
110 G=?
120 #=G>L*(H>G)*150
130 ?="Guess must be in between minimum and maximum."
140 #=100
150 T=T+1
160 #=G=S*220
170 #=G<S*200
180 ?="Too high."
190 #=100
200 ?="Too low."
210 #=100
220 ?="Correct!"
230 ?="Tries: ";
240 ?=T</syntaxhighlight>
{{out}}
<pre>Minimum? 10
Maximum? 90
Guess? 91
Guess must be in between minimum and maximum.
Guess? 9
Guess must be in between minimum and maximum.
Guess? 50
Too low.
Guess? 70
Too high.
Guess? 60
Too high.
Guess? 55
Correct!
Tries: 4</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">import "io" for Stdin, Stdout
import "random" for Random
 
var rand = Random.new()
var n = rand.int(1, 21) // computer number from 1..20 inclusive, say
System.print("The computer has chosen a number between 1 and 20 inclusive.")
while (true) {
System.write(" Your guess 1-20 : ")
Stdout.flush()
var g = Num.fromString(Stdin.readLine())
if (!g || g.type != Num || !g.isInteger || g < 1 || g > 20) {
System.print(" Inappropriate")
} else if (g > n) {
System.print(" Too high")
} else if (g < n) {
System.print(" Too low")
} else {
System.print(" Spot on!")
break
}
}</syntaxhighlight>
 
{{out}}
Sample session:
<pre>
The computer has chosen a number between 1 and 20 inclusive.
Your guess 1-20 : 21
Inappropriate
Your guess 1-20 : 1.5
Inappropriate
Your guess 1-20 : abc
Inappropriate
Your guess 1-20 : 10
Too low
Your guess 1-20 : 15
Too high
Your guess 1-20 : 13
Too high
Your guess 1-20 : 12
Too high
Your guess 1-20 : 11
Spot on!
</pre>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">(defun guessing-game (a b)
; minimum and maximum, to be supplied by the user
(defun prompt ()
Line 3,491 ⟶ 5,026:
(display ". Try to guess it!")
(newline)
(prompt))</langsyntaxhighlight>
{{out}}
<pre>[1] (guessing-game 19 36)
Line 3,513 ⟶ 5,048:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int Lo, Hi, C, Guess, Number;
 
Line 3,536 ⟶ 5,071:
CrLf(0);
until Guess = Number;
]</langsyntaxhighlight>
 
Example output:
Line 3,554 ⟶ 5,089:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">r:=(0).random(10)+1;
while(1){
n:=ask("Num between 1 & 10: ");
Line 3,560 ⟶ 5,095:
if(n==r){ println("Well guessed!"); break; }
println((n<r) and "small" or "big");
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,574 ⟶ 5,109:
Well guessed!
</pre>
 
=={{header|Zoomscript}}==
For typing:
<syntaxhighlight lang="zoomscript">var randnum
var guess
randnum & random 1 10
guess = 0
while ne randnum guess
print "I'm thinking of a number between 1 and 10. What is it? "
guess & get
if lt guess randnum
print "Too low. Try again!"
println
endif
if gt guess randnum
print "Too high. Try again!"
println
endif
endwhile
print "Correct number. You win!"</syntaxhighlight>
 
For importing:
 
¶0¶var randnum¶0¶var guess¶0¶randnum & random 1 10¶0¶guess = 0¶0¶while ne randnum guess¶0¶print "I'm thinking of a number between 1 and 10. What is it? "¶0¶guess & get¶0¶if lt guess randnum¶0¶print "Too low. Try again!"¶0¶println¶0¶endif¶0¶if gt guess randnum¶0¶print "Too high. Try again!"¶0¶println¶0¶endif¶0¶endwhile¶0¶print "Correct number. You win!"
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">ZX Spectrum Basic has no [[:Category:Conditional loops|conditional loop]] constructs, so we have to emulate them here using IF and GO TO.
1 LET n=INT (RND*10)+1
2 INPUT "Guess a number that is between 1 and 10: ",g: IF g=n THEN PRINT "That's my number!": STOP
3 IF g<n THEN PRINT "That guess is too low!": GO TO 2
4 IF g>n THEN PRINT "That guess is too high!": GO TO 2</langsyntaxhighlight>
305

edits