Guess the number/With feedback: Difference between revisions

(add swift)
 
(146 intermediate revisions by 73 users not shown)
Line 1:
{{task|Games}}
{{task|Games}}The task is to write a game that follows the following rules:
:The computer will choose a number between given set limits and asks the player for repeated guesses until the player guesses the target number correctly. At each guess, the computer responds with whether the guess was higher than, equal to, or less than the target - or signals that the input was inappropriate.
 
;Task:
C.f: [[Guess the number/With Feedback (Player)]]
Write a game (computer program) that follows the following rules:
::* The computer chooses a number between given set limits.
::* The player is asked for repeated guesses until the the target number is guessed correctly
::* At each guess, the computer responds with whether the guess is:
:::::* higher than the target,
:::::* equal to the target,
:::::* less than the target,   or
:::::* the input was inappropriate.
 
 
;Related task:
*   [[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 21 ⟶ 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 32 ⟶ 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 95 ⟶ 209:
OD;
print( ( "That's correct!", newline ) )
)</langsyntaxhighlight>
{{out}}
<pre>
Line 118 ⟶ 232:
That's correct!
</pre>
 
=={{header|AppleScript}}==
 
<syntaxhighlight lang="applescript">-- defining the range of the number to be guessed
property minLimit : 1
property maxLimit : 100
 
on run
-- define the number to be guessed
set numberToGuess to (random number from minLimit to maxLimit)
-- prepare a variable to store the user's answer
set guessedNumber to missing value
-- prepare a variable for feedback
set tip to ""
-- start a loop (will be exited by using "exit repeat" after a correct guess)
repeat
-- ask the user for his/her guess, the variable tip contains text after first guess only
set usersChoice to (text returned of (display dialog "Guess the number between " & minLimit & " and " & maxLimit & " inclusive" & return & tip default answer "" buttons {"Check"} default button "Check"))
-- try to convert the given answer to an integer and compare it the number to be guessed
try
set guessedNumber to usersChoice as integer
if guessedNumber is greater than maxLimit or guessedNumber is less than minLimit then
-- the user guessed a number outside the given range
set tip to "(Tipp: Enter a number between " & minLimit & " and " & maxLimit & ")"
else if guessedNumber is less than numberToGuess then
-- the user guessed a number less than the correct number
set tip to "(Tipp: The number is greater than " & guessedNumber & ")"
else if guessedNumber is greater than numberToGuess then
-- the user guessed a number greater than the correct number
set tip to "(Tipp: The number is less than " & guessedNumber & ")"
else if guessedNumber is equal to numberToGuess then
-- the user guessed the correct number and gets informed
display dialog "Well guessed! The number was " & numberToGuess buttons {"OK"} default button "OK"
-- exit the loop (quits this application)
exit repeat
end if
on error
-- something went wrong, remind the user to enter a numeric value
set tip to "(Tipp: Enter a number between " & minLimit & " and " & maxLimit & ")"
end try
end repeat
end run</syntaxhighlight>
 
=={{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 150 ⟶ 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 182 ⟶ 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 200 ⟶ 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 218 ⟶ 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 228 ⟶ 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}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Guess.bas"
110 RANDOMIZE
120 LET UP=10:LET LO=1 ! Limits
130 PRINT "I'm thinking of a number between";LO;"and";UP
140 LET COUNT=0:LET NR=RND(UP-LO+1)+LO
150 DO
160 LET COUNT=COUNT+1
170 INPUT PROMPT "Guess a number: ":GU
180 SELECT CASE GU
190 CASE IS>NR
200 PRINT "My number is lower that."
210 CASE IS<NR
220 PRINT "My number is higher that."
230 CASE ELSE
240 PRINT "Well guessed! Numner of tips:";COUNT
250 END SELECT
260 LOOP UNTIL NR=GU</syntaxhighlight>
 
==={{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 248 ⟶ 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 269 ⟶ 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.
 
<syntaxhighlight 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"></syntaxhighlight>
 
{{out}}
<pre>Guess a number between 1 and 100
> 50
Your guess was too high.
> 25
Your guess was too low.
> 37
Your guess was too high.
> 31
You guessed correctly!</pre>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">number = random 10
 
p "Guess a number between 1 and 10."
Line 288 ⟶ 795:
}
}
}</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <time.h>
Line 305 ⟶ 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 315 ⟶ 823:
 
return 0;
}</langsyntaxhighlight>
 
Demonstration:
Line 332 ⟶ 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 420 ⟶ 881:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>The number is between 1 and 10. Make a guess: 1
Line 437 ⟶ 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}}==
 
In you module.ceylon file put import ceylon.random "1.3.1";
 
<syntaxhighlight lang="ceylon">import ceylon.random {
DefaultRandom
}
 
