Integer comparison

From Rosetta Code

Jump to: navigation, search
Task
Integer comparison
You are encouraged to solve this task according to the task description, using any language you may know.

Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.

You may see other such operations in the Basic Data Operations category, or:

Get two integers from the user, and then output if the first one is less, equal or greater than the other. Test the condition for each case separately, so that all three comparison operators are used in the code.

Contents

[edit] 6502 Assembly

Code is called as a subroutine (i.e. JSR Compare). Specific OS/hardware routines for user input and printing are left unimplemented.

Compare		PHA			;push Accumulator onto stack
JSR GetUserInput ;routine not implemented
;integers to compare now in memory locations A and B
LDA A
CMP B ;sets flags as if a subtraction (a - b) had been carried out
BCC A_less_than_B ;branch if carry clear
BEQ A_equals_B ;branch if equal
;else A greater than B
JSR DisplayAGreaterThanB;routine not implemented
JMP Done
A_less_than_B: JSR DisplayALessThanB ;routine not implemented
JMP Done
A_equals_B: JSR DisplayAEqualsB ;routine not implemented
Done: PLA ;restore Accumulator from stack
RTS ;return from subroutine

[edit] Ada

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_Io;
 
procedure Compare_Ints is
A, B : Integer;
begin
Get(Item => A);
Get(Item => B);
 
-- Test for equality
if A = B then
Put_Line("A equals B");
end if;
 
-- Test For Less Than
if A < B then
Put_Line("A is less than B");
end if;
 
-- Test For Greater Than
if A > B then
Put_Line("A is greater than B");
end if;
end Compare_Ints;

[edit] ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used

Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

Note: the standard includes the characters "≤", "≥" and "≠". These appear in the character sets GOST 10859, ISOtech and IBM's EBCDIC e.g. code page 293, and in extended ASCII code pages 910 & 910

The above distributions of both ALGOL 68G and ELLA ALGOL 68 compilers only allow ASCII characters (ASCII has neither "≤", "≥" nor "≠" characters).

main: (
INT a, b;
read((a, space, b, new line));
 
IF a <= b OR a LE b # OR a ≤ b # THEN
print((a," is less or equal to ", b, new line))
FI;
IF a < b OR a LT b THEN
print((a," is less than ", b, new line))
ELIF a = b OR a EQ b THEN
print((a," is equal to ", b, new line))
ELIF a > b OR a GT b THEN
print((a," is greater than ", b, new line))
FI;
IF a /= b OR a NE b # OR a ≠ b # THEN
print((a," is not equal to ", b, new line))
FI;
IF a >= b OR a GE b # OR a ≥ b # THEN
print((a," is greater or equal to ", b, new line))
FI
)

Example output:

+3 is less or equal to          +4
         +3 is less than          +4
         +3 is not equal to          +4

[edit] AppleScript

set n1 to text returned of (display dialog "Enter the first number:" default answer "") as integer
set n2 to text returned of (display dialog "Enter the second number:" default answer "") as integer
set msg to {n1}
if n1 < n2 then
set end of msg to " is less than "
else if n1 = n2 then
set end of msg to " is equal to "
else if n1 > n2 then
set end of msg to " is greater than "
end if
set end of msg to n2
return msg as string

Or...

set n1 to text returned of (display dialog "Enter the first number:" default answer "") as integer
set n2 to text returned of (display dialog "Enter the second number:" default answer "") as integer
if n1 < n2 then return "" & n1 & " is less than " & n2
if n1 = n2 then return "" & n1 & " is equal to " & n2
if n1 > n2 then return "" & n1 & " is greater than " & n2

[edit] AutoHotkey

Error checking is performed automatically by attaching UpDowns to each of the Edit controls. UpDown controls always yield an in-range number, even when the user has typed something non-numeric or out-of-range in the Edit control. The default range is 0 to 100.

Gui, Add, Edit
Gui, Add, UpDown, vVar1
Gui, Add, Edit
Gui, Add, UpDown, vVar2
Gui, Add, Button, Default, Submit
Gui, Show
Return
 
ButtonSubmit:
Gui, Submit, NoHide
If (Var1 = Var2)
MsgBox, % Var1 "=" Var2
Else If (Var1 < Var2)
MsgBox, % Var1 "<" Var2
Else If (Var1 > Var2)
MsgBox, % Var1 ">" Var2
Return
 
GuiClose:
ExitApp

[edit] AWK

/[0-9]* [0-9]*/{
if ($1 == $2) print $1, "is equal to", $2
if ($1 < $2) print $1, "is less than", $2
if ($1 > $2) print $1, "is greater than", $2
}

[edit] BASIC

Works with: QuickBasic version 4.5

CLS
INPUT "a, b"; a, b 'remember to type the comma when you give the numbers
PRINT "a is ";
IF a < b THEN PRINT "less than ";
IF a = b THEN PRINT "equal to ";
IF a > b THEN PRINT "greater than ";
PRINT "b"

[edit] Befunge

