Comparing two integers
From Rosetta Code
Programming Task
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they 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.
[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
main: (
INT a, b;
readf(($g" "gl$, a, b));
IF a < b THEN
printf(($g" is less than "gl$, a, b))
ELIF a = b THEN
printf(($g" is equal to "gl$, a, b))
ELIF a > b THEN
printf(($g" is greater than "gl$, a, b))
FI
)
[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))
((eq 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))
((eq 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>
int main()
{
int a, b;
std::cin >> a >> b;
// test for less-than
if (a < b)
std::cout << a << " is less than " << b << std::endl;
// test for equality
if (a == b)
std::cout << a << " is equal to " << b << std::endl;
// test for greater-than
if (a > b)
std::cout << a << " is greater than " << b << std::endl;
return 0;
}
[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] 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 greather 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] 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
[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=: 4 : 0
select =. ([:I.[) { ]
English =. (<' is less than '),(<' is equal to '),<' is greater than '
asText =. ;@(":&.>"_)
x (asText@( (<@[), (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
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);
}
[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] 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] 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] 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] 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.
[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 CGI.
[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] 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'
[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
[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] 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"
[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".
[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] Visual Basic .NET
Platform: .NET
Works with: Visual Basic .NET version 9.0+
Sub Main()
Dim a = 1
Dim b = 2
'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
Categories: Programming Tasks | Basic Data Operations | Arithmetic operations | Ada | ALGOL 68 | AWK | BASIC | Befunge | Common Lisp | C | C++ | Clean | D | Forth | Fortran | Haskell | J | Java | JavaScript | Korn Shell | Logo | LSE64 | MAXScript | OCaml | Oz | Pascal | Perl | PHP | Pop11 | Python | Ruby | Scheme | SNUSP | Standard ML | Tcl | Toka | Visual Basic .NET