shared void run() {
value random = DefaultRandom();
value range = 1..10;
while(true) {
value chosen = random.nextElement(range);
print("I have chosen a number between ``range.first`` and ``range.last``.
What is your guess?");
while(true) {
if(exists line = process.readLine()) {
value guess = Integer.parse(line.trimmed);
 
if(is ParseException guess) {
print(guess.message);
continue;
}
 
switch(guess <=> chosen)
case (larger) {
print("Too high!");
}
case (smaller) {
print("Too low!");
}
case (equal) {
print("You got it!");
break;
}
} else {
print("Please enter a number!");
}
}
}
}</syntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn guess-run []
(let [start 1
end 100
Line 454 ⟶ 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 486 ⟶ 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 505 ⟶ 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 527 ⟶ 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 560 ⟶ 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 582 ⟶ 1,307:
Your guess #9: 83
Well Guessed.</pre>
 
=={{header|DCL}}==
<syntaxhighlight lang="dcl">$ rnd = f$extract( 21, 2, f$time() )
$ count = 0
$ loop:
$ inquire guess "guess what number between 0 and 99 inclusive I am thinking of"
$ guess = f$integer( guess )
$ if guess .lt. 0 .or. guess .gt. 99
$ then
$ write sys$output "out of range"
$ goto loop
$ endif
$ count = count + 1
$ if guess .lt. rnd then $ write sys$output "too small"
$ 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"</syntaxhighlight>
{{out}}
<pre>$ @guess
guess what number between 0 and 99 inclusive I am thinking of: 50
too small
guess what number between 0 and 99 inclusive I am thinking of: 999
out of range
guess what number between 0 and 99 inclusive I am thinking of: 75
too small
guess what number between 0 and 99 inclusive I am thinking of: 82
too small
guess what number between 0 and 99 inclusive I am thinking of: 91
too small
guess what number between 0 and 99 inclusive I am thinking of: 96
too small
guess what number between 0 and 99 inclusive I am thinking of: 98
too large
guess what number between 0 and 99 inclusive I am thinking of: 97
it only took you 7 guesses</pre>
 
=={{header|Delphi}}==
 
<langsyntaxhighlight Delphilang="delphi">program GuessTheNumber;
 
{$APPTYPE CONSOLE}
Line 670 ⟶ 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}}==
<syntaxhighlight 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
(lib 'web) ; (play-sound) is defined in web.lib
 
(define (guess-feed (msg " 🔮 Enter a number in [0...100], -1 to stop.") (n (random 100)) (user 0))
(set! user (read user msg))
(play-sound 'ko)
(unless (eq? n user ) ; user is the last user answer
(guess-feed
(cond ;; adapt prompt according to condition
((not (integer? user)) "❌ Please, enter an integer")
(( < user 0) (error "🌵 - It was:" n)) ; exit to top level
((> n user) "Too low ...")
((< n user) "Too high ..."))
n user))
(play-sound 'ok )
" 🔮 Well played!! 🍒 🍇 🍓")
</syntaxhighlight>
 
=={{header|Ela}}==
 
<langsyntaxhighlight lang="ela">open string datetime random core console string datetimemonad readio
 
guess () = do
rnd' v = rnd s 1 v where s = milliseconds <| datetime.now()
putStrLn "What's the upper bound?"
ub <- readAny
main ub
where main ub
| ub < 0 = "Bound should be greater than 0."
| else = do
putStrLn $ format "Guess a number from 1 to {0}" ub
dt <- datetime.now
guesser (rnd (milliseconds $ dt) 1 ub)
guesser v = do
x <- readAny
if x == v then
cont ()
else if x < v then
do putStrLn "Too small!"
guesser v
else
do putStrLn "Too big!"
guesser v
cont () = do
putStrLn "Correct! Do you wish to continue (Y/N)?"
ask ()
ask () = do
a <- readStr
if a == "y" || a == "Y" then
guess ()
else if a == "n" || a == "N" then
do putStrLn "Bye!"
else
do putStrLn "Say what?"
ask ()
 
guess () ::: IO</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 6.x :
<syntaxhighlight lang="elena">import extensions;
public program()
start () =
{
match bound() with
int randomNumber := randomGenerator.nextInt(1,10);
Some v = writen ("Guess a number from 1 to " ++ show v) `seq` (guess <| rnd' v)
console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?");
None = start()
bool numberCorrect := false;
until(numberCorrect)
bound () =
{
writen "What's the upper bound?" `seq` (bound' <| readStr <| readn())
console.print("Guess: ");
where bound' v | v <= 0 = writen "Bound should be greater than 0." `seq` None
int userGuess := console.readLine().toInt();
| else = Some v
if (randomNumber == userGuess)
{
success v =
numberCorrect := true;
writen "Correct! Do you want to continue? (Y/N)" `seq` ask()
console.printLine("Congrats!! You guessed right!")
where ask () = read <| upper <| readn()
read "Y" = start()}
else if read(randomNumber "N"< = writen "Bye!"userGuess)
{
read x = writen "Say what?" `seq` ask()
console.printLine("Your guess was too high")
}
failed v n =
else
writen ("No, this is not " ++ show v ++ ". " ++ hint) `seq` guess n
where hint | v < n = "Try bigger."{
console.printLine("Your guess was |too else = "Try smaller.low")
}
}
guess n = g <| readStr <| readn()
}</syntaxhighlight>
where g v | v == n = success v
{{out}}
| else = failed v n
<pre>
I'm thinking of a number between 1 and 10. Can you guess it?
start()</lang>
Guess: 5
Your guess was too low
Guess: 8
Your guess was too high
Guess: 6
Congrats!! You guessed right!
</pre>
 
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<lang elixir>
<syntaxhighlight lang="elixir">defmodule GuessingGame do
def init() do
:random.seed(:erlang.now())
end
def play(lower, upper) do
play(lower, upper, :Enum.random.uniform(upperlower +.. 1 - lowerupper) + lower - 1)
end
defp play(lower, upper, number) do
guess = Integer.parse(IO.gets "Guess a number (#{lower}-#{upper}): ")
case guess do
{n^number, _} when n == number ->
IO.puts "Well guessed!"
{n, _} when lower <= n and n <=in lower..upper ->
IO.puts if n > number, do: "Too high.", else: "Too low."
IO.puts "Too high."
else
IO.puts "Too low."
end
play(lower, upper, number)
_ ->
Line 731 ⟶ 1,568:
play(lower, upper, number)
end
end
end
GuessingGame.play(1, 100)</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
GuessingGame.init()
<syntaxhighlight lang="lisp">(let* ((min 1)
GuessingGame.play(1, 100)
(max 100)
</lang>
(number (+ (random (1+ (- max min))) min))
guess done)
(message "Guess the number between %d and %d" min max)
(while (not done)
(setq guess (read-number "Please enter a number "))
(cond
((< guess number)
(message "Too low!"))
((> guess number)
(message "Too high!"))
((= guess number)
(setq done t)
(message "Well guessed!")))))</syntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(guess_number).
-export([main/0]).
Line 766 ⟶ 1,618:
guess(N)
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>1> c(guess_number).
Line 786 ⟶ 1,638:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include get.e
 
constant lower_limit = 0, upper_limit = 100
Line 804 ⟶ 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 832 ⟶ 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 873 ⟶ 1,759:
}
}
</syntaxhighlight>
</lang>
 
Sample game:
Line 899 ⟶ 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 928 ⟶ 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 944 ⟶ 1,866:
Enter guess: 57
That is correct</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Randomize
Dim n As Integer = Int(Rnd * 20) + 1
Dim guess As Integer
 
Print "Guess which number I've chosen in the range 1 to 20"
Print
Do
Input " Your guess : "; guess
If guess > n AndAlso guess <= 20 Then
Print "Your guess is higher than the chosen number, try again "
ElseIf guess = n Then
Print "Correct, well guessed!"
Exit Do
ElseIf guess < n AndAlso 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>
 
Sample input/output
{{out}}
<pre>
Your guess : ? 14
Your guess is lower than the chosen number, try again
Your guess : ? 17
Your guess is lower than the chosen number, try again
Your guess : ? 18
Your guess is lower than the chosen number, try again
Your guess : ? 19
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 974 ⟶ 2,199:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Based on the Java implementation
<syntaxhighlight lang="groovy">
def rand = new Random() // java.util.Random
def range = 1..100 // Range (inclusive)
def number = rand.nextInt(range.size()) + range.from // get a random number in the range
 
println "The number is in ${range.toString()}" // print the range
 
def guess
while (guess != number) { // keep running until correct guess
try {
print 'Guess the number: '
guess = System.in.newReader().readLine() as int // read the guess in as int
switch (guess) { // check the guess against number
case { it < number }: println 'Your guess is too low'; break
case { it > number }: println 'Your guess is too high'; break
default: println 'Your guess is spot on!'; break
}
} catch (NumberFormatException ignored) { // catches all input that is not a number
println 'Please enter a number!'
}
}
</syntaxhighlight>
Example:
<syntaxhighlight lang="text">
The number is in 1..100
Guess the number: ghfvkghj
Please enter a number!
Guess the number: 50
Your guess is too low
Guess the number: 75
Your guess is too low
Guess the number: 83
Your guess is too low
Guess the number: 90
Your guess is too low
Guess the number: 95
Your guess is too high
Guess the number: 92
Your guess is spot on!
</syntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">
import Control.Monad
import System.Random
Line 1,001 ⟶ 2,269:
putStrLn "Try to guess my secret number between 1 and 100."
ask `until_` answerIs ans
</syntaxhighlight>
</lang>
 
=={{header|HolyC}}==
<syntaxhighlight lang="holyc">U8 n, *g;
U8 min = 1, max = 100;
 
n = min + RandU16 % max;
 
Print("Guess the number between %d and %d: ", min, max);
 
while(1) {
g = GetStr;
 
if (Str2I64(g) == n) {
Print("You guessed correctly!\n");
break;
}
 
if (Str2I64(g) < n)
Print("Your guess was too low.\nTry again: ");
if (Str2I64(g) > n)
Print("Your guess was too high.\nTry again: ");
}</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
 
<syntaxhighlight lang="icon">
<lang Icon>
procedure main()
smallest := 5
Line 1,026 ⟶ 2,316:
}
end
</syntaxhighlight>
</lang>
 
Output:
Line 1,044 ⟶ 2,334:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">require 'misc'
game=: verb define
assert. y -: 1 >. <.{.y
Line 1,054 ⟶ 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,060 ⟶ 2,350:
Example use:
 
<syntaxhighlight lang="text"> game 100
Guess my integer, which is bounded by 1 and 100
Guess: 64
Line 1,071 ⟶ 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,101 ⟶ 2,391:
} while (guessedNumber != randomNumber);
}
}</langsyntaxhighlight>
Demonstration:
<pre>The number is between 1 and 100.
Line 1,118 ⟶ 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,124 ⟶ 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,145 ⟶ 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,193 ⟶ 2,483:
 
main();
</syntaxhighlight>
</lang>
 
Example session:
Line 1,209 ⟶ 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}}
<lang Julia>function guess_feedback(n)
number = rand(1:n)
print("I choose a number between 1 and $n\nYour guess? ")
while((guess = chomp(readline(STDIN))) != string(number))
isdigit(guess) ?
print("Too $(int(guess) < number ? "small" : "big")\nNew guess? ") :
print("Enter an integer please\nNew guess? ")
end
print("you guessed right!")
end</lang>
{{Out}}
<pre>julia> guess_feedback(10)
I choose a number between 1 and 10
Your guess? 5
Too small
New guess? 8
Too big
New guess? no luck
Enter an integer please
New guess? 6
you guessed right!</pre>
 