Befunge only has the greater-than operator (backtick `). The branch commands (underline _ and pipe |) test for zero.

v                     v  ">"   $<
>&&"=A",,\:."=B ",,,\: .55+,-:0`|
v "<" _v#<
@,+55,," B",,,"A " < "=" <

[edit] Common Lisp

You can type this directly into a REPL:

(let ((a (read *standard-input*))
(b (read *standard-input*)))
(cond
((not (numberp a)) (format t "~A is not a number." a))
((not (numberp b)) (format t "~A is not a number." b))
((< a b) (format t "~A is less than ~A." a b))
((> a b) (format t "~A is greater than ~A." a b))
((= a b) (format t "~A is equal to ~A." a b))
(t (format t "Cannot determine relevance between ~A and ~B!" a b)))))

After hitting enter, the REPL is expecting the two numbers right away. You can enter the two numbers, and the result will print immediately. Alternatively, you can wrap this code in a function definition:

(defun compare-integers () 
(let ((a (read *standard-input*))
(b (read *standard-input*)))
(cond
((not (numberp a)) (format t "~A is not a number." a))
((not (numberp b)) (format t "~A is not a number." b))
((< a b) (format t "~A is less than ~A." a b))
((> a b) (format t "~A is greater than ~A." a b))
((= a b) (format t "~A is equal to ~A." a b))
(t (format t "Cannot determine relevance between ~A and ~B!" a b)))))

Then, execute the function for better control:

(compare-integers)

[edit] C

#include <stdio.h>
 
int main()
{
int a, b;
scanf("%d %d", &a, &b);
 
if (a < b)
printf("%d is less than %d\n", a, b);
 
if (a == b)
printf("%d is equal to %d\n", a, b);
 
if (a > b)
printf("%d is greater than %d\n", a, b);
 
return 0;
}

[edit] C++

#include <iostream>
using namespace std;
 
int main()
{
int a, b;
cin >> a >> b;
 
// test for less-than
if (a < b)
cout << a << " is less than " << b << endl;
 
// test for equality
if (a == b)
cout << a << " is equal to " << b << endl;
 
// test for greater-than
if (a > b)
cout << a << " is greater than " << b << endl;
}

[edit] C#

using System;
 
class Program
{
static void Main()
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
if (a < b)
Console.WriteLine("{0} is less than {1}", a, b);
if (a == b)
Console.WriteLine("{0} equals {1}", a, b);
if (a > b)
Console.WriteLine("{0} is greater than {1}", a, b);
}
}

[edit] Clean

import StdEnv
 
compare a b
| a < b = "A is less than B"
| a > b = "A is more than B"
| a == b = "A equals B"
 
Start world
# (console, world) = stdio world
(_, a, console) = freadi console
(_, b, console) = freadi console
= compare a b

[edit] D

import std.stdio, std.string;
 
void main() {
auto a = readln().atoi(), b = readln().atoi();
if (a < b)
writefln(a, " is less than ", b);
 
if (a == b)
writefln(a, " is equal to ", b);
 
if (a > b)
writefln(a, " is greater than ", b);
}

[edit] E

def compare(a :int, b :int) {
println(if (a < b) { `$a < $b` } \
else if (a <=> b) { `$a = $b` } \
else if (a > b) { `$a > $b` } \
else { `You're calling that an integer?` })
}

[edit] Efene

since if does pattern matching the else is required to avoid the application from crashing

compare = fn (A, B) {
if A == B {
io.format("~p equals ~p~n", [A, B])
}
else {
ok
}
 
if A < B {
io.format("~p is less than ~p~n", [A, B])
}
else {
ok
}
 
if A > B {
io.format("~p is greater than ~p~n", [A, B])
}
else {
ok
}
}
 
@public
run = fn () {
compare(5, 5)
compare(6, 5)
compare(4, 5)
}
 

[edit] Factor

: example ( -- ) 
readln readln [ string>number ] bi@
[ > [ "A > B" print ] when ]
[ < [ "A < B" print ] when ]
[ = [ "A = B" print ] when ] 2tri ;
 

[edit] FALSE

Only equals and greater than are available.

^^ \$@$@$@$@\
>[\$," is greater than "\$,]?
\>[\$," is less than "\$,]?
=["characters are equal"]?

[edit] Forth

To keep the example simple, the word takes the two numbers from the stack.

: compare-integers ( a b -- )
2dup < if ." a is less than b" then
2dup > if ." a is greater than b" then
= if ." a is equal to b" then ;

[edit] Fortran

