fn drawBarRow _bmp _row _width _number _inverse=
(
	local dir = if _inverse then 1 else -1
		if not _inverse then
		(
			setpixels _bmp [0,_row] (for i in 1 to (_width/_number) collect (black))
			for i = (_width/_number) to _width by (_width/_number) do
			(
				local loopPosition = i/(_width-(_width/_number)) as float
				local colorsArr = for c in 1 to (_width/_number) collect (white*loopPosition)
				setpixels _bmp [i,_row] colorsArr
			)
			return _bmp
		)
		else
		(
			setpixels _bmp [0,_row] (for i in 1 to (_width/_number) collect (white))
			for i = _width to (_width/_number) by ((_width/_number)*-1) do
			(
				local loopPosition = 1.0-(i/(_width-(_width/_number))) as float
				local colorsArr = for c in 1 to (_width/_number) collect (white*loopPosition)
				setpixels _bmp [i,_row] colorsArr
			)
			return _bmp
		)

)

fn bitmap_verticalBars =
(
	local width = (sysinfo.desktopsize).x
	local height = (sysinfo.desktopsize).y
	local theBitmap = bitmap width height color:white

	local row = 0
	while row <= (height-1) do
	(
		local barNumber = 0
		case of
		(
			(row < (height/4)): (barNumber = 1)
			(row >= (height/4) and row < (height/2)): (barNumber = 2)
			(row >= (height/2) and row < (height-(height/4))): (barNumber = 3)
			(row >= (height-(height/4))): (barNumber = 4)
			default: return theBitmap
		)
		case barNumber of
		(
			1: (
					theBitmap = drawBarRow theBitmap row width 8 false
				)
			2: (
					theBitmap = drawBarRow theBitmap row width 16 true
				)
			3: (
					theBitmap = drawBarRow theBitmap row width 32 false
				)
			4: (
					theBitmap = drawBarRow theBitmap row width 64 true
				)
		)
		row += 1
		--
	)
	return theBitmap
)

b = bitmap_verticalBars()
display b


import gintro/[glib, gobject, gtk, gio, cairo]

const
  Width = 640
  Height = 480

#---------------------------------------------------------------------------------------------------

proc draw(area: DrawingArea; context: Context) =
  ## Draw the greyscale bars.

  const
    Black = 0.0
    White = 1.0

  var y = 0.0
  var nrect = 8
  let rectHeight = Height / 4

  # Draw quarters.
  for quarter in 0..3:
    let rectWidth = Width / nrect
    var x = 0.0
    var (grey, incr) = if (quarter and 1) == 0: (Black, 1 / nrect) else: (White, -1 / nrect)

    # Draw rectangles.
    for _ in 1..nrect:
      context.rectangle(x, y, rectWidth, rectHeight)
      context.setSource([grey, grey, grey])
      context.fill()
      x += rectWidth
      grey += incr

    y += rectHeight
    nrect *= 2

#---------------------------------------------------------------------------------------------------

proc onDraw(area: DrawingArea; context: Context; data: pointer): bool =
  ## Callback to draw/redraw the drawing area contents.

  area.draw(context)
  result = true

#---------------------------------------------------------------------------------------------------

proc activate(app: Application) =
  ## Activate the application.

  let window = app.newApplicationWindow()
  window.setSizeRequest(Width, Height)
  window.setTitle("Greyscale bars")

  # Create the drawing area.
  let area = newDrawingArea()
  window.add(area)

  # Connect the "draw" event to the callback to draw the spiral.
  discard area.connect("draw", ondraw, pointer(nil))

  window.showAll()

#———————————————————————————————————————————————————————————————————————————————————————————————————

let app = newApplication(Application, "Rosetta.GreyscaleBars")
discard app.connect("activate", activate)
discard app.run()


open Graphics

let round x = truncate (floor (x +. 0.5))

let () =
  open_graph "";
  let width = size_x ()
  and height = size_y () in
  let bars = [| 8; 16; 32; 64 |] in
  let n = Array.length bars in
  Array.iteri (fun i bar ->
    let part = float width /. float bar in
    let y = (height / n) * (n - i - 1) in
    for j = 0 to pred bar do
      let x = round (float j *. part) in
      let v = round (float j *. 255. /. float (bar - 1)) in
      let v = if (i mod 2) = 0 then v else 255 - v in
      set_color (rgb v v v);
      fill_rect x y (round part) (height / n)
    done
  ) bars;
  ignore(read_key())


sub partition {
    my($all, $div) = @_;
    my @marks = 0;
    push @marks, $_/$div * $all for 1..$div;
    my @copy = @marks;
    $marks[$_] -= $copy[$_-1] for 1..$#marks;
    @marks[1..$#marks];
}

sub bars {
    my($h,$w,$p,$rev) = @_;
    my (@nums,@vals,$line,$d);

    $d  = 2**$p;
    push @nums, int $_/($d-1) * (2**16-1) for $rev ? reverse 0..$d-1 : 0..$d-1;
    push @vals, ($nums[$_]) x (partition($w, $d))[$_] for 0..$#nums;
    $line = join(' ', @vals) . "\n";
    $line x $h;
}

my($w,$h) = (1280,768);
open my $pgm, '>', 'Greyscale-bars-perl5.pgm' or die "Can't create Greyscale-bars-perl5.pgm: $!";

print $pgm <<"EOH";
P2
# Greyscale-bars-perl5.pgm
$w $h
65535
EOH

my ($h1,$h2,$h3,$h4) = partition($h,4);

print $pgm
    bars($h1,$w,3,0),
    bars($h2,$w,4,1),
    bars($h3,$w,5,0),
    bars($h4,$w,6,1);


--
-- demo\rosetta\Greyscale_bars.exw
-- ===============================
--
with javascript_semantics
include pGUI.e

Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas

integer quit = 1
bool refire = false

function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
    cdCanvasActivate(cddbuffer)
    integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE")
    integer h = floor(height/4)
    height -= 1
    for row=1 to 4 do
        integer x = 0, p2 = power(2,row+2), c = floor(255/(p2-1))
        for n=0 to p2-1 do
            integer colour = c*n*#010101
            if and_bits(row,1)=0 then colour = xor_bits(colour,#FFFFFF) end if
            cdCanvasSetForeground(cddbuffer, colour)
            integer nx = ceil(width*(n+1)/p2)
            cdCanvasBox(cddbuffer, x, nx-1, (4-row)*h, height)
            x = nx
        end for
        height = (4-row)*h-1
    end for
    cdCanvasFlush(cddbuffer)
    return IUP_DEFAULT
end function

function map_cb(Ihandle ih)
    cdcanvas = cdCreateCanvas(CD_IUP, ih)
    cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
    return IUP_DEFAULT
end function

function unmap_cb(Ihandle /*ih*/)
    cdKillCanvas(cddbuffer)
    cdKillCanvas(cdcanvas)
    return IUP_DEFAULT
end function

procedure main()
    IupOpen()
    canvas = IupCanvas("RASTERSIZE=600x400")
    IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
                             "UNMAP_CB", Icallback("unmap_cb"),
                             "ACTION", Icallback("redraw_cb")})
    dlg = IupDialog(canvas, `TITLE="Greyscale bars"`)
    IupShow(dlg)
    IupSetAttribute(canvas, "RASTERSIZE", NULL)
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

main()


(let Pgm  # Create PGM of 384 x 288 pixels
   (make
      (for N 4
         (let L
            (make
               (for I (* N 8)
                  (let C (*/ (dec I) 255 (dec (* N 8)))
                     (unless (bit? 1 N)
                        (setq C (- 255 C)) )
                     (do (/ 48 N) (link C)) ) ) )
            (do 72 (link L)) ) ) )
   (out '(display)  # Pipe to ImageMagick
      (prinl "P5")  # NetPBM format
      (prinl (length (car Pgm)) " " (length Pgm))
      (prinl 255)
      (for Y Pgm (apply wr Y)) ) )


To run:
Start up.
Clear the screen.
Imagine a box with the screen's left and the screen's top and the screen's right and the screen's bottom divided by 4.
Make a gradient with the box and 8 and "left-to-right".
Draw the gradient.
Draw the next gradient given the gradient.
Draw the next gradient given the gradient.
Draw the next gradient given the gradient.
Refresh the screen.
Wait for the escape key.
Shut down.

A gradient is a record with
A box,
A partitions number,
And a direction string. \"left-to-right" or "right-to-left"

To make a gradient with a box and a number and a string:
Put the box into the gradient's box.
Put the number into the gradient's partitions.
Put the string into the gradient's direction.

To draw a gradient:
Put the white color into a color.
Put 1000 [the maximum lightness] divided by the gradient's partitions into an amount.
If the gradient's direction is "left-to-right", put the black color into the color.
Put the gradient's box into a box.
Put the gradient's box's width divided by the gradient's partitions into a width number.
Put the width plus the box's left into the box's right.
Loop.
If a counter is past the gradient's partitions, exit.
Draw and fill the box with the color.
Move the box right the width.
If the gradient's direction is "left-to-right", lighten the color by the amount; repeat.
Darken the color by the amount.
Repeat.

To draw the next gradient given a gradient:
Move the gradient's box down the gradient's box's height.
Double the gradient's partitions.
If the gradient's direction is "left-to-right", set a flag.
If the flag is set, put "right-to-left" into the gradient's direction.
If the flag is not set, put "left-to-right" into the gradient's direction.
Draw the gradient.


EnableExplicit

Macro Check(Function)
  If Not Function : End : EndIf
EndMacro

Check(InitKeyboard())    ; Cannot initialize keyboard
Check(InitSprite())      ; Cannot initialize sprite/screen library
Check(ExamineDesktops()) ; Cannot retrieve informations about desktops

Define.i iHeight, iWidth, iDepth
iHeight = DesktopHeight(0)
iWidth  = DesktopWidth(0)
iDepth  = DesktopDepth(0)