<syntaxhighlight lang="julia">function guesswithfeedback(n::Integer)
number = rand(1:n)
print("I choose a number between 1 and $n\nYour guess? ")
while (guess = readline()) != dec(number)
if all(isdigit, guess)
print("Too ", parse(Int, guess) < number ? "small" : "big")
else
print("Enter an integer please")
end
print(", new guess? ")
end
println("You guessed right!")
end
 
guesswithfeedback(10)</syntaxhighlight>
 
{{out}}
<pre>I choose a number between 1 and 10
Your guess? 11
Too big, new guess? 1
Too small, new guess? 5
Too small, new guess? 6
Too small, new guess? 7
You guessed right!</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">import kotlin.random.Random
 
fun main() {
val n = 1 + rand.nextInt(20)
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 }
in n + 1 .. 20 -> println("Your guess is higher than the chosen number, try again")
in 1 .. n - 1 -> println("Your guess is lower than the chosen number, try again")
else -> println("Your guess is inappropriate, try again")
}
}
}</syntaxhighlight>
Sample inout/output
{{out}}
<pre>
Guess which number I've chosen in the range 1 to 20
 
Your guess : 10
Your guess is higher than the chosen number, try again
Your guess : 5
Your guess is higher than the chosen number, try again
Your guess : 3
Your guess is higher than the chosen number, try again
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,267 ⟶ 2,723:
#status = true
}
}</langsyntaxhighlight>
 