In ALL Fortran versions (including original 1950's era) you could use an "arithmetic IF" statement to compare using subtraction:

program arithif
integer a, b
 
c fortran 77 I/O statements, for simplicity
read(*,*) a, b
 
if ( a - b ) 10, 20, 30
10 write(*,*) a, ' is less than ', b
goto 40
 
20 write(*,*) a, ' is equal to ', b
goto 40
 
30 write(*,*) a, ' is greater than ', b
40 continue
 
end

In ANSI FORTRAN 66 or later you could use relational operators (.lt., .gt., .eq., etc.) and unstructured IF statements:

program compare
integer a, b
c fortran 77 I/O statements, for simplicity
read(*,*) a, b
 
if (a .lt. b) write(*, *) a, ' is less than ', b
if (a .eq. b) write(*, *) a, ' is equal to ', b
if (a .gt. b) write(*, *) a, ' is greater than ', b
end

In ANSI FORTRAN 77 or later you can use relational operators and structured IF statements:

program compare
integer a, b
read(*,*) a, b
 
if (a .lt. b) then
write(*, *) a, ' is less than ', b
else if (a .eq. b) then
write(*, *) a, ' is equal to ', b
else if (a .gt. b) then
write(*, *) a, ' is greater than ', b
end if
 
end

In ISO Fortran 90 or later you can use symbolic relational operators (<, >, ==, etc.)

program compare
integer :: a, b
read(*,*) a, b
 
if (a < b) then
write(*, *) a, ' is less than ', b
else if (a == b) then
write(*, *) a, ' is equal to ', b
else if (a > b) then
write(*, *) a, ' is greater than ', b
end if
 
end program compare

[edit] F#

let compare_ints a b =
let r =
match a with
| x when x < b -> -1, printfn "%d is less than %d" x b
| x when x = b -> 0, printfn "%d is equal to %d" x b
| x when x > b -> 1, printfn "%d is greater than %d" x b
| x -> 0, printf "default condition (not reached)"
fst r

[edit] Groovy

[edit] Relational Operators

def comparison = { a, b ->
println "a ? b = ${a} ? ${b} = a ${a < b ? '<' : a > b ? '>' : a == b ? '==' : '?'} b"
}

Program:

comparison(2000,3)
comparison(2000,300000)
comparison(2000,2000)

Output:

a ? b    = 2000 ? 3    = a > b
a ? b    = 2000 ? 300000    = a < b
a ? b    = 2000 ? 2000    = a == b

[edit] "Spaceship" (compareTo) Operator

Using spaceship operator and a lookup table:

def comparison = { a, b ->
def rels = [ (-1) : '<', 0 : '==', 1 : '>' ]
println "a ? b = ${a} ? ${b} = a ${rels[a <=> b]} b"
}

Program:

comparison(2000,3)
comparison(2000,300000)
comparison(2000,2000)

Output:

a ? b    = 2000 ? 3    = a > b
a ? b    = 2000 ? 300000    = a < b
a ? b    = 2000 ? 2000    = a == b

[edit] Haskell

myCompare a b
| a < b = "A is less than B"
| a > b = "A is greater than B"
| a == b = "A equals B"
 
main = do
a' <- getLine
b' <- getLine
let { a :: Integer; a = read a' }
let { b :: Integer; b = read b' }
putStrLn $ myCompare a b

However, the more idiomatic and less error-prone way to do it in Haskell would be to use a compare function that returns type Ordering, which is either LT, GT, or EQ:

myCompare a b = case compare a b of
LT -> "A is less than B"
GT -> "A is greater than B"
EQ -> "A equals B"

[edit] HicEst

DLG(NameEdit=a, NameEdit=b, Button='OK')
 
IF (a < b) THEN
WRITE(Messagebox) a, ' is less than ', b
ELSEIF(a == b) THEN
WRITE(Messagebox) a, ' is equal to ', b
ELSEIF(a > b) THEN
WRITE(Messagebox) a, ' is greater than ', b
ENDIF

[edit] Icon and Unicon

[edit] Icon

procedure main()
 
until integer(a) do {
writes("Enter the first integer a := ")
write(a := read())
}
 
until integer(b) do {
writes("Enter the second integer b := ")
write(b := read())
}
writes("Then ")
write(a," < ", a < b)
write(a," = ", a = b)
write(a," > ", a > b)
end

Sample Output:

#int_compare.exe
Enter the first integer a := 7
Enter the second integer b := 7
Then 7 = 7

[edit] Unicon

This Icon solution works in Unicon.

[edit] J

Comparison is accomplished by the verb compare, which provides logical-numeric output.
Text elaborating the output of compare is provided by cti:

compare=: < , = , >
 
cti=: dyad define
select =. ;@#
English =. ' is less than ';' is equal to ';' is greater than '
x (":@[, (compare select English"_), ":@]) y
)

Examples of use:

   4 compare 4
0 1 0
4 cti 3
4 is greater than 3

[edit] Java

import java.io.*;
 
public class compInt {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
 
int nbr1 = Integer.parseInt(in.readLine());
int nbr2 = Integer.parseInt(in.readLine());
 
if(nbr1<nbr2)
System.out.println(nbr1 + " is less than " + nbr2);
 
if(nbr1>nbr2)
System.out.println(nbr1 + " is greater than " + nbr2);
 
if(nbr1==nbr2)
System.out.println(nbr1 + " is equal to " + nbr2);
} catch(IOException e) { }
}
}

[edit] JavaScript

 
// Using type coercion
function compare(a, b) {
if (a==b) print(a + " equals " + b);
if (a < b) print(a + " is less than " + b);
if (a > b) print(a + " is greater than " + b);
}
 
// Without using type coercion and using standards
// Written for browsers
// assumption of a and b are both integers if typeof test passes
function compare (a, b) {
if (typeof a === typeof b) {
if (a === b) {
document.writeln(a + " equals " + b);
}
if (a < b) {
document.writeln(a + " is less than " + b);
}
if (a > b) {
document.writeln(a + " is greater than " + b);
}
} else {
// "1" and 1 are an example of this as the first is type string and the second is type number
print(a + "{" + (typeof a) + "} and " + b + "{" + (typeof b) + "} are not of the same type and cannot be compared.");
}
}
 

[edit] Joy