If OpenScreen(iWidth, iHeight, iDepth, "Press ENTER to exit")
  Define.i bMode.b, iLines, fLine.f, iRow, iSpans, fSpan.f,
           fColor.f, iTop, iWide, iHigh, iCol, iShade
  If StartDrawing(ScreenOutput())

    bMode  = #True ; Pow = #True; Add = #False
    iLines = 4     ; Number of Lines

    If   iLines < 1  : iLines = 1  : EndIf ; Pow/Add-Min
    If bMode
      If iLines > 6  : iLines = 6  : EndIf ; Pow-Max
    Else
      If iLines > 32 : iLines = 32 : EndIf ; Add-Max
    EndIf
    fLine  = iHeight / iLines
    iLines - 1

    For iRow = 0 To iLines
      If bMode
        iSpans = Pow(2, iRow + 3) - 1 ; Pow: 8, 16, 32, 64, 128, 256
      Else
        iSpans = (iRow + 1) * 8 - 1   ; Add: 8, 16, 24, 32, 40, 48, ...
      EndIf
      fSpan  = iWidth / (iSpans + 1)
      fColor = 255 / iSpans
      iTop   = Round(iRow * fLine, #PB_Round_Up)
      iWide  = Round(fSpan, #PB_Round_Up)
      iHigh  = Round(fLine, #PB_Round_Up)
      For iCol = 0 To iSpans
        iShade = Round(fColor * iCol, #PB_Round_Nearest)
        If iRow % 2 <> 0 : iShade = 255 - iShade : EndIf ; Alternation
        Box(Round(iCol * fSpan, #PB_Round_Up), iTop, iWide, iHigh,
            RGB(iShade, iShade, iShade))
      Next
    Next

    StopDrawing()
    FlipBuffers()

    Repeat
      Delay(30)
      ExamineKeyboard()
    Until KeyboardPushed(#PB_Key_Escape) Or
          KeyboardPushed(#PB_Key_Return)
  EndIf
  CloseScreen()
EndIf
End


#!/usr/bin/env python
#four gray scaled stripes 8:16:32:64 in Python 2.7.1

from livewires import *

horiz=640; vert=480; pruh=vert/4; dpp=255.0
begin_graphics(width=horiz,height=vert,title="Gray stripes",background=Colour.black)

def ty_pruhy(each):
	hiy=each[0]*pruh; loy=hiy-pruh
	krok=horiz/each[1]; piecol=255.0/(each[1]-1)
	for x in xrange(0,each[1]):
		barva=Colour(piecol*x/dpp,piecol*x/dpp,piecol*x/dpp ); set_colour(barva)
		if each[2]:
			box(x*krok,hiy,x*krok+krok,loy,filled=1)
		else:
			box(horiz-x*krok,hiy,horiz-((x+1)*krok),loy,filled=1)

# main
source=[[4,8,True],[3,16,False],[2,32,True],[1,64,False]]
for each in source:
	ty_pruhy(each)

while keys_pressed() != [' ']: # press spacebar to close window
	pass


#lang racket/gui
(require slideshow/pict)

(define-values (*width* *height*) (values 400 40))

(define (shades inc)
  (for/list ([scale (in-range 0 (+ 1 inc) inc)])
    (round (* 255 scale))))

(define (grays increment direction)
  (define colors (shades increment))
  (apply hc-append
         ((if (eq? direction 'right) identity reverse)
          (for/list ([c colors])
            (colorize (filled-rectangle
                       (/ *width* (length colors)) *height*)
                      (make-color c c c))))))

(vc-append (grays 1/8 'right)  (grays 1/16 'left)
           (grays 1/32 'right) (grays 1/64 'left))


my ($width,$height) = 1280,768;

my $PGM = open "Greyscale-bars-perl6.pgm", :w orelse die "Can't create Greyscale-bars-perl6.pgm: $_";

$PGM.print: qq:to/EOH/;
    P2
    # Greyscale-bars-perl6.pgm
    $width $height
    65535
    EOH

my ($h1,$h2,$h3,$h4) = divvy($height,4);

my @nums = ((0/7,1/7...7/7) X* 65535)».floor;
my $line = ~(@nums Zxx divvy($width,8));
$PGM.say: $line for ^$h1;

@nums = ((15/15,14/15...0/15) X* 65535)».floor;
$line = ~(@nums Zxx divvy($width,16));
$PGM.say: $line for ^$h2;

@nums = ((0/31,1/31...31/31) X* 65535)».floor;
$line = ~(@nums Zxx divvy($width,32));
$PGM.say: $line for ^$h3;

@nums = ((63/63,62/63...0/63) X* 65535)».floor;
$line = ~(@nums Zxx divvy($width,64));
$PGM.say: $line for ^$h4;

$PGM.close;

sub divvy($all, $div) {
    my @marks = ((1/$div,2/$div ... 1) X* $all)».round;
    @marks Z- 0,|@marks;
}


Declare Sub PaintCanvas

Create Form as Qform
    Caption = "Rosetta Greyscale"
    Center
    create Canv as QCanvas
        align = 5
        onPaint = PaintCanvas
    end create
end create

Sub PaintCanvas
    NumRows = 4 'Change for number of rows
    for curbar = 0 to NumRows-1
        Bars = 2^(curbar+3)
        for x = 0 to (Bars -1)
            x1=Canv.Width/Bars*x
            y1=Canv.Height/NumRows*CurBar
            x2=Canv.Width/Bars*(x+1)
            y2=Canv.Height/NumRows*(CurBar+1)
            c=(255/(Bars-1))*x
            c=iif(curbar mod 2, 255-c, c)
            Canv.FillRect(x1, y1, x2, y2, rgb(c, c, c))
        next x
    next curbar
end sub

Form.showmodal


# Project : Greyscale bars/Display

load "guilib.ring"

paint = null

new qapp
        {
        win1 = new qwidget() {
                  setwindowtitle("Greyscale bars/Display")
                  setgeometry(100,100,500,600)
                  label1 = new qlabel(win1) {
                              setgeometry(10,10,400,400)
                              settext("")
                  }
                  new qpushbutton(win1) {
                          setgeometry(150,500,100,30)
                          settext("draw")
                          setclickevent("draw()")
                  }
                  show()
        }
        exec()
        }

func draw
        p1 = new qpicture()
               color = new qcolor() {
               setrgb(0,0,255,255)
        }
        pen = new qpen() {
                 setcolor(color)
                 setwidth(1)
        }
        paint = new qpainter() {
                  begin(p1)
                  setpen(pen)

        for row=1 to 4
              n=pow(2,(row+2))
              w=1280/n
              py=256*(4-row)
              for b=0 to n-1
                   g=floor(255*b/(n-1))
                   if n=16 or n=64
                      g=255-g
                   ok
                   color2 = new qcolor()
                   color2.setrgb(g,g,g,255)
                   mybrush = new qbrush() {setstyle(1) setcolor(color2)}
                   paint.setbrush(mybrush)
                   paint.drawrect(w*b,py,w,256)
              next
        next

        endpaint()
        }
        label1 { setpicture(p1) show() }


for i = 1 to 4
	incr	= int(256 / (i * 8))
	c	= 256
        html "

"
	for j = 1 to i * 8
		html "	"
		c = c - incr
	next j
        html "
"
next i
html "
"
end


import scala.swing._

class GreyscaleBars extends Component {
  override def paintComponent(g:Graphics2D)={
    val barHeight=size.height>>2
    for(run <- 0 to 3; colCount=8<<run){
      val deltaX=size.width.toDouble/colCount
      val colBase=if (run%2==0) -255 else 0
      for(x <- 0 until colCount){
        val col=(colBase+(255.0/(colCount-1)*x).toInt).abs
        g.setColor(new Color(col,col,col))

        val startX=(deltaX*x).toInt
        val endX=(deltaX*(x+1)).toInt
        g.fillRect(startX, barHeight*run, endX-startX, barHeight)
      }
    }
  }
}


$ include "seed7_05.s7i";
  include "draw.s7i";
  include "keybd.s7i";

const proc: main is func
  local
    var integer: barHeight is 0;
    var integer: barNumber is 0;
    var integer: colCount is 0;
    var integer: deltaX is 0;
    var integer: x is 0;
    var integer: col is 0;
  begin
    screen(640, 480);
    KEYBOARD := GRAPH_KEYBOARD;
    barHeight := height(curr_win) div 4;
    for barNumber range 0 to 3 do
      colCount := 8 << barNumber;
      deltaX := width(curr_win) div colCount;
      for x range 0 to pred(colCount) do
        if barNumber rem 2 = 0 then
          col := 65535 - 65535 div pred(colCount) * x;
        else
          col := 65535 div pred(colCount) * x;
        end if;
        rect(deltaX * x, barHeight * barNumber, deltaX, barHeight,
            color(col, col, col));
      end for;
    end for;
    ignore(getc(KEYBOARD));
  end func;


package require Tcl 8.5
package require Tk 8.5

wm attributes . -fullscreen 1
pack [canvas .c -highlightthick 0] -fill both -expand 1

# Add more values into this to do more greyscale bar variations
set splits {8 16 32 64}
set dy [expr {[winfo screenheight .c] / [llength $splits]}]
set y 0
foreach s $splits {
    set dx [expr {double([winfo screenwidth .c]) / $s}]
    set dc [expr {double(0xFF) / ($s-1)}]
    for {set i 0} {$i < $s} {incr i} {
	set c [expr {int($i * $dc)}]
	set x [expr {int($i * $dx)}]
	.c create rectangle $x $y [expr {$x+$dx+1}] [expr {$y+$dy+1}] \
            -fill [format "#%02x%02x%02x" $c $c $c] -outline {}
    }
    incr y $dy
}


import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math

class GreyBars {
    construct new(width, height) {
        Window.title = "Grey bars example"
        Window.resize(width, height)
        Canvas.resize(width, height)
        _w = width
        _h = height
    }

    init() {
        drawBars()
    }

    drawBars() {
        var run = 0
        var colorComp = 0 // component of the color
        var columnCount = 8
        while (columnCount < 128) {
            var colorGap = 255 / (columnCount - 1) // by this gap we change the background color
            var columnWidth = (_w / columnCount).floor
            var columnHeight = (_h / 4).floor
            if (run % 2 == 0) { // switches color directions with each iteration of while loop
                colorComp = 0
            } else {
                colorComp = 255
                colorGap = -colorGap
            }
            var ystart = columnHeight * run
            var xstart = 0
            for (i in 0...columnCount) {
                var iColor = Math.round(colorComp)
                var nextColor = Color.rgb(iColor, iColor, iColor)
                Canvas.rectfill(xstart, ystart, xstart + columnWidth, ystart + columnHeight, nextColor)
                xstart = xstart + columnWidth
	            colorComp = colorComp + colorGap
	        }
            run = run + 1
            columnCount = columnCount * 2
        }
    }

    update() {}

    draw(alpha) {}
}

var Game = GreyBars.new(640, 320)


include c:\cxpl\codes;          \intrinsic 'code' declarations
int Q, N, W, B, C, Y;
[SetVid($112);                  \640x480x24 graphics
for Q:= 0 to 4-1 do             \quarter of screen
    [N:= 8<<Q;                  \number of bars
    W:= 640/N;                  \width of bar (pixels)
    for B:= 0 to N-1 do         \for each bar...
        [C:= fix(255.0/float(N-1) * float(if Q&1 then N-1-B else B));
        C:= C<<16 + C<<8 + C;   \RGB color = gray
        for Y:= Q*120 to (Q+1)*120-1 do
                [Move(W*B, Y);  Line(W*(B+1)-1, Y, C)];
        ];
    ];
Q:= ChIn(1);                    \wait for keystroke
SetVid(3);                      \restore normal text mode
]


open window 1024, 600
w = peek("winwidth")
h = peek("winheight")
rows = 4
hd = int(h / rows)
mitad = 0

for row = 1 to rows
  if not mitad then
     wd = int(w / (8 * row))
     mitad = wd
  else
     mitad = mitad / 2
  end if
  c = 255 / (w / mitad)
  for n = 0 to (w / mitad)
     color 255 - c * n, 255 - c * n, 255 - c * n
     if mod(row, 2) = 0 color c * n, c * n, c * n
     fill rectangle mitad * n, hd * (row - 1), mitad * (n+1), hd * row
     pause .1
  next n
next row


img:=PPM(640,480);
foreach q in ([0..3]){		//quarter of screen
   n:=(8).shiftLeft(q);         //number of bars
   w:=640/n;			//width of bar (pixels)
   foreach b in ([0..n-1]){	//for each bar...
      c:=(255.0/(n-1).toFloat() * (if(q.isOdd) n-1-b else b)).toInt();
      c:=c.shiftLeft(16) + c.shiftLeft(8) + c;   //RGB color = gray
      foreach y in ([(3-q)*120 .. (3-q+1)*120-1]){  // flip image vertically
         img.line(w*b,y, w*(b+1)-1,y, c);
      }
   }
}
img.write(File("foo.ppm","wb"));


10 REM wind the colour down or use a black and white television to see greyscale bars
20 REM The ZX Spectrum display is 32 columns wide, so we have 8 columns of 4 spaces
25 BORDER 0: CLS
30 FOR r=0 TO 21: REM There are 22 rows
40 FOR c=0 TO 7: REM We use the native colour sequence here
50 PRINT PAPER c;"    ";: REM four spaces, the semicolon prevents newline
60 NEXT c
70 REM at this point the cursor has wrapped, so we don't need a newline
80 NEXT r


V t = random:(1..10)
V g = Int(input(‘Guess a number that's between 1 and 10: ’))
L t != g
   g = Int(input(‘Guess again! ’))
print(‘That's right!’)


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program guessNumber.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE,          100

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessNum: .asciz "I'm thinking of a number between 1 and 10. \n Try to guess it:\n"

szMessError:            .asciz "That's not my number. Try another guess:\n"
szMessSucces:           .asciz "Correct.\n"

szCarriageReturn:       .asciz "\n"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
sBuffer:              .skip BUFFERSIZE
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:
    mov x0,1
    mov x1,10
    bl extRandom                                // generate random number
    mov x5,x0

    ldr x0,qAdrszMessNum
    bl affichageMess
loop:
    mov x0,#STDIN                               // Linux input console
    ldr x1,qAdrsBuffer                          // buffer address
    mov x2,#BUFFERSIZE                          // buffer size
    mov x8,#READ                                // request to read datas
    svc 0                                       // call system
    ldr x1,qAdrsBuffer                          // buffer address
    mov x2,#0                                   // end of string
    sub x0,x0,#1                                // replace character 0xA
    strb w2,[x1,x0]                             // store byte at the end of input string (x0 contains number of characters)
    ldr x0,qAdrsBuffer
    bl conversionAtoD                           // call routine conversion ascii to décimal
    cmp x0,x5
    beq 1f
    ldr x0,qAdrszMessError                      // not Ok
    bl affichageMess
    b loop
1:
    ldr x0,qAdrszMessSucces                     // ok
    bl affichageMess

100:                                            // standard end of the program
    mov x0, #0                                  // return code
    mov x8, #EXIT                               // request to exit program
    svc 0                                       // perform system call
qAdrszMessNum:            .quad szMessNum
qAdrszMessError:          .quad szMessError
qAdrszMessSucces:         .quad szMessSucces

qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrsBuffer:              .quad sBuffer
/******************************************************************/
/*     random number                                          */
/******************************************************************/
/*  x0 contains inferior value */
/*  x1 contains maxi value */
/*  x0 return random number */
extRandom:
    stp x1,lr,[sp,-16]!        // save  registers
    stp x2,x8,[sp,-16]!        // save  registers
    stp x19,x20,[sp,-16]!      // save  registers
    sub sp,sp,16               // reserve 16 octets on stack
    mov x19,x0
    add x20,x1,1
    mov x0,sp                  // store result on stack
    mov x1,8                   // length 8 bytes
    mov x2,0
    mov x8,278                 //  call system Linux 64 bits Urandom
    svc 0
    mov x0,sp                  // load résult on stack
    ldr x0,[x0]
    sub x2,x20,x19             // calculation of the range of values
    udiv x1,x0,x2              // calculation range modulo
    msub x0,x1,x2,x0
    add  x0,x0,x19             // and add inferior value
100:
    add sp,sp,16               // alignement stack
    ldp x19,x20,[sp],16        // restaur  2 registers
    ldp x2,x8,[sp],16          // restaur  2 registers
    ldp x1,lr,[sp],16          // restaur  2 registers
    ret                        // retour adresse lr x30

/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


REPORT guess_the_number.

DATA prng TYPE REF TO cl_abap_random_int.

cl_abap_random_int=>create(
  EXPORTING
    seed = cl_abap_random=>seed( )
    min  = 1
    max  = 10
  RECEIVING
    prng = prng ).

DATA(number) = prng->get_next( ).

DATA(field) = VALUE i( ).

cl_demo_input=>add_field( EXPORTING text = |Choice one number between 1 and 10| CHANGING field = field ).
cl_demo_input=>request( ).

WHILE number <> field.
  cl_demo_input=>add_field( EXPORTING text = |You miss, try again| CHANGING field = field ).
  cl_demo_input=>request( ).
ENDWHILE.

cl_demo_output=>display( |Well Done| ).


PROC Main()
  BYTE x,n,min=[1],max=[10]

  PrintF("Try to guess a number %B-%B: ",min,max)
  x=Rand(max-min+1)+min
  DO
    n=InputB()
    IF n=x THEN
      PrintE("Well guessed!")
      EXIT
    ELSE
      Print("Incorrect. Try again: ")
    FI
  OD
RETURN


with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
procedure Guess_Number is
   subtype Number is Integer range 1 .. 10;
   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 : Number;
begin
   Number_RNG.Reset (Generator);
   My_Number := Number_RNG.Random (Generator);
   Ada.Text_IO.Put_Line ("Guess my number!");
   loop
      Ada.Text_IO.Put ("Your guess: ");
      Number_IO.Get (Your_Guess);
      exit when Your_Guess = My_Number;
      Ada.Text_IO.Put_Line ("Wrong, try again!");
   end loop;
   Ada.Text_IO.Put_Line ("Well guessed!");
end Guess_Number;

-------------------------------------------------------------------------------------------------------
-- Another version ------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Numerics.Discrete_Random;

-- procedure main - begins program execution
procedure main is
guess : Integer := 0;
counter : Integer := 0;
theNumber : Integer := 0;

-- function generate number - creates and returns a random number between the
-- ranges of 1 to 100
function generateNumber return Integer is
   type randNum is new Integer range 1 .. 100;
   package Rand_Int is new Ada.Numerics.Discrete_Random(randNum);
   use Rand_Int;
   gen : Generator;
   numb : randNum;

begin
   Reset(gen);

   numb := Random(gen);

   return Integer(numb);
end generateNumber;

-- procedure intro - prints text welcoming the player to the game
procedure intro is
begin
   Put_Line("Welcome to Guess the Number");
   Put_Line("===========================");
   New_Line;

   Put_Line("Try to guess the number. It is in the range of 1 to 100.");
   Put_Line("Can you guess it in the least amount of tries possible?");
   New_Line;
end intro;

begin
   New_Line;

   intro;
   theNumber := generateNumber;

   -- main game loop
   while guess /= theNumber loop
      Put("Enter a guess: ");
      guess := integer'value(Get_Line);

      counter := counter + 1;

      if guess > theNumber then
         Put_Line("Too high!");
      elsif guess < theNumber then
         Put_Line("Too low!");
      end if;
   end loop;

   New_Line;

   Put_Line("CONGRATULATIONS! You guessed it!");
   Put_Line("It took you a total of " & integer'image(counter) & " attempts.");

   New_Line;
end main;


file f;
integer n;
text s;

f.stdin;

n = irand(1, 10);
o_text("I'm thinking of a number between 1 and 10.\n");
o_text("Try to guess it!\n");
while (1) {
    f_look(f, "0123456789");
    f_near(f, "0123456789", s);
    if (atoi(s) != n) {
	o_text("That's not my number.\n");
	o_text("Try another guess!\n");
    } else {
	break;
    }
}

o_text("You have won!\n");


main:
(
    INT n;
    INT g;
    n := ENTIER (random*10+1);
    PROC puts = (STRING string)VOID: putf(standout, ($gl$,string));
    puts("I'm thinking of a number between 1 and 10.");
    puts("Try to guess it! ");
    DO
        readf(($g$, g));
        IF g = n THEN break
        ELSE
          puts("That's not my number. ");
          puts("Try another guess!")
        FI
    OD;
    break:
    puts("You have won! ")
)


on run
    -- define the number to be guessed
    set numberToGuess to (random number from 1 to 10)
    -- prepare a variable to store the user's answer
    set guessedNumber to missing value
    -- start a loop (will be exited by using "exit repeat" after a correct guess)
    repeat
        try
            -- ask the user for his/her guess
            set usersChoice to (text returned of (display dialog "Guess the number between 1 and 10 inclusive" default answer "" buttons {"Check"} default button "Check"))
            -- try to convert the given answer to an integer
            set guessedNumber to usersChoice as integer
        on error
            -- something gone wrong, overwrite user's answer with a non-matching value
            set guessedNumber to missing value
        end try
        -- decide if the user's answer was the right one
        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
    end repeat
end run


n: random 1 10

while [notEqual? to :integer input "Guess the number: " n] [
	print "Wrong!"
]

print "Well guessed!"


Random, rand, 1, 10  ; This stores a number between 1 and 10 in the var rand using the Mersenne Twister
msgbox I am thinking of a number between 1 and 10.

loop
{
	InputBox, guess, Guess the number, Type in a number from 1 to 10
		If (guess = rand)
		{
			msgbox Well Guessed!
			Break ; exits loop
		}
		Else
			Msgbox Try again.
}


$irnd = Random(1, 10, 1)
$iinput = -1
While $input <> $irnd
	$iinput = InputBox("Choose a number", "Please chosse a Number between 1 and 10")
WEnd
MsgBox(0, "Success", "Well guessed!")


# syntax: GAWK -f GUESS_THE_NUMBER.AWK
BEGIN {
    srand()
    n = int(rand() * 10) + 1
    print("I am thinking of a number between 1 and 10. Try to guess it.")
    while (1) {
      getline ans
      if (ans !~ /^[0-9]+$/) {
        print("Your input was not a number. Try again.")
        continue
      }
      if (n == ans) {
        print("Well done you.")
        break
      }
      print("Incorrect. Try again.")
    }
    exit(0)
}


10 N% = RND(1) * 10 + 1
20 PRINT "A NUMBER FROM 1 ";
30 PRINT "TO 10 HAS BEEN ";
40 PRINT "RANDOMLY CHOSEN."
50 FOR Q = 0 TO 1 STEP 0
60     INPUT "ENTER A GUESS. "; G%
70     Q = G% = N%
80 NEXT
90 PRINT "WELL GUESSED!"


n = int(rand * 10) + 1
print "I am thinking of a number from 1 to 10"
do
   input "Guess it > ",g
   if g <> n then
      print "No luck,  Try again."
   endif
until g = n
print "Yea! You guessed my number."


@echo off
set /a answer=%random%%%(10-1+1)+1
set /p guess=Pick a number between 1 and 10:
:loop
if %guess%==%answer% (echo Well guessed!
pause) else (set /p guess=Nope, guess again:
goto loop)


      choose% = RND(10)
      REPEAT
        INPUT "Guess a number between 1 and 10: " guess%
        IF guess% = choose% THEN
          PRINT "Well guessed!"
          END
        ELSE
          PRINT "Sorry, try again"
        ENDIF
      UNTIL FALSE


( ( GuessTheNumber
  =   mynumber
    .   clk$:?mynumber
      & mod$(!mynumber*den$!mynumber.10)+1:?mynumber
      &   whl
        ' ( put'"Guess my number:"
          & get':~!mynumber:?K
          )
      & out'"Well guessed!"
  )
& GuessTheNumber$
);


number = random 10

p "Guess a number between 1 and 10."

until {
  true? ask("Guess: ").to_i == number
    { p "Well guessed!"; true }
    { p "Guess again!" }
}


#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main(void)
{
    int n;
    int g;
    char c;

    srand(time(NULL));
    n = 1 + (rand() % 10);

    puts("I'm thinking of a number between 1 and 10.");
    puts("Try to guess it:");

    while (1) {
        if (scanf("%d", &g) != 1) {
		/* ignore one char, in case user gave a non-number */
		scanf("%c", &c);
		continue;
	}

        if (g == n) {
	    puts("Correct!");
	    return 0;
	}
        puts("That's not my number. Try another guess:");
    }
}


using System;

class GuessTheNumberGame
{
    static void Main()
    {
        int randomNumber = new Random().Next(1, 11);

        Console.WriteLine("I'm thinking of a number between 1 and 10. Can you guess it?");
        while(true)
        {
            Console.Write("Guess: ");
            if (int.Parse(Console.ReadLine()) == randomNumber)
                break;
            Console.WriteLine("That's not it. Guess again.");
        }
        Console.WriteLine("Congrats!! You guessed right!");
    }
};


#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
    srand(time(0));
    int n = 1 + (rand() % 10);
    int g;
    std::cout << "I'm thinking of a number between 1 and 10.\nTry to guess it! ";
    while(true)
    {
        std::cin >> g;
        if (g == n)
            break;
        else
            std::cout << "That's not my number.\nTry another guess! ";
    }
    std::cout << "You've guessed my number!";
    return 0;
}


(def target (inc (rand-int 10))

(loop [n 0]
   (println "Guess a number between 1 and 10 until you get it right:")
   (let [guess (read)]
	(if (= guess target)
	    (printf "Correct on the %d guess.\n" n)
	    (do
	     (println "Try again")
	     (recur (inc n))))))


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Guess-The-Number.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  Random-Num PIC 99.
       01  Guess      PIC 99.

       PROCEDURE DIVISION.
           COMPUTE Random-Num = 1 + (FUNCTION RANDOM * 10)
           DISPLAY "Guess a number between 1 and 10:"

           PERFORM FOREVER
               ACCEPT Guess

               IF Guess = Random-Num
                   DISPLAY "Well guessed!"
                   EXIT PERFORM
               ELSE
                   DISPLAY "That isn't it. Try again."
               END-IF
           END-PERFORM

           GOBACK
           .


num = Math.ceil(Math.random() * 10)
guess = prompt "Guess the number. (1-10)"
while parseInt(guess) isnt num
  guess = prompt "YOU LOSE! Guess again. (1-10)"
alert "Well guessed!"


(defun guess-the-number (max)
  (format t "Try to guess a number from 1 to ~a!~%Guess? " max)
  (loop with num = (1+ (random max))
        for guess = (read)
        as num-guesses from 1
        until (and (numberp guess) (= guess num))
        do (format t "Your guess was wrong.  Try again.~%Guess? ")
           (force-output)
        finally (format t "Well guessed! You took ~a ~:*~[~;try~:;tries~].~%" num-guesses)))


n = rand(1..10)
puts "Guess the number: 1..10"
until gets.to_s.to_i == n; puts "Wrong! Guess again: " end
puts "Well guessed!"


void main() {
    immutable num = uniform(1, 10).text;

    do write("What's next guess (1 - 9)? ");
    while (readln.strip != num);

    writeln("Yep, you guessed my ", num);
}


import 'dart:math';
import 'dart:io';

main() {
  final n = (1 + new Random().nextInt(10)).toString();
  print("Guess which number I've chosen in the range 1 to 10");
  do { stdout.write(" Your guess : "); } while (n != stdin.readLineSync());
  print("\nWell guessed!");
}


$ time = f$time()
$ number = f$extract( f$length( time ) - 1, 1, time ) + 1
$ loop:
$  inquire guess "enter a guess (integer 1-10) "
$  if guess .nes. number then $ goto loop
$ write sys$output "Well guessed!"


program GuessTheNumber;

{$APPTYPE CONSOLE}

uses SysUtils;

var
  theDigit : String ;
  theAnswer : String ;

begin
  Randomize ;
  theDigit := IntToStr(Random(9)+1) ;
  while ( theAnswer <> theDigit ) do Begin
    Writeln('Please enter a digit between 1 and 10' ) ;
    Readln(theAnswer);
  End ;
  Writeln('Congratulations' ) ;
end.


local :number random-range 1 11

while true:
	if = number to-num !prompt "Guess my number: ":
		!print "Congratulations, you've guessed it!"
		return
	else:
		!print "Nope, try again."


n = random 10 + 1
write "Guess a number between 1 and 10: "
repeat
  g = number input
  write g
  until g = n
  print " is wrong"
  write "try again: "
.
print " is correct. Well guessed!"


class
	APPLICATION

create
	make

feature {NONE} -- Initialization

	make
		local
			number_to_guess: INTEGER
		do
			number_to_guess := (create {RANDOMIZER}).random_integer_in_range (1 |..| 10)
			from
				print ("Please guess the number!%N")
				io.read_integer
			until
				io.last_integer = number_to_guess
			loop
				print ("Please, guess again!%N")
				io.read_integer
			end
			print ("Well guessed!%N")
		end

end


import extensions;

public program()
{
    int randomNumber := randomGenerator.eval(1,10);
    console.printLine("I'm thinking of a number between 1 and 10.  Can you guess it?");
    bool numberCorrect := false;
    until(numberCorrect)
    {
        console.print("Guess: ");
        int userGuess := console.readLine().toInt();
        if (randomNumber == userGuess)
        {
            numberCorrect := true;
            console.printLine("Congrats!!  You guessed right!")
        }
        else
        {
            console.printLine("That's not it.  Guess again.")
        }
    }
}


defmodule GuessingGame do
  def play do
    play(Enum.random(1..10))
  end

  defp play(number) do
    guess = Integer.parse(IO.gets "Guess a number (1-10): ")
    case guess do
      {^number, _} ->
        IO.puts "Well guessed!"
      {n, _} when n in 1..10 ->
        IO.puts "That's not it."
        play(number)
      _ ->
        IO.puts "Guess not in valid range."
        play(number)
    end
  end
end

GuessingGame.play


(let ((number (1+ (random 10))))
  (while (not (= (read-number "Guess the number ") number))
    (message "Wrong, try again."))
  (message "Well guessed! %d" number))


% Implemented by Arjun Sunel
-module(guess_the_number).
-export([main/0]).

main() ->
	io:format("Guess my number between 1 and 10 until you get it right:\n"),
	N = random:uniform(10),
	guess(N).

guess(N) ->
	{ok, [K]} = io:fread("Guess number :  ","~d"),

	if
		K=:=N ->
			io:format("Well guessed!!\n");
		true ->
			guess(N)
	end.


PROGRAM GUESS_NUMBER

!
! for rosettacode.org
!

BEGIN

  RANDOMIZE(TIMER)
  N=0
  R=INT(RND(1)*100+1)  ! RND function gives a random number from 0 to 1
  G=0
  C$=""

  WHILE G<>R DO
    INPUT("Pick a number between 1 and 100";G)
    IF G=R THEN
        PRINT("You got it!")
        N+=1
        PRINT("It took";N;"tries to pick the right Number.")
    ELSIF G<R THEN
        PRINT("Try a larger number.")
        N+=1
    ELSE
        PRINT("Try a smaller number.")
        N+=1
    END IF
  END WHILE
END PROGRAM


include get.e

integer n,g
n = rand(10)

puts(1,"I have thought of a number from 1 to 10.\n")
puts(1,"Try to guess it!\n")

while 1 do
    g = prompt_number("Enter your guess: ",{1,10})
    if n = g then
        exit
    end if
    puts(1,"Your guess was wrong. Try again!\n")
end while

puts(1,"Well done! You guessed it.")


USING: io random math math.parser kernel formatting ;
IN: guess-the-number

<PRIVATE

: gen-number ( -- n )
  10 random 1 + ;

: make-guess ( n -- n ? )
  dup readln string>number = ;

: play-game ( n -- n )
  [ make-guess ]
  [ "Guess a number between 1 and 10:" print flush ] do until ;

PRIVATE>

: guess-the-number ( -- )
  gen-number play-game
  "Yes, the number was %d!\n" printf ;


class Main
{
  public static Void main ()
  {
    Str target := (1..10).random.toStr
    Str guess := ""
    while (guess != target)
    {
      echo ("Enter a guess: ")
      guess = Env.cur.in.readLine
      if (guess.trim == target) // 'trim' to remove any spaces/newline
      {
        echo ("Well guessed!")
        break
      }
      else
        echo ("Failed - try again")
    }
  }
}


\ tested with GForth  0.7.0
: RND    ( -- n) TIME&DATE 2DROP 2DROP DROP 10 MOD ;         \ crude random number
: ASK    ( -- ) CR ." Guess a number between 1 and 10? " ;
: GUESS  ( -- n)  PAD DUP 4 ACCEPT EVALUATE ;
: REPLY  ( n n' -- n)  2DUP <> IF CR ." No, it's not " DUP . THEN ;

: GAME ( -- )
          RND
          BEGIN   ASK GUESS REPLY  OVER =  UNTIL
          CR ." Yes it was " .
          CR ." Good guess!"  ;


program guess_the_number
 implicit none

 integer                          :: guess
 real                             :: r
 integer                          :: i, clock, count, n
 integer,dimension(:),allocatable :: seed

 real,parameter :: rmax = 10

!initialize random number generator:
 call random_seed(size=n)
 allocate(seed(n))
 call system_clock(count)
 seed = count
 call random_seed(put=seed)
 deallocate(seed)

!pick a random number between 1 and rmax:
 call random_number(r)          !r between 0.0 and 1.0
 i = int((rmax-1.0)*r + 1.0)    !i between 1 and rmax

!get user guess:
 write(*,'(A)') 'I''m thinking of a number between 1 and 10.'
 do   !loop until guess is correct
	write(*,'(A)',advance='NO') 'Enter Guess: '
	read(*,'(I5)') guess
	if (guess==i) exit
	write(*,*) 'Sorry, try again.'
 end do

 write(*,*) 'You''ve guessed my number!'

end program guess_the_number


' FB 1.05.0 Win64

Randomize
Dim n As Integer = Int(Rnd * 10) + 1
Dim guess As Integer
Print "Guess which number I've chosen in the range 1 to 10"
Print
Do
  Input " Your guess : "; guess
  If n = guess Then
    Print "Well guessed!"
    End
  End If
Loop


// Guess a Number
target = random[1,10] // 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 10. 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 10."]
   else
      guess == target ? println["$guess is correct. Well guessed!"] : println["$guess is not correct. Guess again!"]
}


Public Sub Form_Open()
Dim byGuess, byGos As Byte
Dim byNo As Byte = Rand(1, 10)
Dim sHead As String = "Guess the number"

Repeat
  Inc byGos
  byGuess = InputBox("Guess the number between 1 and 10", sHead)
  sHead = "Sorry, have another go"
Until byGuess = byNo

Message.Info("Well guessed! You took " & Str(byGos) & " gos to guess the number was " & Str(byNo), "OK")
Me.Close

End


var n, g;
n = irandom_range(1,10);
show_message("I'm thinking of a number from 1 to 10");
g = get_integer("Please enter guess", 1);
while(g != n)
    {
    g = get_integer("I'm sorry "+g+" is not my number, try again. Please enter guess", 1);
    }
show_message("Well guessed!");


package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    fmt.Print("Guess number from 1 to 10: ")
    rand.Seed(time.Now().Unix())
    n := rand.Intn(10) + 1
    for guess := n; ; fmt.Print("No. Try again: ") {
        switch _, err := fmt.Scan(&guess); {
        case err != nil:
            fmt.Println("\n", err, "\nSo, bye.")
            return
        case guess == n:
            fmt.Println("Well guessed!")
            return
        }
    }
}


def random = new Random()
def keyboard = new Scanner(System.in)
def number = random.nextInt(10) + 1
println "Guess the number which is between 1 and 10: "
def guess = keyboard.nextInt()
while (number != guess) {
    println "Guess again: "
    guess = keyboard.nextInt()
}
println "Hurray! You guessed correctly!"


10 RANDOMIZE TIMER:N=INT(RND*10+1):G=0
20 PRINT "Guess the number between 1 and 10."
30 WHILE N<>G
40 INPUT "Your guess? ",G
50 WEND
60 PRINT "That's correct!"


import Control.Monad
import System.Random

-- Repeat the action until the predicate is true.
until_ act pred = act >>= pred >>= flip unless (until_ act pred)

answerIs ans guess
    | ans == guess = putStrLn "You got it!" >> return True
    | otherwise = putStrLn "Nope. Guess again." >> return False

ask = liftM read getLine

main = do
  ans <- randomRIO (1,10) :: IO Int
  putStrLn "Try to guess my secret number between 1 and 10."
  ask `until_` answerIs ans


U8 n, *g;

n = 1 + RandU16 % 10;

Print("I'm thinking of a number between 1 and 10.\n");
Print("Try to guess it:\n");

while(1) {
  g = GetStr;

  if (Str2I64(g) == n) {
    Print("Correct!\n");
    break;
  }

  Print("That's not my number. Try another guess:\n");
}


procedure main()
    n := ?10
    repeat {
        writes("Pick a number from 1 through 10: ")
        if n = numeric(read()) then break
        }
    write("Well guessed!")
end


require 'misc'
game=: verb define
  n=: 1 + ?10
  smoutput 'Guess my integer, which is bounded by 1 and 10'
  whilst. -. guess -: n do.
    guess=. {. 0 ". prompt 'Guess: '
    if. 0 -: guess do. 'Giving up.' return. end.
    smoutput (guess=n){::'no.';'Well guessed!'
  end.
)


public class Guessing {
    public static void main(String[] args) throws NumberFormatException{
        int n = (int)(Math.random() * 10 + 1);
        System.out.print("Guess the number between 1 and 10: ");
        while(Integer.parseInt(System.console().readLine()) != n){
            System.out.print("Wrong! Guess again: ");
        }
        System.out.println("Well guessed!");
    }
}


function guessNumber() {
  // Get a random integer from 1 to 10 inclusive
  var num = Math.ceil(Math.random() * 10);
  var guess;

  while (guess != num) {
    guess = prompt('Guess the number between 1 and 10 inclusive');
  }
  alert('Congratulations!\nThe number was ' + num);
}

guessNumber();


{prompt: "Please enter your guess:", random: (1+rand(9)) }
| ( (while( .guess != .random; .guess = (input|tonumber) ) | .prompt),
  "Well done!"


function guessNumber() {
    // Get a random integer from 1 to 10 inclusive
    var num = Math.ceil(Math.random() * 10);
    var guess;
    var tries = 0;

    while (guess != num) {
        tries += 1;
        printf('%s', 'Guess the number between 1 and 10 inclusive: ');
        guess = console.input();
    }
    printf('Congratulations!\nThe number was %d   it took %d tries\n', num, tries);
}

if (Interp.conf('unitTest')) {
    // Set a predictable outcome
    Math.srand(0);
    guessNumber();
}

/*
=!INPUTSTART!=
5
9
2
=!INPUTEND!=
*/

/*
=!EXPECTSTART!=
Guess the number between 1 and 10 inclusive: Guess the number between 1 and 10 inclusive: Guess the number between 1 and 10 inclusive: Congratulations!
The number was 2   it took 3 tries
=!EXPECTEND!=
*/


function guess()
    number = dec(rand(1:10))
    print("Guess my number! ")
    while readline() != number
        print("Nope, try again... ")
    end
    println("Well guessed!")
end

guess()


// version 1.0.5-2

fun main(args: Array<String>) {
	val n = (1 + java.util.Random().nextInt(10)).toString()
	println("Guess which number I've chosen in the range 1 to 10\n")
	do { print(" Your guess : ") } while (n != readLine())
	println("\nWell guessed!")
}


writeln "Guess a number from 1 to 10"

val .n = toString random 10
for {
    val .guess = read ">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7, ZLS
    if .guess == ZLS {
        writeln "too much bad data"
        break
    }
    if .guess == .n {
        writeln "That's it."
        break
    }
    writeln "not it"
}


local(
	number	= integer_random(10, 1),
	status	= false,
	guess
)

// prompt for a number
stdout('Guess a number between 1 and 10: ')

while(not #status) => {
	#guess = null

	// the following bits wait until the terminal gives you back a line of input
	while(not #guess or #guess -> size == 0) => {
		#guess = file_stdin -> readSomeBytes(1024, 1000)
	}
	#guess = integer(#guess)

	if(not (range(#guess, 1, 10) == #guess)) => {
		stdout('Input not of correct type or range. Guess a number between 1 and 10: ')
	else(#guess == #number)
		stdout('Well guessed!')
		#status = true
	else
		stdout('You guessed wrong number. Guess a number between 1 and 10: ')
	}

}


(defmodule guessing-game
  (export (main 0)))

(defun get-player-guess ()
  (let (((tuple 'ok (list guessed)) (: io fread '"Guess number: " '"~d")))
    guessed))

(defun check-guess (answer guessed)
    (cond
      ((== answer guessed)
        (: io format '"Well-guessed!!~n"))
      ((/= answer guessed)
        (check-guess answer (get-player-guess)))))

(defun main ()
  (: io format '"Guess the number I have chosen, between 1 and 10.~n")
  (check-guess
    (: random uniform 10)
    (get-player-guess)))


number = int(rnd(0) * 10) + 1
input "Guess the number I'm thinking of between 1 and 10. "; guess
while guess <> number
    input "Incorrect! Try again! "; guess
wend
print "Congratulations, well guessed! The number was "; number;"."


command guessTheNumber
    local tNumber, tguess
    put random(10) into tNumber
    repeat until tguess is tNumber
        ask question "Please enter a number between 1 and 10" titled "Guess the number"
        if it is not empty then
            put it into tguess
            if tguess is tNumber then
                answer "Well guessed!"
            end if
        else
            exit repeat
        end if
    end repeat
end guessTheNumber


10 RANDOMIZE TIME:num=INT(RND*10+1):guess=0
20 PRINT "Guess the number between 1 and 10."
30 WHILE num<>guess
40 INPUT "Your guess? ", guess
50 WEND
60 PRINT "That's correct!"


HAI 1.3

VISIBLE "SEED ME, FEMUR! "!
I HAS A seed, GIMMEH seed

HOW IZ I randomizin
    seed R MOD OF SUM OF 1 AN PRODUKT OF 69069 AN seed AN 10
IF U SAY SO

I IZ randomizin MKAY
I HAS A answer ITZ SUM OF seed AN 1
I HAS A guess

IM IN YR guesser
    VISIBLE "WUTS MY NUMBR? "!
    GIMMEH guess, guess IS NOW A NUMBR

    BOTH SAEM guess AN answer, O RLY?
        YA RLY, VISIBLE "U WIN!", GTFO
    OIC
IM OUTTA YR guesser

KTHXBYE


math.randomseed( os.time() )
n = math.random( 1, 10 )

print( "I'm thinking of a number between 1 and 10. Try to guess it: " )

repeat
    x = tonumber( io.read() )

    if x == n then
	print "Well guessed!"
    else
	print "Guess again: "
    end
until x == n


Module QBASIC_Based {
      supervisor:
      GOSUB initialize
      GOSUB guessing
      GOTO continue

      initialize:
      \\ Not need to RANDOMIZE TIMER
      \\ we can use Random(1, 100) to get a number from 1 to 100
      n = 0: r = INT(RND * 100 + 1): g = 0: c$ = ""
      RETURN

      guessing:
      WHILE g <> r {
                INPUT "Pick a number between 1 and 100:"; g
                IF g = r THEN {
                    PRINT "You got it!"
                    n ++
                    PRINT "It took "; n; " tries to pick the right number."
                } ELSE.IF g < r THEN {
                    PRINT "Try a larger number."
                    n ++
                } ELSE {
                    PRINT "Try a smaller number."
                    n++
                }
      }
      RETURN

      continue:
      WHILE c$ <> "YES" AND c$ <> "NO" {
          INPUT "Do you want to continue? (YES/NO)"; c$
          c$ = UCASE$(c$)
          IF c$ = "YES" THEN {
              GOTO supervisor
          } ELSE.IF c$ = "NO" THEN {
              Goto End
          }
      }
      End:
}
QBASIC_Based


GuessNumber := proc()
    local number;
    randomize():
    printf("Guess a number between 1 and 10 until you get it right:\n:");
    number := rand(1..10)();
    while parse(readline()) <> number do
        printf("Try again!\n:");
    end do:
    printf("Well guessed! The answer was %d.\n", number);
end proc:


number = RandomInteger[{1, 10}];
While[guess =!= number, guess = Input["Guess my number"]];
Print["Well guessed!"]


number = ceil(10*rand(1));
[guess, status] = str2num(input('Guess a number between 1 and 10: ','s'));

while (~status || guess ~= number)
    [guess, status] = str2num(input('Guess again: ','s'));
end
disp('Well guessed!')


rand = random 1 10
clearListener()
while true do
(
	userval = getKBValue prompt:"Enter an integer between 1 and 10: "
	if userval == rand do (format "\nWell guessed!\n"; exit)
	format "\nChoose another value\n"
)


:- module guess.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module random, string.

main(!IO) :-
        time(Time, !IO),
        random.init(Time, Rand),
        random.random(1, 10, N, Rand, _),
        main(from_int(N) ++ "\n", !IO).

:- pred main(string::in, io::di, io::uo) is det.
main(N, !IO) :-
        io.write_string("Guess the number: ", !IO),
        io.read_line_as_string(Res, !IO),
        (
                Res = ok(S),
                ( if S = N then io.write_string("Well guessed!\n", !IO)
                  else main(N, !IO) )
        ;
                Res = error(E)
        ;
                Res = eof
        ).

:- pred time(int::out, io::di, io::uo) is det.

:- pragma foreign_decl("C", "#include <time.h>").
:- pragma foreign_proc("C", time(Int::out, _IO0::di, _IO1::uo),
                       [will_not_call_mercury, promise_pure],
                       "Int = time(NULL);").


randomize

9 random succ

"Guess my number between 1 and 10." puts!

("Your guess" ask int over ==) 'pop ("Wrong." puts!) () linrec

"Well guessed!" puts!


num = ceil(rnd*10)
while true
    x = val(input("Your guess?"))
    if x == num then
        print "Well guessed!"
        break
    end if
end while


# WRITTEN: August 26, 2016 (at midnight...)

# This targets MARS implementation and may not work on other implementations
# Specifically, using MARS' random syscall
.data
	take_a_guess: .asciiz "Make a guess:"
	good_job: .asciiz "Well guessed!"

.text
	#retrieve system time as a seed
	li $v0,30
	syscall

	#use the high order time stored in $a1 as the seed arg
	move $a1,$a0

	#set the seed
	li $v0,40
	syscall

	#generate number 0-9 (random int syscall generates a number where):
	# 0 <= $v0 <= $a1
	li $a1,10
	li $v0,42
	syscall

	#increment the randomly generated number and store in $v1
	add $v1,$a0,1

loop:	jal print_take_a_guess
	jal read_int

	#go back to beginning of loop if user hasn't guessed right,
	#    else, just "fall through" to exit_procedure
	bne $v0,$v1,loop

exit_procedure:
	#set syscall to print_string, then set good_job string as arg
	li $v0,4
	la $a0,good_job
	syscall

	#exit program
	li $v0,10
	syscall

print_take_a_guess:
	li $v0,4
	la $a0,take_a_guess
	syscall
	jr $ra

read_int:
	li $v0,5
	syscall
	jr $ra


random = new(Nanoquery.Util.Random)
target = random.getInt(9) + 1
guess = 0

println "Guess a number between 1 and 10."
while not target = guess
	guess = int(input())
end

println "That's right!"


using System;
using System.Console;

module Guess
{
    Main() : void
    {
        def rand = Random();
        def x = rand.Next(1, 11);  // returns 1 <= x < 11
        mutable guess = 0;

        do
        {
            WriteLine("Guess a nnumber between 1 and 10:");
            guess = Int32.Parse(ReadLine());
        } while (guess != x);

        WriteLine("Well guessed!");
    }
}


/* NetRexx */

options replace format comments java crossref savelog symbols nobinary

guessThis = (Math.random * 10 + 1) % 1
guess = -1
prompt = [ -
  'Try guessing a number between 1 and 10', -
  'Wrong; try again...' -
  ]
promptIdx = int 0

loop label g_ until guess = guessThis
  say prompt[promptIdx]
  promptIdx = 1
  parse ask guess .
  if guess = guessThis then do
    say 'Well guessed!' guess 'is the correct number.'
    leave g_
    end
  end g_

return


; guess-number.lsp
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Guess_the_number

(seed (time-of-day)) ; Initialize random number generator from clock.
(setq number (+ 1 (rand 10)))

(println "I'm thinking of a number between 1 and 10. Can you guess it?")
(print   "Type in your guess and hit [enter]: ")
(while (!= number (int (read-line))) (print "Nope! Try again: "))
(println "Well guessed! Congratulations!")

(exit)


import strutils, random

randomize()
var chosen = rand(1..10)
echo "I have thought of a number. Try to guess it!"

var guess = parseInt(readLine(stdin))

while guess != chosen:
  echo "Your guess was wrong. Try again!"
  guess = parseInt(readLine(stdin))

echo "Well guessed!"


10 NUMBER=RND(10)+1
20 INPUT "I'M THINKING OF A NUMBER BETWEEN 1 AND 10. WHAT IS IT? ",GUESS
30 IF GUESS<>NUMBER THEN PRINT "INCORRECT GUESS. TRY AGAIN.": GOTO 20
40 PRINT "CORRECT NUMBER."


MODULE GuessTheNumber;
IMPORT
  RandomNumbers,
  In,
  Out;

  PROCEDURE Do;
  VAR
    n,guess: LONGINT;
  BEGIN
    n := RandomNumbers.RND(10);
    Out.String("Guess a number between 1 and 10: ");Out.Flush();
    LOOP
      In.LongInt(guess);
      IF  guess = n THEN
        Out.String("You guessed!!"); Out.Ln; EXIT
      END;
      Out.String(" Sorry, try again: ");Out.Flush()
    END
  END Do;

BEGIN
  Do;
END GuessTheNumber.


use IO;

bundle Default {
  class GuessNumber {
    function : Main(args : String[]) ~ Nil {
      done := false;
      "Guess the number which is between 1 and 10 or 'q' to quite: "->PrintLine();
      rand_num := (Float->Random() * 10.0)->As(Int) + 1;
      while(done = false) {
        guess := Console->ReadString();
        number := guess->ToInt();
        if(number <> 0) {
          if(number <> rand_num) {
            "Guess again: "->PrintLine();
          }
          else {
            "Hurray! You guessed correctly!"->PrintLine();
            done := true;
          };
        }
        else {
          if(guess->StartsWith("q") | guess->StartsWith("Q")) {
            done := true;
          };
        };
      };
    }
  }
}


#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSLog(@"I'm thinking of a number between 1 - 10. Can you guess what it is?\n");

        int rndNumber = arc4random_uniform(10) + 1;

        // Debug (Show rndNumber in console)
        //NSLog(@"Random number is %i", rndNumber);

        int userInput;

        do {

            NSLog(@"Input the number below\n");
            scanf("%i", &userInput);

            if (userInput > 10) {

                NSLog(@"Please enter a number less than 10\n");
            }

            if (userInput > 10 || userInput != rndNumber) {

                NSLog(@"Your guess %i is incorrect, please try again", userInput);

            } else {

                NSLog(@"Your guess %i is correct!", userInput);
            }

        } while (userInput > 10 || userInput != rndNumber);
    }
    return 0;
}


#!/usr/bin/env ocaml

let () =
  Random.self_init();
  let n =
    if Random.bool () then
      let n = 2 + Random.int 8 in
      print_endline "Please guess a number between 1 and 10 excluded";
      (n)
    else
      let n = 1 + Random.int 10 in
      print_endline "Please guess a number between 1 and 10 included";
      (n)
  in
  while read_int () <> n do
    print_endline "The guess was wrong! Please try again!"
  done;
  print_endline "Well guessed!"


import: console

: guess
   10 rand doWhile: [ "Guess :" . System.Console askln asInteger over <> ]
   drop "Well guessed!" . ;


(import (otus random!))

(define number (+ 1 (rand! 10)))
(let loop ()
   (display "Pick a number from 1 through 10: ")
   (if (eq? (read) number)
      (print "Well guessed!")
      (loop)))


Program GuessTheNumber(input, output);

var
  number, guess: integer;

begin
  randomize;
  number := random(10) + 1;
  writeln ('I''m thinking of a number between 1 and 10, which you should guess.');
  write   ('Enter your guess: ');
  readln  (guess);
  while guess <> number do
  begin
    writeln ('Sorry, but your guess is wrong. Please try again.');
    write   ('Enter your new guess: ');
    readln  (guess);
  end;
  writeln ('You made an excellent guess. Thank you and have a nice day.');
end.


my $number = 1 + int rand 10;
do { print "Guess a number between 1 and 10: " } until <> == $number;
print "You got it!\n";


--
-- demo\rosetta\Guess_the_number.exw
--
with javascript_semantics
include pGUI.e

integer secret = rand(10)

function valuechanged_cb(Ihandle guess)
    integer n = IupGetInt(guess,"VALUE")
    if n=secret then
        Ihandle lbl = IupGetBrother(guess,true)
        IupSetAttribute(lbl,"TITLE","Your guess was correct")
        IupRefresh(lbl)
        IupSetInt(guess,"ACTIVE",false)
    end if
    return IUP_DEFAULT
end function

procedure main()
    IupOpen()
    Ihandle lbl = IupLabel("Your guess","RASTERSIZE=58x21"),
            guess = IupText("VALUECHANGED_CB", Icallback("valuechanged_cb"),
                            "RASTERSIZE=21x21"),
            dlg = IupDialog(IupVbox({IupFill(),
                            IupHbox({IupFill(),lbl,guess,IupFill()},
                                    "GAP=10"),
                            IupFill()}),
                            `MINSIZE=300x100,TITLE="Guess the number"`)
    IupShow(dlg)
    IupSetAttribute(lbl,"RASTERSIZE","x21")
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

main()


<?php

session_start();

if(isset($_SESSION['number']))
{
   $number = $_SESSION['number'];
}
else
{
   $_SESSION['number'] = rand(1,10);
}

if(isset($_POST["guess"])){
	if($_POST["guess"]){
	    $guess  = htmlspecialchars($_POST['guess']);

		echo $guess . "
";
	    if ($guess != $number)
		{
	        echo "Your guess is not correct";
	    }
		elseif($guess == $number)
		{
	        echo "You got the correct number!";
	    }
	}
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Guess A Number</title>

		<form action="<?=$_SERVER['PHP_SELF'] ?>" method="post" name="guess-a-number">
		    Guess number:

		    <input type="text" name="guess" />
		    <input name="number" type="hidden" value="<?= $number ?>" />
		    <input name="submit" type="submit" />
		</form>


go =>
  N = random(1,10),
  do print("Guess a number: ")
  while (read_int() != N),
  println("Well guessed!").


(de guessTheNumber ()
   (let Number (rand 1 9)
      (loop
         (prin "Guess the number: ")
         (T (= Number (read))
            (prinl "Well guessed!") )
         (prinl "Sorry, this was wrong") ) ) )


To run:
Start up.
Play guess the number.
Wait for the escape key.
Shut down.

To play guess the number:
Pick a secret number between 1 and 10.
Write "I picked a secret number between 1 and 10." to the console.
Loop.
Write "What is your guess? " to the console without advancing.
Read a number from the console.
If the number is the secret number, break.
Repeat.
Write "Well guessed!" to the console.


\newlinechar`\^^J
\edef\tagetnumber{\number\numexpr1+\pdfuniformdeviate9}%
\message{^^JI'm thinking of a number between 1 and 10, try to guess it!}%
\newif\ifnotguessed
\notguessedtrue
\loop
	\message{^^J^^JYour try: }\read -1 to \useranswer
	\ifnum\useranswer=\tagetnumber\relax
		\message{You win!^^J}\notguessedfalse
	\else
		\message{No, it's another number, try again...}%
	\fi
	\ifnotguessed
\repeat
\bye


Function GuessNumber($Guess)
{
    $Number = Get-Random -min 1 -max 11
    Write-Host "What number between 1 and 10 am I thinking of?"
        Do
        {
        Write-Warning "Try again!"
        $Guess = Read-Host "What's the number?"
        }
        While ($Number -ne $Guess)
    Write-Host "Well done! You successfully guessed the number $Guess."
}


:a
editvar /modify /value=-random-= <10
editvar /newvar /value=-random- /title=a
editvar /newvar /value=b /userinput=1 /title=Guess a number:
if -b- /hasvalue=-a- printline You guessed correctly! else printline Your guess was wrong & goto :a


main :-
    random_between(1, 10, N),
    repeat,
    prompt1('Guess the number: '),
    read(N),
    writeln('Well guessed!'),
    !.


If OpenConsole()
  Define TheNumber=Random(9)+1

  PrintN("I've picked a number from 1 to 10." + #CRLF$)
  Repeat
    Print("Guess the number: ")
  Until TheNumber=Val(Input())

  PrintN("Well guessed!")

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf


import random
t,g=random.randint(1,10),0
g=int(input("Guess a number that's between 1 and 10: "))
while t!=g:g=int(input("Guess again! "))
print("That's right!")


START:
CLS
RANDOMIZE TIMER
num = INT(RND * 10) + 1
DO
    INPUT "Enter a number between 1 and 10: ", n
    IF n = num THEN EXIT DO
    PRINT "Nope."
LOOP UNTIL n = num
INPUT "Well guessed! Go again"; a$
IF LEFT$(LCASE$(a$), 1) = "y" THEN GOTO START


'Task
'Plus features:  1) AI gives suggestions about your guess
' 2) AI controls wrong input by user (numbers outer  1   and   10).
' 3) player can choose to replay the game

Randomize Timer
Dim As Integer Done, Guess, Number

Done = 1
Guess = 0
While Done
    Cls
    Number = Rnd * 10 + 1
    Do While Number <> Guess
        Cls
        Locate 2, 1
        Input "What number have I thought? (1-10)", Guess
        If Guess > 0 And Guess < 11 Then
            If Guess = Number Then
                Locate 4, 1: Print "Well done, you win!"; Space$(20)
                Exit Do
            ElseIf Guess > Number Then
                Locate 4, 1: Print "Too high, try lower"; Space$(20)
            ElseIf Guess < Number Then
                Locate 4, 1: Print "Too low, try higher"; Space$(20)
            End If
        Else
            Print "Wrong input data! Try again"; Space$(20)
        End If
        _Delay 1
        If Done = 11 Then Exit Do Else Done = Done + 1
    Loop
    If Done = 11 Then
        Locate 4, 1: Print "Ah ah ah, I win and you loose!"; Space$(20)
    Else
        Locate 4, 1: Print " Sigh, you win!"; Space$(20)
    End If
    Locate 6, 1: Input "Another play? 1 = yes, others values = no ", Done
    If Done <> 1 Then Done = 0
Wend
End


randomise
10 random 1+ number$
say 'I chose a number between 1 and 10.' cr
[ $ 'Your guess? ' input
  over = if
    done
  again ]
drop say 'Well guessed!'


f <- function() {
    print("Guess a number between 1 and 10 until you get it right.")
    n <- sample(10, 1)
    while (as.numeric(readline()) != n) {
        print("Try again.")
    }
    print("You got it!")
}


#lang racket
(define (guess-number)
  (define number (add1 (random 10)))
  (let loop ()
    (define guess (read))
    (if (equal? guess number)
        (display "Well guessed!\n")
        (loop))))


my $number = (1..10).pick;
repeat {} until prompt("Guess a number: ") == $number;
say "Guessed right!";


RANDOMIZE
number = rnd(10) + 1
Print "I selected a number between 1 and 10, try to find it:" + chr$(10)

while Guess <> Number
    input "Your guess: "; Guess
wend

print "You guessed right, well done !"
input "Press enter to quit";a$


import vis::Render;
import vis::Figure;
import util::Math;

public void Guess(){
	random = arbInt(10);
	entered = "";
	guess = false;
	figure = box(vcat([
			text("Try to guess the number from 0 to 9."),
			textfield("Put your guess here", void(str s){guess = (toInt(s)==random); entered = s; }, fillColor("white")),
			text(str(){return guess ? "Correct answer!" : "This is false, the number is not <entered>.";}),
			button("Start over", void(){random = arbInt(10);}) ]));
	render(figure);
}


Red []
#include %environment/console/CLI/input.red
random/seed now
print "I have thought of a number between 1 and 10. Try to guess it."
number: random 10
while [(to integer! input) <> number][
    print "Your guess was wrong. Try again."
]
print "Well guessed!"


: checkGuess ( gn-gf || f )
  over = [ drop 0 ] [ "Sorry, try again!\n" puts -1 ] if ;

: think ( -n )
  random abs 10 mod 1+ ;

: guess ( - )
  "I'm thinking of a number between 1 and 10.\n" puts
  "Try to guess it!\n" puts
  think [ getToken toNumber checkGuess ] while
  "You got it!\n" puts ;


#!/usr/bin/rexx
/*REXX program to play:    Guess the number  */

number = random(1,10)
say "I have thought of a number. Try to guess it!"

guess=0    /* We don't want a valid guess, before we start */

do while guess \= number
  pull guess
  if guess \= number then
    say "Sorry, the guess was wrong. Try again!"
  /* endif - There is no endif in rexx. */
end

say "Well done! You guessed it!"


### Bert Mariani
### 2018-03-01
### Guess_My_Number

myNumber = random(10)
answer   = 0

See "Guess my number between 1 and 10"+ nl

while answer != myNumber
  See "Your guess: "
  Give answer

  if answer = myNumber
    See "Well done! You guessed it! "+ myNumber +nl
  else
    See "Try again"+ nl
  ok

  if answer = 0
    See "Give up. My number is: "+ myNumber +nl
  ok
end


DIR
  INITIALIZE
  << { C G R } PURGE RAND 10 * 1 + IP 'R' STO GUESSING
  >>
  GUESSING
  << "Pick a number between 1 and 10." "" INPUT OBJ-> 'G' STO
     IF
       G R ==
     THEN
       CLLCD "You got it!" 1 DISP 7 FREEZE 0 WAIT CLLCD CONTINUE
     ELSE
       IF
         G R <
       THEN
         CLLCD "Try a larger number." 1 DISP 7 FREEZE 0 WAIT GUESSING
       ELSE
         CLLCD "Try a smaller number." 1 DISP 7 FREEZE 0 WAIT GUESSING
       END
     END
  >>
  CONTINUE
  << "Do you want to continue? (0/1)" "" INPUT OBJ-> 'C' STO
     IF
       C 1 ==
     THEN
       INITIALIZE
     ELSE
       CLEAR
     END
  >>
END


n = rand(1..10)
puts 'Guess the number: '
puts 'Wrong! Guess again: ' until gets.to_i == n
puts 'Well guessed!'


while 1
choose = int(RND(0) * 9) + 1
while guess <> choose
   print "Guess a number between 1 and 10: ";: input guess
   if guess = choose THEN
      print "You guessed!"
     else
      print "Sorry, try again"
   end if
wend
wend


extern crate rand;

fn main() {
    println!("Type in an integer between 1 and 10 and press enter.");

    let n = rand::random::<u32>() % 10 + 1;
    loop {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        let option: Result<u32,_> = line.trim().parse();
        match option {
            Ok(guess) => {
                if guess < 1 || guess > 10 {
                    println!("Guess is out of bounds; try again.");
                } else if guess == n {
                    println!("Well guessed!");
                    break;
                } else {
                    println!("Wrong! Try again.");
                }
            },
            Err(_) => println!("Invalid input; try again.")
        }
    }
}


val n = (math.random * 10 + 1).toInt
print("Guess the number: ")
while(readInt != n) print("Wrong! Guess again: ")
println("Well guessed!")


(define (guess)
  (define number (random 11))
  (display "Pick a number from 1 through 10.\n> ")
  (do ((guess (read) (read)))
        ((= guess number) (display "Well guessed!\n"))
      (display "Guess again.\n")))


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: number is 0;
    var integer: guess is 0;
  begin
    number := rand(1, 10);
    writeln("I'm thinking of a number between 1 and 10.");
    writeln("Try to guess it!");
    readln(guess);
    while guess <> number do
      writeln("That's not my number.");
      writeln("Try another guess!");
      readln(guess);
    end while;
    writeln("You have won!");
  end func;


(|
parent* = traits clonable.
copy = (resend.copy secretNumber: random integerBetween: 1 And: 10).
secretNumber.

ask             = ((userQuery askString: 'Guess the Number: ') asInteger).
reportSuccess   = (userQuery report: 'You got it!').
reportFailure   = (userQuery report: 'Nope. Guess again.').
sayIntroduction = (userQuery report: 'Try to guess my secret number between 1 and 10.').

hasGuessed = ( [ask = secretNumber] onReturn: [|:r| r ifTrue: [reportSuccess] False: [reportFailure]] ).
run  = (sayIntroduction. [hasGuessed] whileFalse)
|) copy run


var n = irand(1, 10)
var msg = 'Guess the number: '
while (n != read(msg, Number)) {
    msg = 'Wrong! Guess again: '
}
say 'Well guessed!'


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()
    TextWindow.WriteLine("Guess again! ")
EndWhile
TextWindow.WriteLine("You win!")


import Cocoa

var found = false
let randomNum = Int(arc4random_uniform(10) + 1)

println("Guess a number between 1 and 10\n")
while (!found) {
    var fh = NSFileHandle.fileHandleWithStandardInput()

    println("Enter a number: ")
    let data = fh.availableData
    var str = NSString(data: data, encoding: NSUTF8StringEncoding)
    if (str?.integerValue == randomNum) {
        found = true
        println("Well guessed!")
    }
}


set target [expr {int(rand()*10 + 1)}]
puts "I have thought of a number."
puts "Try to guess it!"
while 1 {
    puts -nonewline "Enter your guess: "
    flush stdout
    gets stdin guess
    if {$guess == $target} {
	break
    }
    puts "Your guess was wrong. Try again!"
}
puts "Well done! You guessed it."


$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
luckynumber=RANDOM_NUMBERS (1,10,1)
COMPILE
LOOP round=1,7
message=CONCAT ("[",round,"] Please insert a number")
ASK $message: n=""
 IF (n!='digits') THEN
   PRINT "wrong insert: ",n," Please insert a digit"
 ELSEIF (n>10.or.n<1) THEN
   PRINT "wrong insert: ",n," Please insert a number between 1-10"
 ELSEIF (n==#luckynumber) THEN
   PRINT "BINGO"
   EXIT
ENDIF
IF (round==7) PRINT/ERROR "You've lost: luckynumber was: ",luckynumber
ENDLOOP
ENDCOMPILE


#!/bin/sh
# Guess the number
# This simplified program does not check the input is valid

# Use awk(1) to get a random number. If awk(1) not found, exit now.
number=`awk 'BEGIN{print int(rand()*10+1)}'` || exit

echo 'I have thought of a number. Try to guess it!'
echo 'Enter an integer from 1 to 10.'
until read guess; [ "$guess" -eq "$number" ]
do
  echo 'Sorry, the guess was wrong! Try again!'
done
echo 'Well done! You guessed it.'


# Simple number guessing game

decl ursa.util.random random
decl int target guess

set target (int (+ 1 (random.getint 9)))
out "Guess a number between 1 and 10." endl console
while (not (= target guess))
        set guess (in int console)
end while

out "That's right!" endl console


int main() {
	int x = Random.int_range(1, 10);
	stdout.printf("Make a guess (1-10): ");
	while(int.parse(stdin.read_line()) != x)
                stdout.printf("Wrong! Try again: ");
	stdout.printf("Got it!\n");
	return 0;
}


Sub GuessTheNumber()
Dim NbComputer As Integer, NbPlayer As Integer
    Randomize Timer
    NbComputer = Int((Rnd * 10) + 1)
    Do
        NbPlayer = Application.InputBox("Choose a number between 1 and 10 : ", "Enter your guess", Type:=1)
    Loop While NbComputer <> NbPlayer
    MsgBox "Well guessed!"
End Sub


randomize
MyNum=Int(rnd*10)+1
Do
	x=x+1
	YourGuess=InputBox("Enter A number from 1 to 10")
	If not Isnumeric(YourGuess) then
		msgbox YourGuess &" is not numeric. Try again."
	ElseIf CInt(YourGuess)>10 or CInt(YourGuess)<1 then
		msgbox YourGuess &" is not between 1 and 10. Try Again."
	ElseIf CInt(YourGuess)=CInt(MyNum) then
		MsgBox "Well Guessed!"
		wscript.quit
	ElseIf Cint(YourGuess)<>CInt(Mynum) then
		MsgBox "Nope. Try again."
	end If

	if x > 20 then
		msgbox "I take pity on you"
		wscript.quit
	end if
loop


Module Guess_the_Number
    Sub Main()
        Dim random As New Random()
        Dim secretNum As Integer = random.Next(10) + 1
        Dim gameOver As Boolean = False
        Console.WriteLine("I am thinking of a number from 1 to 10. Can you guess it?")
        Do
            Dim guessNum As Integer
            Console.Write("Enter your guess: ")

            If Not Integer.TryParse(Console.ReadLine(), guessNum) Then
                Console.WriteLine("You should enter a number from 1 to 10. Try again!")
                Continue Do
            End If

            If guessNum = secretNum Then
                Console.WriteLine("Well guessed!")
                gameOver = True
            Else
                Console.WriteLine("Incorrect. Try again!")
            End If
        Loop Until gameOver
    End Sub
End Module


import rand
import rand.seed
import os

fn main() {
    seed_array := seed.time_seed_array(2)
    rand.seed(seed_array)
    num := rand.intn(10) + 1  // Random number 1-10
    for {
        print('Please guess a number from 1-10 and press <Enter>: ')
        guess := os.get_line()
        if guess.int() == num {
            println("Well guessed! '$guess' is correct.")
            return
        } else {
            println("'$guess' is Incorrect. Try again.")
        }
    }
}


(module
  (import "wasi_unstable" "fd_read"
    (func $fd_read (param i32 i32 i32 i32) (result i32)))
  (import "wasi_unstable" "fd_write"
    (func $fd_write (param i32 i32 i32 i32) (result i32)))
  (import "wasi_unstable" "random_get"
    (func $random_get (param i32 i32) (result i32)))

  (memory 1) (export "memory" (memory 0))
  ;; memory usage:
  ;; 0-7: temp IO Vector used with WASI functions
  ;; 8-24: temp buffer used for reading numbers
  ;; 100-: string data

  ;; string constants
  (data (i32.const 100) "Guess a number between 1 and 10.\n")
  (data (i32.const 200) "Well guessed!\n")

  ;; function to print a null-terminated string at the given address
  ;; (assumes use of an IOVector at address 0)
  (func $print_cstr (param $strAddr i32)
	(local $charPos i32)

	;; store the data address into our IO vector (address 0)
	i32.const 0  local.get $strAddr  i32.store

	;; find the null terminator at the end of the string
	local.get $strAddr  local.set $charPos
	block $loop_break
	  loop $LOOP
		;; get the character at charPos
		local.get $charPos  i32.load
		;; if it is equal to zero, break out of the loop
		i32.eqz if br $loop_break end
		;; otherwise, increment and loop
		local.get $charPos  i32.const 1  i32.add  local.set $charPos
		br $LOOP
	  end
	end

	;; from that, compute the length of the string for our IOVector
	i32.const 4  ;; (address of string length in the IOVector)
	local.get $charPos  local.get $strAddr  i32.sub
	i32.store

	;; now call $fd_write to actually write to stdout
	i32.const 1  ;; 1 for stdout
	i32.const 0  i32.const 1   ;; 1 IOVector at address 0
	i32.const 0  ;; where to stuff the number of bytes written
	call $fd_write
	drop  ;; (drop the result value)
  )

  ;; function to read a number
  ;; (assumes use of an IOVector at address 0,
  ;; and 16-character buffer at address 8)
  (func $input_i32 (result i32)
	(local $ptr i32)
	(local $n i32)
	(local $result i32)

	;; prepare our IOVector to point to the buffer
	i32.const 0  i32.const 8  i32.store    ;; (address of buffer)
	i32.const 4  i32.const 16  i32.store   ;; (size of buffer)

	i32.const 0  ;; 0 for stdin
	i32.const 0  i32.const 1  ;; 1 IOVector at address 0
	i32.const 4  ;; where to stuff the number of bytes read
	call $fd_read  drop

	;; Convert that to a number!
	;; loop over characters in the string until we hit something < '0'.
	i32.const 8  local.set $ptr
	block $LOOP_BREAK
	  loop $LOOP
		;; get value of current digit
		;; (we assume all positive integers for this task)
		local.get $ptr  i32.load8_u
		i32.const 48  i32.sub     ;; (subtract 48, ASCII value of '0')
		local.tee $n

		;; bail out if < 0
		i32.const 0  i32.lt_s  br_if $LOOP_BREAK

		;; multiply current number by 10, and add new number
		local.get $result  i32.const 10  i32.mul
		local.get $n  i32.add
		local.set $result

		;; increment and loop
		local.get $ptr  i32.const 1  i32.add  local.set $ptr
		br $LOOP
	  end
	end

	local.get $result
  )

  ;; function to get a random i32
  ;; (assumes use of temporary space at address 0)
  (func $random_i32 (result i32)
	i32.const 0  i32.const 4  call $random_get  drop
	i32.const 0  i32.load
  )

  (func $main (export "_start")
	(local $trueNumber i32)

	;; get a random integer, then take that (unsigned) mod 10
	call $random_i32  i32.const 10  i32.rem_u
	local.set $trueNumber

	loop $LOOP
	    ;; print prompt
	    i32.const 100  call $print_cstr

	    ;; input a guess
	    call $input_i32

	    ;; if correct, print message and we're done
	    local.get $trueNumber i32.eq  if
		i32.const 200  call $print_cstr
		return
	    end
	    br $LOOP
	end
  )
)


let mnnumber=1
let mxnumber=10
let number=mnnumber
let keycode=0
let guessed=0
print 1 "Press any key so the computer can generate a random number for you to guess."
while keycode=0
let number=number=1
let keycode=key()
if number=mxnumber+1
let number=mnnumber
endif
wend
print 1 "Guess the number. It is between "+mnnumber+"and "+mxnumber
while guessed=0
input guess
if guess=number
print 1 "Well done! You guessed the correct number."
let guessed=1
else
print 1 "You guessed the incorrect number. Please try again."
endif
wend
end


@let {
  num 10Wc
  guess 0
  [
    @while != guess num
      :guess !prompt "Guess the number between 1 and 10 inclusive"
    !alert "Congratulations!\nThe number was {num}."
  ]
}


import "io" for Stdin, Stdout
import "random" for Random

var rand = Random.new()
var n = rand.int(1, 11) // computer number from 1..10 inclusive
while (true) {
    System.write("Your guess 1-10 : ")
    Stdout.flush()
    var guess = Num.fromString(Stdin.readLine())
    if (n == guess) {
        System.print("Well guessed!")
        break
    }
}


 segment .data

      random  dd  0   ; Where the random number will be stored
      guess   dd  0   ; Where the user input will be stored

     instructions    db  10, "Welcome user! The game is simple: Guess a random number (1-10)!", 10, 10
     len1 equ $ - instructions   ; 1 \n before and 2 \n after instructions for better appearance

     wrong           db  "Not the number :(", 10
     len2 equ $ - wrong

     correct         db  "You guessed right, congratulations :D", 10
     len3 equ $ - correct

 segment .bss

 segment .text
     global  main

 main:
     push    rbp
     mov     rbp, rsp
     ; ********** CODE STARTS HERE **********

     ;;;;; Random number generator ;;;;;

     mov     eax, 13
     mov     ebx, random
     int     80h
     mov     eax, [ebx]
     mov     ebx, 10
     xor     edx, edx
     div     ebx
     inc     edx
     mov     [random], edx

     ;;;;; Print the instructions ;;;;;

     mov     eax, 4
     mov     ebx, 1
     mov     ecx, instructions
     mov     edx, len1
     int     80h

 userInput:

     ;;;;; Ask user for input ;;;;;

     mov     eax, 3
     xor     ebx, ebx
     mov     ecx, instructions
     mov     edx, 1
     int     80h
     mov     al, [ecx]
     cmp     al, 48
     jl      valCheck
     cmp     al, 57
     jg      valCheck

     ;;;;; If number ;;;;;

     sub     al, 48
     xchg    eax, [guess]
     mov     ebx, 10
     mul     ebx
     add     [guess], eax
     jmp     userInput

 valCheck:

     ;;;;; Else check number ;;;;;

     mov     eax, 4
     inc     ebx
     mov     ecx, [guess]
     cmp     ecx, [random]
     je      correctResult

     ;;;;; If not equal, "not the number :(" ;;;;;

     mov     ecx, wrong
     mov     edx, len2
     mov     DWORD [guess], 0
     int     80h
     jmp     userInput

 correctResult:

     ;;;;; If equal, "congratulations :D" ;;;;;

     mov     ecx, correct
     mov     edx, len3
     int     80h

     ;;;;; EXIT ;;;;;

     mov     rax, 0
     mov     rsp, rbp
     pop     rbp
     ret

; "Guess my number" program by Randomboi (8/8/2021)


const Range:{Min:number,Max:number} = {
	Min:number=1,
	Max:number=10,
};

while(true){
	set RandomNumber:number = math.random(Range.Min,Range.Max);
	set Response:string = window->prompt("Enter a number from "+tostring(Range.Min)+" to "+tostring(Range.Max));
	if (toint(Response)==RandomNumber){
		log("Well guessed!");
		stop;
	}
}


(defun guessing-game ()
    (defun prompt ()
        (display "What is your guess? ")
        (define guess (read))
        (if (= guess n)
            (display "Well guessed!")
            (begin
                (display "No...")
                (newline)
                (prompt))))
    (define n (+ (random 10) 1))
    (display "I have thought of a number between 1 and 10. Try to guess it!")
    (newline)
    (prompt))


code Ran=1, IntIn=10, Text=12;
int N, G;
[N:= Ran(10)+1;
Text(0, "I'm thinking of a number between 1 and 10.^M^J");
loop    [Text(0, "Can you guess it? ");
        G:= IntIn(0);
        if G=N then quit;
        Text(0, "Nope, that's not it.^M^J");
        ];
Text(0, "Well guessed!^M^J");
]


r:=((0).random(10)+1).toString();
while(1){
   n:=ask("Num between 1 & 10: ");
   if(n==r){ println("Well guessed!"); break; }
   println("Nope")
}


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 ne guess randnum
print "Incorrect. Try again!"
println
endif
endwhile
print "Correct number. You win!"


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.")


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


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_RNG is new Ada.Numerics.Discrete_Random (Number);
      Generator  : Number_RNG.Generator;
      My_Number  : Number;
      Your_Guess : Integer;
   begin
      Number_RNG.Reset (Generator);
      My_Number := Number_RNG.Random (Generator);
      Ada.Text_IO.Put_Line ("Guess my number!");
      loop
         Your_Guess := Get_Int ("Your guess: ");
         exit when Your_Guess = My_Number;
         if Your_Guess > My_Number then
            Ada.Text_IO.Put_Line ("Wrong, too high!");
         else
            Ada.Text_IO.Put_Line ("Wrong, too low!");
         end if;
      end loop;
      Ada.Text_IO.Put_Line ("Well guessed!");
   end Guess_Number;
   Lower_Limit : Integer;
   Upper_Limit : Integer;
begin
   loop
      Lower_Limit := Get_Int  ("Lower Limit: ");
      Upper_Limit := Get_Int  ("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;


# simple guess-the-number game #

main:(

    BOOL valid input := TRUE;

    # register an error handler so we can detect and recover from #
    # invalid input #
    on value error( stand in
                  , ( REF FILE f )BOOL:
                    BEGIN
                        valid input := FALSE;
                        TRUE
                    END
                  );

    # construct a random integer between 1 and 100                #
    INT   number = 1 + ROUND ( random * 99 );

    print( ( "I'm thinking of a number between 1 and 100", newline ) );

    # read the user's guesses until they guess correctly          #
    # we give feedback so they can find the number using interval #
    # halving                                                     #
    WHILE
        print( ( "What do you think it is? " ) );
        INT guess;
        WHILE
            valid input := TRUE;
            read( ( guess, newline ) );
            NOT valid input
        DO
            print( ( "Please guess a number between 1 and 100", newline ) )
        OD;
        number /= guess
    DO
        IF number > guess
        THEN
            # the user's guess was too small #
            print( ( newline, "My number is higher than that", newline ) )
        ELSE
            # the user's guess was too large #
            print( ( newline, "My number is lower than that",  newline ) )
        FI
    OD;
    print( ( "That's correct!", newline ) )
)


-- 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


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!"
]


MinNum = 1
MaxNum = 99999999999

Random, RandNum, %MinNum%, %MaxNum%
Loop
{
 InputBox, Guess, Number Guessing, Please enter a number between %MinNum% and %MaxNum%:,, 350, 130,,,,, %Guess%
 If ErrorLevel
  ExitApp
 If Guess Is Not Integer
 {
  MsgBox, 16, Error, Invalid guess.
  Continue
 }
 If Guess Not Between %MinNum% And %MaxNum%
 {
  MsgBox, 16, Error, Guess must be a number between %MinNum% and %MaxNum%.
  Continue
 }
 If A_Index = 1
  TotalTime = %A_TickCount%
 Tries = %A_Index%
 If Guess = %RandNum%
  Break
 If Guess < %RandNum%
  MsgBox, 64, Incorrect, The number guessed (%Guess%) was too low.
 If Guess > %RandNum%
  MsgBox, 64, Incorrect, The number guessed (%Guess%) was too high.
}
TotalTime := Round((A_TickCount - TotalTime) / 1000,1)
MsgBox, 64, Correct, The number %RandNum% was guessed in %Tries% tries, which took %TotalTime% seconds.


# syntax: GAWK -f GUESS_THE_NUMBER_WITH_FEEDBACK.AWK
BEGIN {
    L = 1
    H = 100
    srand()
    n = int(rand() * (H-L+1)) + 1
    printf("I am thinking of a number between %d and %d. Try to guess it.\n",L,H)
    while (1) {
      getline ans
      if (ans !~ /^[0-9]+$/) {
        print("Your input was not a number. Try again.")
        continue
      }
      if (n == ans) {
        print("Well done you.")
        break
      }
      if (n > ans) {
        print("Incorrect, your answer was too low. Try again.")
        continue
      }
      if (n < ans) {
        print("Incorrect, your answer was too high. Try again.")
        continue
      }
    }
    exit(0)
}


100 L% = 1
110 U% = 10
120 N% = RND(1) * (U% - L% + 1) + L%
130 PRINT "A NUMBER FROM " L%;
140 PRINT " TO " U%;
150 PRINT ", CALLED A TARGET, HAS BEEN RANDOMLY CHOSEN."
160 FOR Q = 0 TO 1 STEP 0
170     INPUT "GUESS THE TARGET NUMBER: "; G%
180     IF G% < L% OR G% > U% THEN PRINT "THE INPUT WAS INAPPROPRIATE."
190     IF G% > N% THEN PRINT "THE GUESS WAS HIGHER THAN THE TARGET."
200     IF G% < N% THEN PRINT "THE GUESS WAS LESS THAN THE TARGET."
210     Q = G% = N%
220 NEXT
230 PRINT "THE GUESS WAS EQUAL TO THE TARGET."


@echo off

:A
set /a number=%random% %% 10 + 1
:B
set /p guess=Choose a number between 1 and 10:
if %guess equ %number% goto win
if %guess% gtr 10 msg * "Number must be between 1 and 10."
if %guess% leq 0 msg * "Number must be between 1 and 10."
if %guess% gtr %number% echo Higher!
if %guess% lss %number% echo Lower!
goto B
:win
cls
echo You won! The number was %number%
pause>nul
goto A


      Min% = 1
      Max% = 10
      chosen% = RND(Max%-Min%+1) + Min% - 1
      REPEAT
        PRINT "Guess a number between "; Min% " and " ;Max% ;
        INPUT ": " guess%
        CASE TRUE OF
          WHEN guess% < Min% OR guess% > Max%:
            PRINT "That was an invalid number"
          WHEN guess% < chosen%:
            PRINT "Sorry, your number was too low"
          WHEN guess% > chosen%:
            PRINT "Sorry, your number was too high"
          OTHERWISE:
            PRINT "Well guessed!"
            EXIT REPEAT
        ENDCASE
      UNTIL FALSE
      END


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))
$)


number = random 10

p "Guess a number between 1 and 10."

until {
  guess = ask("Guess: ").to_i

  true? (guess.null? || { guess > 10 || guess < 1 })
    { p "Please guess a number between 1 and 10."}
    { true? guess == number
      { p "Correct!"; true }
      { true? guess < number
        { p "Too low!" }
        { p "Too high!" }
      }
    }
}


#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define lower_limit 0
#define upper_limit 100

int main(){
  int number, guess;

  srand( time( 0 ) );
  number = lower_limit + rand() % (upper_limit - lower_limit + 1);

  printf( "Guess the number between %d and %d: ", lower_limit, upper_limit );

  while( scanf( "%d", &guess ) == 1 ){
    if( number == guess ){
      printf( "You guessed correctly!\n" );
      break;
    }
    printf( "Your guess was too %s.\nTry again: ", number < guess ? "high" : "low" );
  }

  return 0;
}


using System;

class Program
{
    static void Main(string[] args)
    {
        const int from = 1;
        const int to = 10;

        int randomNumber = new Random().Next(from, to);
        int guessedNumber;

        Console.Write("The number is between {0} and {1}. ", from, to);
        while (true)
        {
            Console.Write("Make a guess: ");
            if (int.TryParse(Console.ReadLine(), out guessedNumber))
            {
                if (guessedNumber == randomNumber)
                {
                    Console.WriteLine("You guessed the right number!");
                    break;
                }
                else
                {
                    Console.WriteLine("Your guess was too {0}.", (guessedNumber > randomNumber) ? "high" : "low");
                }
            }
            else
            {
                Console.WriteLine("Input was not an integer.");
            }
        }

        Console.WriteLine();
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}


#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;
}