With range value 8 and 73. Correct number 13
Line 1,283 ⟶ 2,739:
 
=={{header|LFE}}==
<langsyntaxhighlight lang="lisp">
(defmodule guessing-game
(export (main 0)))
Line 1,305 ⟶ 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,324 ⟶ 2,780:
ok
>
</syntaxhighlight>
</lang>
 
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
[start]
target = int( rnd( 1) * 100) +1
Line 1,345 ⟶ 2,800:
if c >target then print " Your guess was too high."
wend
</syntaxhighlight>
</lang>
 
=={{header|LiveCode}}==
<syntaxhighlight lang="livecode">command guessTheNumber lowN highN
local tNumber, tguess, tmin, tmax
if lowN is empty or lowN < 1 then
put 1 into tmin
else
put lowN into tmin
end if
if highN is empty then
put 10 into tmax
else
put highN into tmax
end if
put random(tmax - tmin + 1) + tmin - 1 into tNumber
repeat until tguess is tNumber
ask question "Please enter a number between" && tmin && "and" && tmax titled "Guess the number"
if it is not empty then
put it into tguess
if tguess is tNumber then
answer "Well guessed!"
else if tguess < tNumber then
answer "too low"
else
answer "too high"
end if
else
exit repeat
end if
end repeat
end guessTheNumber</syntaxhighlight>
Test
<syntaxhighlight lang="livecode">command testGuessNumber
guessTheNumber --defaults to 1-10
guessTheNumber 9,12
end testGuessNumber</syntaxhighlight>
 
=={{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,363 ⟶ 2,852:
110 INPUT "That's correct! Another game (y/n)? ", yn$
120 IF yn$="y" THEN 20
</syntaxhighlight>
</lang>
 
Output:
Line 1,371 ⟶ 2,860:
=={{header|Logo}}==
{{trans|UNIX Shell}}
<langsyntaxhighlight lang="logo">to guess [:max 100]
local "number
make "number random :max
Line 1,396 ⟶ 2,885:
]
end
</syntaxhighlight>
</lang>
 
Sample run:<pre>? guess
Line 1,413 ⟶ 2,902:
=={{header|Lua}}==
 
<langsyntaxhighlight Lualang="lua">math.randomseed(os.time())
me_win=false
my_number=math.random(1,10)
Line 1,435 ⟶ 2,924:
end
end
</syntaxhighlight>
</lang>
 
<pre>
Line 1,451 ⟶ 2,940:
</pre>
 
=={{header|MathematicaM2000 Interpreter}}==
{{trans|BASIC256}}
<lang mathematica>guessnumber[min_, max_] :=
<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}}==
<syntaxhighlight lang="maple">GuessANumber := proc(low, high)
local number, input;
randomize():
printf( "Guess a number between %d and %d:\n:> ", low, high );
number := rand(low..high)();
do
input := parse(readline());
if input > number then
printf("Too high, try again!\n:> ");
elif input < number then
printf("Too low, try again!\n:> ");
else
printf("Well guessed! The answer was %d.\n", number);
break;
end if;
end do:
end proc:</syntaxhighlight>
<syntaxhighlight lang="maple">GuessANumber(2,5);</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">guessnumber[min_, max_] :=
Module[{number = RandomInteger[{min, max}], guess},
While[guess =!= number,
Line 1,461 ⟶ 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,492 ⟶ 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,510 ⟶ 3,054:
)
)
</syntaxhighlight>
</lang>
 