#!/usr/local/bin/joy.exe
DEFINE
prompt == "Please enter a number and <Enter>: " putchars;
newline == '\n putch;
putln == put newline.
 
stdin # F
prompt fgets # S F
10 strtol # A F
swap # F A
dupd # F A A
prompt fgets # S F A A
10 strtol # B F A A
popd # B A A
dup # B B A A
rollup # B A B A
[<] [swap put "is less than " putchars putln] [] ifte
[=] [swap put "is equal to " putchars putln] [] ifte
[>] [swap put "is greater than " putchars putln] [] ifte
# B A
quit.

[edit] Korn Shell

#!/bin/ksh
# tested with ksh93s+
 
builtin printf
 
integer a=0
integer b=0
 
read a?"Enter value of a: " || { print -u2 "Input of a aborted." ; exit 1 ; }
read b?"Enter value of b: " || { print -u2 "Input of b aborted." ; exit 1 ; }
 
if (( a < b )) ; then
printf "%d is less than %d\n" a b
fi
if (( a == b )) ; then
printf "%d is equal to %d\n" a b
fi
if (( a > b )) ; then
printf "%d is greater than %d\n" a b
fi
 
exit 0

[edit] Logo

to compare :a :b
if :a = :b [(print :a [equals] :b)]
if :a < :b [(print :a [is less than] :b)]
if :a > :b [(print :a [is greater than] :b)]
end

Each infix operator has prefix synonyms (equalp, equal?, lessp, less?, greaterp, greater?), where the 'p' stands for "predicate" as in Lisp.

[edit] Lua

print('Enter the first number: ')
a = tonumber(io.stdin:read())
print('Enter the second number: ')
b = tonumber(io.stdin:read())
 
if a < b then print(a .. " is less than " .. b) end
if a > b then print(a .. " is greater than " .. b) end
if a == b then print(a .. " is equal to " .. b) end

[edit] LSE64

over : 2 pick
2dup : over over
 
compare : 2dup = then " equals"
compare : 2dup < then " is less than"
compare : 2dup > then " is more than"
 
show : compare rot , sp ,t sp , nl

[edit] Mathematica

a=Input["Give me the value for a please!"];
b=Input["Give me the value for b please!"];
If[a==b,Print["a equals b"]]
If[a>b,Print["a is bigger than b"]]
If[a<b,Print["b is bigger than a"]]

[edit] MAXScript

a = getKBValue prompt:"Enter value of a:"
b = getKBValue prompt:"Enter value of b:"
if a < b then print "a is less then b"
else if a > b then print "a is greater then b"
else if a == b then print "a is equal to b"

[edit] Metafont

message "integer 1: ";
a1 := scantokens readstring;
message "integer 2: ";
a2 := scantokens readstring;
if a1 < a2:
message decimal a1 & " is less than " & decimal a2
elseif a1 > a2:
message decimal a1 & " is greater than " & decimal a2
elseif a1 = a2:
message decimal a1 & " is equal to " & decimal a2
fi;
end

[edit] MMIX

Some simple error checking is included.

// main registers
p IS $255 % pointer
pp GREG % backup for p
A GREG % first int
B GREG % second int
 
// arg registers
argc IS $0
argv IS $1
 
LOC Data_Segment
GREG @
ERR BYTE "Wrong number of arguments",#a,0
ILLH BYTE "Argument -> ",0
ILLT BYTE " <- contains an illegal character",#a,0
LT BYTE "A is less than B",#a,0
EQ BYTE "A equals B",#a,0
GT BYTE "A is greater than B",#a,0
 
LOC #1000
GREG @
// call: p points to the start of a 0-terminated numeric string
// leading chars + and - are allowed
// reg $72 0 if negative int
// reg $73 gen. purpose
// return: reg $70 contains integer value
readInt XOR $70,$70,$70 % reset result reg: N=0.
LDA pp,p % remember &p
LDBU $72,p
CMP $73,$72,'+' % ignore '+'
BZ $73,2F
CMP $72,$72,'-'
BNZ $72,1F
2H INCL p,1
JMP 1F
% repeat
3H CMP $73,$71,'0' % if c < '0' or c > '9'
BN $73,4F % then print err and halt program
CMP $73,$71,'9'
BP $73,4F
SUB $71,$71,'0' % 'extract' number
MUL $70,$70,10
ADD $70,$70,$71 % N = 10 * N + digit
INCL p,1
1H LDBU $71,p % get next digit
PBNZ $71,3B % until end of string
CMP $72,$72,0
BNZ $72,2F % if marked negative
NEG $70,$70 % then make negative
2H GO $127,$127,0 % return (N)
 
4H LDA p,ILLH
TRAP 0,Fputs,StdErr
LDA p,pp
TRAP 0,Fputs,StdErr
LDA p,ILLT
TRAP 0,Fputs,StdErr
TRAP 0,Halt,0
 