Output:
<syntaxhighlight lang="maxscript">
<lang MAXSCRIPT>
Enter a number between 1 and 100: 5
Too low!
Line 1,527 ⟶ 3,071:
Well guessed!
OK
</syntaxhighlight>
</lang>
 
=={{header|Mirah}}==
<langsyntaxhighlight lang="mirah">def getInput:int
s = System.console.readLine()
Integer.parseInt(s)
Line 1,555 ⟶ 3,099:
puts "Please enter an integer."
end
end</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE guessf;
 
IMPORT InOut, Random, NumConv, Strings;
Line 1,597 ⟶ 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 1,610 ⟶ 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 1,638 ⟶ 3,221:
} while (guess != secret)
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,703 ⟶ 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 1,733 ⟶ 3,316:
(println "\nWell guessed! Congratulations!")
 
(exit)</langsyntaxhighlight>
 
Sample output:
Line 1,750 ⟶ 3,333:
</pre>
 
=={{header|NimrodNim}}==
<syntaxhighlight lang nimrod="nim">import math, rdstdinrandom, strutils
 
randomize()
Line 1,758 ⟶ 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 EInvalidValueValueError:
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 1,830 ⟶ 3,400:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let rec _read_int() =
try read_int()
with _ ->
Line 1,868 ⟶ 3,438:
loop ()
in
loop ()</langsyntaxhighlight>
 
Playing the game:
Line 1,901 ⟶ 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 1,927 ⟶ 3,497:
end
end
disp('Well guessed!')</langsyntaxhighlight>
 
=={{header|PARI/GPOforth}}==
 