// entrance of program
// e.g. ~> mmix compare2ints A B
//
Main CMP p,argc,3 % main (argc, argv) {
BZ p,1F % if argc == 3 then continue
LDA p,ERR % else print wrong number of args
TRAP 0,Fputs,StdErr
TRAP 0,Halt,0
// get ints A and B
1H LDOU p,argv,8 % fetch addres of first int
GO $127,readInt % read int A
ADD A,$70,0
 
LDOU p,argv,16
GO $127,readInt % read int B
ADD B,$70,0
 
// perform comparison
CMP A,A,B % case compare A B
LDA p,LT
BN A,2F % LT: print 'LT'
LDA p,EQ
BZ A,2F % EQ: print 'EQ'
LDA p,GT % _ : print 'GT'
2H TRAP 0,Fputs,StdOut % print result
TRAP 0,Halt,0

Example of use:

~/MIX/MMIX/Progs> mmix compare2ints 121 122
A is less than B

~/MIX/MMIX/Progs> mmix compare2ints 121 121
A equals B

~/MIX/MMIX/Progs> mmix compare2ints 121 120
A is greater than B

~/MIX/MMIX/Progs> mmix compare2ints -121 -122
A is greater than B

~/MIX/MMIX/Progs> mmix compare2ints -121 -121
A equals B

~/MIX/MMIX/Progs> mmix compare2ints -121 -120
A is less than B

[edit] Modula-3

MODULE Main;
 
FROM IO IMPORT Put, GetInt;
FROM Fmt IMPORT Int;
 
VAR a,b: INTEGER;
 
BEGIN
a := GetInt();
b := GetInt();
IF a < b THEN
Put(Int(a) & " is less than " & Int(b) & "\n");
ELSIF a = b THEN
Put(Int(a) & " is equal to " & Int(b) & "\n");
ELSIF a > b THEN
Put(Int(a) & " is greater than " & Int(b) & "\n");
END;
END Main.

[edit] MUMPS

INTCOMP
NEW A,B
INTCOMPREAD
READ !,"Enter an integer to test: ",A
READ !,"Enter another integer: ",B
IF (+A\1'=A)!(+B\1'=B) WRITE !!,"Please enter two integers.",! GOTO INTCOMPREAD
IF A<B WRITE !,A," is less than ",B
IF A=B WRITE !,A," is equal to ",B
IF A>B WRITE !,A," is greater than ",B
KILL A,B
QUIT
Output:
USER>d INTCOMP^ROSETTA
 
Enter an integer to test: 43
Enter another integer: 44
43 is less than 44
USER>d INTCOMP^ROSETTA
 
Enter an integer to test: 44
Enter another integer: 43
44 is greater than 43
USER>d INTCOMP^ROSETTA
 
Enter an integer to test: 2
Enter another integer: 2
2 is equal to 2

[edit] NSIS

[edit] Pure NSIS (Using IntCmp directly)

 
Function IntergerComparison
Push $0
Push $1
StrCpy $0 8
StrCpy $1 2
 
IntCmp $0 $1 Equal Val1Less Val1More
 
Equal:
DetailPrint "$0 = $1"
Goto End
Val1Less:
DetailPrint "$0 < $1"
Goto End
Val1More:
DetailPrint "$0 > $1"
Goto End
End:
 
Pop $1
Pop $0
FunctionEnd
 

[edit] Using LogicLib (bundled library)

Library: LogicLib

 
Function IntegerComparison
Push $0
Push $1
 
StrCpy $0 8
StrCpy $1 2
 
${If} $0 == $1
DetailPrint "$0 = $1"
${ElseIf} $0 < $1
DetailPrint "$0 < $1"
${ElseIf} $0 > $1
DetailPrint "$0 > $1"
${EndIf}
 
Pop $1
Pop $0
FunctionEnd
 

[edit] Oberon-2

MODULE Compare;
 
IMPORT In, Out;
 
VAR a,b: INTEGER;
 
BEGIN
In.Int(a);
In.Int(b);
IF a < b THEN
Out.Int(a,0);
Out.String(" is less than ");
Out.Int(b,0);
Out.Ln;
ELSIF a = b THEN
Out.Int(a,0);
Out.String(" is equal to ");
Out.Int(b,0);
Out.Ln;
ELSIF a > b THEN
Out.Int(a,0);
Out.String(" is greater than ");
Out.Int(b,0);
Out.Ln;
END;
END Compare.

use IO;

[edit] Objeck

 
bundle Default {
class IntCompare {
function : Main(args : String[]) ~ Nil {
a := Console->GetInstance()->ReadString()->ToInt();
b := Console->GetInstance()->ReadString()->ToInt();
 
if (a < b) {
Console->GetInstance()->Print(a)->Print(" is less than ")->PrintLine(b);
};
 
if (a = b) {
Console->GetInstance()->Print(a)->Print(" is equal than ")->PrintLine(b);
};
 
if (a > b) {
Console->GetInstance()->Print(a)->Print(" is greater than ")->PrintLine(b);
};
}
}
}
 

[edit] OCaml

let my_compare a b =
if a < b then "A is less than B"
else if a > b then "A is greater than B"
else if a = b then "A equals B"
else "cannot compare NANs"
 
let () =
let a = read_int ()
and b = read_int () in
print_endline (my_compare a b)

[edit] Octave

printf("Enter a: ");
a = scanf("%d", "C");
printf("Enter b: ");
b = scanf("%d", "C");
if (a > b)
disp("a greater than b");
elseif (a == b)
disp("a equal to b");
elseif (a < b)
disp("a less than b");
endif

[edit] Oz

functor
import
Application(exit)
Open(text file)
define
 
Txt = class from Open.file Open.text end
Stdout = {New Open.file init(name:stdout)}
Stdin = {New Txt init(name:stdin)}
 
proc{Print Msg}
{Stdout write(vs:Msg)}
end
 
fun{GetInt Prompt}
{Print Prompt}
{StringToInt {Stdin getS($)}}
end
 
Int1 = {GetInt "Enter 1st Integer:"}
Int2 = {GetInt "Enter 2nd Integer:"}
 
if(Int1 < Int2) then {Print Int1#" less than "#Int2} end
if(Int1 > Int2) then {Print Int1#" greater than "#Int2} end
if(Int1 == Int2) then {Print Int1#" equal to "#Int2} end
 
{Application.exit 0}
end

[edit] Pascal

program compare(input, output)
 
var
a, b: integer;
 
begin
if (a < b) then writeln(a, ' is less than ', b);
if (a = b) then writeln(a, ' is equal to ', b);
if (a > b) then writeln(a, ' is greater than ', b);
end.

[edit] Perl

Works with: Perl version 5.x

Separate tests for less than, greater than, and equals

sub test_num {
my $f = shift;
my $s = shift;
if ($f < $s){
return -1; # returns -1 if $f is less than $s
} elsif ($f > $s) {
return 1; # returns 1 if $f is greater than $s
} elsif ($f == $s) {
# = operator is an assignment
# == operator is a numeric comparison
return 0; # returns 0 $f is equal to $s
};
};

All three tests in one. If $f is less than $s return -1, greater than return 1, equal to return 0

sub test_num {
return $_[0] <=> $_[1];
};

Note: In Perl, $a and $b are (kind of) reserved identifiers for the built-in sort function. It's good style to use more meaningful names, anyway.

# Get input, test and display
print "Enter two integers: ";
($x, $y) = split ' ', <>;
print $x, (" is less than ", " is equal to ",
" is greater than ")[test_num($x, $y) + 1], $y, "\n";

[edit] Perl 6

Works with: Rakudo version #22 "Thousand Oaks"

my Int $a = floor $*IN.get;
my Int $b = floor $*IN.get;
 
if $a < $b {
say 'Less';
}
elsif $a > $b {
say 'Greater';
}
elsif $a == $b {
say 'Equal';
}

With cmp:

say <Less Equal Greater>[($a cmp $b) + 1];

[edit] PHP

<?php
 
echo "Enter an integer [int1]: ";
fscanf(STDIN, "%d\n", $int1);
if(!is_numeric($int1)) {
echo "Invalid input; terminating.\n";
exit(1); // return w/ general error
}
 
echo "Enter an integer [int2]: ";
fscanf(STDIN, "%d\n", $int2);
if(!is_numeric($int2)) {
echo "Invalid input; terminating.\n";
exit(1); // return w/ general error
}
 
// now $int1 and $int2 are numbers.
// for simplicity, this does not explicitly examine types
 
if($int1 < $int2)
echo "int1 < int2\n";
if($int1 == $int2)
echo "int1 = int2\n";
if($int1 > $int2)
echo "int1 > int2\n";
 
?>

Note that this works from the command-line interface only, whereas PHP is usually executed as wp:Common_Gateway_Interface CGI.

[edit] PicoLisp

(prin "Please enter two values: ")
 
(in NIL # Read from standard input
(let (A (read) B (read))
(prinl
"The first one is "
(cond
((> A B) "greater than")
((= A B) "equal to")
(T "less than") )
" the second." ) ) )

Output:

Please enter two values: 4 3
The first one is greater than the second.

[edit] Pike

int main(int argc, array(int) argv){
if(argc != 3){
write("usage: `pike compare-two-ints.pike <x> <y>` where x and y are integers.\n");
return 0;
}
 
int a = argv[1];
int b = argv[2];
 
if(a > b) {
write(a + " is greater than " + b + "\n");
} else if (a < b) {
write(a + " is less than " + b + "\n");
} else {
write(a + " is equal to " + b + "\n");
}
}

[edit] PL/I

 
declare (a, b) fixed binary;
 
get list (a, b);
if a = b then
put skip list ('The numbers are equal');
if a > b then
put skip list ('The first number is greater than the second');
if a < b then
put skip list ('The second number is greater than the first');
 

[edit] Pop11

;;; Comparison procedure
define compare_integers(x, y);
if x > y then
printf('x is greater than y\n');
elseif x < y then
printf('x is less than y\n');
elseif x = y then
printf('x equals y\n');
endif;
enddefine;
 
;;; Setup token reader
vars itemrep;
incharitem(charin) -> itemrep;
 
;;; Read numbers and call comparison procedure
compare_integers(itemrep(), itemrep());

[edit] PowerShell

$a = [int] (Read-Host a)
$b = [int] (Read-Host b)
 
if ($a -lt $b) {
Write-Host $a is less than $b`.
} elseif ($a -eq $b) {
Write-Host $a is equal to $b`.
} elseif ($a -gt $b) {
Write-Host $a is greater than $b`.
}

[edit] PureBasic

If OpenConsole()  
 
Print("Enter an integer: ")
x.i = Val(Input())
Print("Enter another integer: ")
y.i = Val(Input())
 
If x < y
Print( "The first integer is less than the second integer.")
ElseIf x = y
Print("The first integer is equal to the second integer.")
ElseIf x > y
Print("The first integer is greater than the second integer.")
EndIf
 
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf

[edit] Python

#!/usr/bin/env python
a = int(raw_input('Enter value of a: '))
b = int(raw_input('Enter value of b: '))
 
if a < b:
print 'a is less than b'
elif a > b:
print 'a is greater than b'
elif a == b:
print 'a is equal to b'

(Note: in Python3 raw_input() will become input().).

An alternative implementation could use a Python dictionary to house a small dispatch table to be indexed by the results of the built-in cmp() function. cmp() returns a value suitable for use as a comparison function in a sorting algorithm: -1, 0 or 1 for <, = or > respectively. Thus we could use:

Works with: Python version 2.x

#!/usr/bin/env python
import sys
try:
a = int(raw_input('Enter value of a: '))
b = int(raw_input('Enter value of b: '))
except (ValueError, EnvironmentError), err:
print sys.stderr, "Erroneous input:", err
sys.exit(1)
 
dispatch = {
-1: 'is less than',
0: 'is equal to',
1: 'is greater than'
}
print a, dispatch[cmp(a,b)], b

In this case the use of a dispatch table is silly. However, more generally in Python the use of dispatch dictionaries or tables is often preferable to long chains of elif' clauses in a condition statement. Python's support of classes and functions (including currying, partial function support, and lambda expressions) as first class objects obviates the need for a "case" or "switch" statement.

[edit] R

print("insert number a")
a <- scan(what=numeric(0), nmax=1)
print("insert number b")
b <- scan(what=numeric(0), nmax=1)
if ( a < b ) {
print("a is less than b")
} else if ( a > b ) {
print("a is greater than b")
} else if ( a == b ) { # could be simply else of course...
print("a and b are the same")
}


[edit] REBOL

 
rebol [
Title: "Comparing Two Integers"
Author: oofoe
Date: 2009-12-04
URL: http://rosettacode.org/wiki/Comparing_two_integers
]

 
a: ask "First integer? " b: ask "Second integer? "
 
relation: [
a < b "less than"
a = b "equal to"
a > b "greater than"
]
print [a "is" case relation b]
 

[edit] REXX

say 'Enter value of a:'
pull a
say 'Enter value of b:'
pull b
 
if a < b then
say 'a is less than b'
if a > b then
say 'a is greater than b'
if a = b then
say 'a is equal to b'

[edit] Ruby

Gets is used to get input from the STDIN and 'to_i' is used to convert the string into an integer. This is not explicitly necessary, since strings will be compared correctly too. If two strings are entered they will be considered equal using this method.

a = gets( "enter a value for a: ").to_i
b = gets( "enter a value for b: ").to_i
 
print "a is less than b" if a < b
print "a is greater than b" if a > b
print "a is equal to b" if a == b

An alternative method, which is similar to the python version mentioned above (at the time of writing this) is:

# Function to make prompts nice and simple to abuse
def prompt str
print str, ": "
gets.chomp
end
 
# Get value of a
a = prompt('Enter value of a').to_i
# Get value of b
b = prompt('Enter value of b').to_i
 
# The dispatch hash uses the <=> operator
# When doing x<=>y:
# -1 means x is less than y
# 0 means x is equal to y
# 1 means x is greater than y
dispatch = {
-1 => "less than",
0 => "equal to",
1 => "greater than"
}
 
# I hope you can figure this out
puts "#{a} is #{dispatch[a<=>b]} #{b}"

[edit] Scheme

(define (my-compare a b)
(cond ((< a b) "A is less than B")
((> a b) "A is greater than B")
((= a b) "A equals B")))
 
(my-compare (read) (read))

[edit] Slate

[ |:a :b |
 
( a > b ) ifTrue: [ inform: 'a greater than b\n' ].
( a < b ) ifTrue: [ inform: 'a less than b\n' ].
( a = b ) ifTrue: [ inform: 'a is equal to b\n' ].
 
] applyTo: {Integer readFrom: (query: 'Enter a: '). Integer readFrom: (query: 'Enter b: ')}.

[edit] Smalltalk

| a b |
'a = ' display. a := (stdin nextLine asInteger).
'b = ' display. b := (stdin nextLine asInteger).
( a > b ) ifTrue: [ 'a greater than b' displayNl ].
( a < b ) ifTrue: [ 'a less than b' displayNl ].
( a = b ) ifTrue: [ 'a is equal to b' displayNl ].

[edit] SNOBOL4

Comparisons in Snobol are not operators, but predicate functions that return a null string and generate a success or failure value which allows or blocks statement execution, and which can be tested for branching. Other numeric comparisons are ge (>=), le (<=) and ne (!= ). There is also a parallel set of L-prefixed predicates in modern Snobols for lexical string comparison.

*       # Get user input        
output = 'Enter X,Y:'
trim(input) break(',') . x ',' rem . y
 
output = lt(x,y) x ' is less than ' y :s(end)
output = eq(x,y) x ' is equal to ' y :s(end)
output = gt(x,y) x ' is greater than ' y
end

[edit] SNUSP

There are no built-in comparison operators, but you can (destructively) check which of two adjacent cells is most positive.

++++>++++ a b !/?\<?\#  a=b
> - \# a>b
- <
a<b #\?/

[edit] Standard ML

fun compare_integers(a, b) =
if a < b then print "A is less than B\n"
if a > b then print "A is greater than B\n"
if a = b then print "A equals B\n"
 
fun test () =
let
open TextIO
val SOME a = Int.fromString (input stdIn)
val SOME b = Int.fromString (input stdIn)
in
compare_integers (a, b)
end
handle Bind => print "Invalid number entered!\n"

A more idiomatic and less error-prone way to do it in SML would be to use a compare function that returns type order, which is either LESS, GREATER, or EQUAL:

fun myCompare (a, b) = case Int.compare (a, b) of
LESS => "A is less than B"
| GREATER => "A is greater than B"
| EQUAL => "A equals B"

[edit] Tcl

This is not how one would write this in Tcl, but for the sake of clarity:

puts "Please enter two numbers:"
 
gets stdin x
gets stdin y
 
if { $x > $y } { puts "$x is greater than $y" }
if { $x < $y } { puts "$x is less than $y" }
if { $x == $y } { puts "$x equals $y" }

Other comparison operators are "<=", ">=" and "!=".

Note that Tcl doesn't really have a notion of a variable "type" - all variables are just strings of bytes and notions like "integer" only ever enter at interpretation time. Thus the above code will work correctly for "5" and "6", but "5" and "5.5" will also be compared correctly. It will not be an error to enter "hello" for one of the numbers ("hello" is greater than any integer). If this is a problem, the type can be expressly cast

if {int($x) > int($y)} { puts "$x is greater than $y" }

or otherwise type can be checked with "if { string is integer $x }..."

Note that there is no substitution/evaluation here anywhere: entering "3*5" and "15" will parse "3*5" as a non-numerical string (like "hello") and thus the result will be "3*5 is greater than 15".

A variant that iterates over comparison operators, demonstrated in an interactive tclsh:

% set i 5;set j 6
% foreach {o s} {< "less than" > "greater than" == equal} {if [list $i $o $j] {puts "$i is $s $j"}}
5 is less than 6
% set j 5
% foreach {o s} {< "less than" > "greater than" == equal} {if [list $i $o $j] {puts "$i is $s $j"}}
5 is equal 5
% set j 4
% foreach {o s} {< "less than" > "greater than" == equal} {if [list $i $o $j] {puts "$i is $s $j"}}
5 is greater than 4

[edit] TI-89 BASIC

Local a, b, result
Prompt a, b
If a < b Then
"<" → result
ElseIf a = b Then
"=" → result
ElseIf a > b Then
">" → result
Else
"???" → result
EndIf
Disp string(a) & " " & result & " " & string(b)

[edit] Toka

[ ( a b -- )
2dup < [ ." a is less than b\n" ] ifTrue
2dup > [ ." a is greater than b\n" ] ifTrue
= [ ." a is equal to b\n" ] ifTrue
] is compare-integers
 
1 1 compare-integers
2 1 compare-integers
1 2 compare-integers

[edit] V

[compare
[ [>] ['less than' puts]
[<] ['greater than' puts]
[=] ['is equal' puts]
] when].
 
|2 3 compare
greater than
|3 2 compare
less than
|2 2 compare
is equal

[edit] VBScript

Based on the BASIC

[edit] Implementation
 
option explicit
 
function eef( b, r1, r2 )
if b then
eef = r1
else
eef = r2
end if
end function
 
dim a, b
wscript.stdout.write "First integer: "
a = cint(wscript.stdin.readline) 'force to integer

wscript.stdout.write "Second integer: "
b = cint(wscript.stdin.readline) 'force to integer

wscript.stdout.write "First integer is "
if a < b then wscript.stdout.write "less than "
if a = b then wscript.stdout.write "equal to "
if a > b then wscript.stdout.write "greater than "
wscript.echo "Second integer."
 
wscript.stdout.write "First integer is " & _
eef( a < b, "less than ", _
eef( a = b, "equal to ", _
eef( a > b, "greater than ", vbnullstring ) ) ) & "Second integer."
 

[edit] Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

Sub Main()
 
Dim a = CInt(Console.ReadLine)
Dim b = CInt(Console.ReadLine)
 
'Using if statements
If a < b Then Console.WriteLine("a is less than b")
If a = b Then Console.WriteLine("a equals b")
If a > b Then Console.WriteLine("a is greater than b")
 
'Using Case
Select Case a
Case Is < b
Console.WriteLine("a is less than b")
Case b
Console.WriteLine("a equals b")
Case Is > b
Console.WriteLine("a is greater than b")
End Select
 
End Sub

[edit] XSLT

Because XSLT uses XML syntax, the less than and greater than operators which would normally be written '<' and '>' must be escaped using character entities, even inside of XPath expressions.

<xsl:template name="compare">
<xsl:param name="a" select="1"/>
<xsl:param name="b" select="2"/>
<fo:block>
<xsl:choose>
<xsl:when test="$a &lt; $b">a &lt; b</xsl:when>
<xsl:when test="$a &gt; $b">a &gt; b</xsl:when>
<xsl:when test="$a = $b">a = b</xsl:when>
</xsl:choose>
</fo:block>
</xsl:template>
Personal tools
Support