<lang parigp>guess_the_number(N=10)={
<syntaxhighlight lang="oforth">import: console
a=random(N);
 
print("guess the number between 0 and "N);
: guessNumber(a, b)
for(x=1,N,
| n g |
if(x>1,
b a - rand a + 1- ->n
if(b>a,
begin
print("guess again lower")
"Guess a number between" . a . "and" . b . ":" .
,
while(System.Console askln asInteger dup -> g isNull) [ "Not a number " println ]
print("guess again higher")
g n == ifTrue: [ "You found it !" .cr return ]
);
g n < ifTrue: [ "Less" ] else: [ "Greater" ] . "than the target" .cr
b=input();
again ;</syntaxhighlight>
if(b==a,break())
 
);
=={{header|Ol}}==
print("You guessed it correctly")
};</syntaxhighlight lang="ol">
(import (otus random!))
 
(define from 0)
(define to 100)
 
(define number (+ from (rand! (+ from to 1))))
 
(let loop ()
(for-each display `("Pick a number from " ,from " through " ,to ": "))
(let ((guess (read)))
(cond
((not (number? guess))
(print "Not a number!")
(loop))
((or (< guess from)
(< to guess))
(print "Out of range!")
(loop))
((< guess number)
(print "Too low!")
(loop))
((> guess number)
(print "Too high!")
(loop))
((= guess number)
(print "Well guessed!")))))
</syntaxhighlight>
 
=={{header|ooRexx}}==
Line 1,954 ⟶ 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,011 ⟶ 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,034 ⟶ 3,649:
while ($_ = $tgt <=> prompt "Your guess");
 
print "Correct! You guessed it after $tries tries.\n";</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
 
<span style="color: #000080;font-style:italic;">--
<lang perl6>my $maxnum = prompt("Hello, please give me an upper boundary: ");
-- demo\rosetta\Guess_the_number3.exw
until 0 < $maxnum < Inf {
--</span>
say "Oops! The upper boundary should be > 0 and not Inf";
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
$maxnum = prompt("Please give me a valid upper boundary: ");
<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>
}
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
 
my $count = 0;
<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>
my $number = (1..$maxnum).pick;
<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>
say "I'm thinking of a number from 1 to $maxnum, try to guess it!";
<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>
repeat until my $guessed-right {
given prompt("Your guess: ") {
<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>
when /^[e|q]/ { say 'Goodbye.'; exit; }
when not 1 <= $_ <= $maxnum {
<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>
say "You really should give me a number from 1 to $maxnum."
<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>
$count++;
<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>
when $number { $guessed-right = True }
<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>
when $number < $_ { say "Sorry, my number is smaller." }
<span style="color: #008000;">"uh?"</span><span style="color: #0000FF;">)))</span>
when $number > $_ { say "Sorry, my number is bigger." }
<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>
say "Great you guessed right after $count attempts!";</lang>
 
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<pre>Hello, please give me an upper boundary: 10
<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>
I'm thinking of a number from 1 to 10, try to guess it!
<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>
Your guess: 5
<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>
Sorry, my number is bigger.
<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>
Your guess: 7
<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>
Sorry, my number is smaller.
<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>
Your guess: 6
<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>
Great you guessed right after 3 attempts!</pre>
<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,123 ⟶ 3,744:
</body>
</html>
</syntaxhighlight>
</lang>
 
 
=={{header|PicoLisp}}==
{{trans|PureBasic}}
<langsyntaxhighlight PicoLisplang="picolisp">(de guessTheNumber ()
(use (Low High Guess)
(until
Line 2,146 ⟶ 3,766:
"Your guess is too "
(if (> Number Guess) "low" "high")
"." ) ) ) ) )</langsyntaxhighlight>
Output:
<pre>: (guessTheNumber)
Line 2,158 ⟶ 3,778:
You got it!</pre>
 
=={{header|PureBasicPlain English}}==
<syntaxhighlight lang="plainenglish">The low number is 1.
<lang PureBasic>OpenConsole()
 
The high number is 100.
Repeat
; Ask for limits, with sanity check
Print("Enter low limit : "): low =Val(Input())
Print("Enter high limit: "): High =Val(Input())
Until High>low
 
To run:
TheNumber=Random(High-low)+low
Start up.
Debug TheNumber
Play the guessing game.
Repeat
Wait for the escape key.
Print("Guess what number I have: "): Guess=Val(Input())
Shut down.
If Guess=TheNumber
 
PrintN("You got it!"): Break
To play the guessing game:
ElseIf Guess < TheNumber
Pick a secret number between the low number and the high number.
PrintN("Your guess is to low.")
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.
Else
Loop.
PrintN("Your guess is to high.")
Ask the user for a number.
EndIf
If the number is the secret number, break.
ForEver</lang>
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">
function Get-Guess
{
[int]$number = 1..100 | Get-Random
[int]$guess = 0
[int[]]$guesses = @()
 
Write-Host "Guess a number between 1 and 100" -ForegroundColor Cyan
 
while ($guess -ne $number)
{
try
{
[int]$guess = Read-Host -Prompt "Guess"
 
if ($guess -lt $number)
{
Write-Host "Greater than..."
}
elseif ($guess -gt $number)
{
Write-Host "Less than..."
}
else
{
Write-Host "You guessed it"
}
}
catch [Exception]
{
Write-Host "Input a number between 1 and 100." -ForegroundColor Yellow
continue
}
 
$guesses += $guess
}
 
[PSCustomObject]@{
Number = $number
Guesses = $guesses
}
}
 
$answer = Get-Guess
 
Write-Host ("The number was {0} and it took {1} guesses to find it." -f $answer.Number, $answer.Guesses.Count)
</syntaxhighlight>
{{Out}}
<pre>
Guess a number between 1 and 100
Guess: 50
Greater than...
Guess: 60
Greater than...
Guess: a
Input a number between 1 and 100.
Guess: 70
Greater than...
Guess: 80
Less than...
Guess: 75
Less than...
Guess: 73
You guessed it
The number was 73 and it took 6 guesses to find it.
</pre>
 
=={{header|Prolog}}==
Line 2,184 ⟶ 3,905:
{{works with|SWI-Prolog|6}}
 
<langsyntaxhighlight lang="prolog">main :-
play_guess_number.
 
Line 2,220 ⟶ 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,258 ⟶ 4,001:
if answer > target: print(" Too high.")
 
print("\nThanks for playing.")</langsyntaxhighlight>
 
'''Sample Game'''
Line 2,292 ⟶ 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.
 
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.
 
<syntaxhighlight lang="rsplus">guessANumber <- function(low, high)
{
boundryErrorCheck(low, high)
goal <- sample(low:high, size = 1)
guess <- getValidInput(paste0("I have a whole number between ", low, " and ", high, ". What's your guess? "))
while(guess != goal)
{
if(guess < low || guess > high){guess <- getValidInput("Out of range! Try again "); next}
if(guess > goal){guess <- getValidInput("Too high! Try again "); next}
if(guess < goal){guess <- getValidInput("Too low! Try again "); next}
}
"Winner!"
}
 
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 min 1)
(define max 10)
 
(define (guess-number (number (+ min (random max))))
(define guesstarget (read+ min (random (- max min -1))))
(printf "I'm thinking of a number between ~a and ~a\n" min max)
(cond ((not (number? guess)) (display "That's not a number!\n" (guess-number number)))
(let loop ([prompt "Your guess"])
((or (> guess max) (> min guess)) (display "Out of range!\n") (guess-number number))
(printf "~a: " prompt)
((> guess number) (display "Too high!\n") (guess-number number))
(flush-output)
((< guess number) (display "Too low!\n") (guess-number number))
(define guess (read))
(else (display "Well guessed!\n"))))
(define response
(cond [(not (exact-integer? guess)) "Please enter a valid integer"]
[(< guess target) "Too low"]
[(> guess target) "Too high"]
[else #f]))
(when response (printf "~a\n" response) (loop "Try again")))
(printf "Well guessed!\n"))
 
(guess-number 1 100)
(display (format "Guess a number between ~a and ~a\n" min max))
</syntaxhighlight>
(guess-number)</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,325 ⟶ 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 that plays the guessingguess (the number) game. with a human; the computer picks the number*/
low= 1 /*the lower range for the guessing game. */
high= 100 /* " upper range for guessing" " " " game." */
try= 0 /*the number of valid (guess) attempts. */
r= random(1low,100 high) /*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'
er! erm= '*** error! ***'
prompt @gtn=centre( "guess the number, it's between" low 'and',
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.*/
do validate=0
select
when g=='' then iterate ask
when abbrev('QUIT', g, 1) then exit /*what a whoos.*/
when words(g) \== 1 then say er!erm 'too many numbers entered:' g
when \datatype(g, 'N') then say er!erm g "isn't numeric"
when \datatype(g, 'W') then say er!erm g "isn't a whole number"
when g<low then say er!erm g 'is below the lower limit of' low
when g>high then say er!erm g 'is above the higher limit of' high
otherwise leave /*validate*/
end /*select*/
iterate ask
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>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">fr = 1 t0 = 10
while true
see "Hey There,
========================
I'm thinking of a number between " + fr + " and " + t0 + ", Can you guess it??
Guess :> "
give x
n = nrandom(fr,t0)
if x = n see "
 
Congratulations :D
 
*****************************************************
** Your guess was right You Are Genius :D **
*****************************************************
 
 
"
exit
else
see "Oops its not true, you were just few steps"
if x > n see " up :)" else see " down :)" ok
see copy(nl,3)
ok
end
 
func nRandom s,e
if try==1 then say 'Gadzooks!!! You guessed the number right away!'
while true
else say 'Congratulations!, you guessed the number in' try "tries."
d = random(e)
/*stick a fork in it, we're done.*/</lang>
if d >= s return d ok
end</syntaxhighlight>
 
=={{header|Ruby}}==
{{trans|Mirah}}
<langsyntaxhighlight lang="ruby">number = rand(1..10)
 
puts "Guess the number between 1 and 10"
Line 2,386 ⟶ 4,290:
puts "Please enter an integer."
end
end</langsyntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand}}
{{works with|rustc|0.12.0-pre-nightly}}
<syntaxhighlight lang ="rust">use std::iorand::IoResultRng;
use std::iocmp::stdio::stdinOrdering;
use std::rand::{Rng, task_rng}io;
 
staticconst LOWEST: intu32 = 1;
staticconst HIGHEST: intu32 = 100;
 
fn main() {
let secret_number = rand::thread_rng().gen_range(1..101);
let mut rng = task_rng();
 
let mut stdin = stdin();
println!("I have chosen my number between {} and {}. Guess the number!", LOWEST, HIGHEST);
 
loop {
let number: int = rng.gen_range(LOWEST, HIGHEST + 1);
let mut num_guesses = 0i;
println!("I have chosen my number between {:d} and {:d}. You know what to do", LOWEST, HIGHEST);
loop {
println!("Please input your guess.");
num_guesses += 1;
let line: IoResult<String> = stdin.read_line();
let val: Option<int> = line.ok().map_or(None, |line| from_str::<int>(line.as_slice().trim()));
 
let mut guess = String::new();
match val {
 
None => println!("numbers only, please"),
Someio::stdin(n) if n == number => {
.read_line(&mut guess)
println!("you got it in {:d} tries!", num_guesses);
break .expect("Failed to read line");
 
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
 
println!("You guessed: {}", guess);
 
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
Some(n) if n < number => println!("too low!"),
Some(n) if n > number => println!("too high!"),
Some(_) => println!("something went wrong")
}
}
}</syntaxhighlight>
}
<pre>I have chosen my number between 1 and 100. Guess the number!
}</lang>
Please input your guess.
<pre>I have chosen my number between 0 and 100. You know what to do
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}}==
<syntaxhighlight lang="scala">import java.util.Random
import java.util.Scanner
 
val scan = new Scanner(System.in)
val random = new Random
val (from , to) = (1, 100)
val randomNumber = random.nextInt(to - from + 1) + from
var guessedNumber = 0
printf("The number is between %d and %d.\n", from, to)
 
do {
print("Guess what the number is: ")
guessedNumber = scan.nextInt
if (guessedNumber > randomNumber) println("Your guess is too high!")
else if (guessedNumber < randomNumber) println("Your guess is too low!")
else println("You got it!")
} while (guessedNumber != randomNumber)</syntaxhighlight>
 
=={{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 2,462 ⟶ 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 2,491 ⟶ 4,434:
writeln("You gave up!");
end if;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<syntaxhighlight lang="ruby">var number = rand(1..10);
say "Guess the number between 1 and 10";
 
loop {
given(var n = Sys.scanln("> ").to_i) {
when (number) { say "You guessed it."; break }
case (n < number) { say "Too low" }
default { say "Too high" }
}
}</syntaxhighlight>
 
=={{header|Small Basic}}==
<syntaxhighlight lang="small basic">number=Math.GetRandomNumber(10)
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
While guess<>number
guess=TextWindow.ReadNumber()
If guess>number Then
TextWindow.WriteLine("Lower number!")
EndIf
If guess<number Then
TextWindow.WriteLine("Higher number!")
EndIf
EndWhile
TextWindow.WriteLine("You win!")</syntaxhighlight>
 
=={{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 2,520 ⟶ 4,598:
break;
}
}</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Cocoa
 
var found = false
Line 2,544 ⟶ 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 2,566 ⟶ 4,645:
break
}
}</langsyntaxhighlight>
Sample output:
<pre>
Line 2,585 ⟶ 4,664:
Well done! You guessed it.
</pre>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
Line 2,607 ⟶ 4,687:
IF (round==7) PRINT/ERROR "You've lost: luckynumber was: ",luckynumber
ENDLOOP
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,634 ⟶ 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 2,659 ⟶ 4,739:
fi
done
}</langsyntaxhighlight>
 
Sample run:
Line 2,675 ⟶ 4,755:
You got it in 5 guesses!
</pre>
 
=={{header|Ursa}}==
{{trans|Python}}
<syntaxhighlight lang="ursa">decl int high low
set low 0
set high 100
 
out "Guess a number between " low " and " high "." endl endl console
decl int target answer i
decl ursa.util.random random
set target (int (+ 1 (+ low (random.getint (int (- high low))))))
while (not (= answer target))
inc i
out "Your guess(" i "): " console
set answer (in int console)
if (or (< answer low) (> answer high))
out " Out of range!" endl console
continue
end if
if (= answer target)
out " Ye-Haw!!" endl console
continue
end if
if (< answer target)
out " Too low." endl console
end if
if (> answer target)
out " Too high." endl console
end if
end while
 
out endl "Thanks for playing." endl console</syntaxhighlight>
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">
void main(){
const int from = 1;
Line 2,709 ⟶ 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 2,720 ⟶ 4,833:
stdout.printf("Got it!\n");
return 0;
}</langsyntaxhighlight>
 
=={{header|VBA Excel}}==
The Application.InputBox display a message when input is inappropriate.
<syntaxhighlight lang="vb">Sub GuessTheNumberWithFeedback()
Dim Nbc&, Nbp&, m&, n&, c&
 
Randomize Timer
m = 11
n = 100
Nbc = Int((Rnd * (n - m + 1)) + m)
Do
c = c + 1
Nbp = Application.InputBox("Choose a number between " & m & " and " & n & " : ", "Enter your guess", Type:=1)
Select Case Nbp
Case Is > Nbc: MsgBox "Higher than target!"
Case Is < Nbc: MsgBox "Less than target!"
Case Else: Exit Do
End Select
Loop
MsgBox "Well guessed!" & vbCrLf & "You find : " & Nbc & " in " & c & " guesses!"
End Sub</syntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Dim max,min,secretnum,numtries,usernum
max=100
min=1
numtries=0
Randomize
secretnum = Int((max-min+1)*Rnd+min)
 
Do While usernum <> secretnum
usernum = Inputbox("Guess the secret number beween 1-100","Guessing Game")
If IsEmpty(usernum) Then
WScript.Quit
End If
If IsNumeric(usernum) Then
numtries = numtries + 1
usernum = Cint(usernum)
If usernum < secretnum Then
Msgbox("The secret number is higher than " + CStr(usernum))
ElseIf usernum > secretnum Then
Msgbox("The secret number is lower than " + CStr(usernum))
Else
Msgbox("Congratulations, you found the secret number in " + CStr(numtries) + " guesses!")
End If
Else
Msgbox("Please enter a valid number.")
End If
Loop
</syntaxhighlight>
 
=={{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}}==
<syntaxhighlight lang="lisp">(defun guessing-game (a b)
; minimum and maximum, to be supplied by the user
(defun prompt ()
(display "What is your guess? ")
(define guess (read))
(if (eq guess n) ; EQ, unlike =, won't blow up
; if GUESS isn't a number
(display "Well guessed!")
(begin
(display
(cond
((not (integer? guess)) "Come on, that isn't even an integer")
((or (< guess a) (> guess b)) "Now you k n o w it won't be that")
((< guess n) "Too low")
((> guess n) "Too high")))
(display "! Try again...")
(newline)
(prompt))))
(define n (+ (random (- (+ b 1) a)) a))
(display "I have thought of an integer between ")
(display a)
(display " and ")
(display b)
(display ". Try to guess it!")
(newline)
(prompt))</syntaxhighlight>
{{out}}
<pre>[1] (guessing-game 19 36)
I have thought of an integer between 19 and 36. Try to guess it!
What is your guess? 2
Now you k n o w it won't be that! Try again...
What is your guess? 25
Too high! Try again...
What is your guess? 24.5
Come on, that isn't even an integer! Try again...
What is your guess? n
Come on, that isn't even an integer! Try again...
What is your guess? 19
Too low! Try again...
What is your guess? 22
Too high! Try again...
What is your guess? 21
Too high! Try again...
What is your guess? 20
Well guessed!</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int Lo, Hi, C, Guess, Number;
 
Line 2,746 ⟶ 5,071:
CrLf(0);
until Guess = Number;
]</langsyntaxhighlight>
 
Example output:
Line 2,764 ⟶ 5,089:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">r:=(0).random(10)+1;
while(1){
n:=ask("Num between 1 & 10: ");
Line 2,770 ⟶ 5,095:
if(n==r){ println("Well guessed!"); break; }
println((n<r) and "small" or "big");
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,785 ⟶ 5,110:
</pre>
 
=={{header|Zoomscript}}==
{{omit from|Lilypond}}
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}}==
<syntaxhighlight 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</syntaxhighlight>
305

edits