Integer comparison: Difference between revisions

From Rosetta Code
Content added Content deleted
m (re-alphabetise)
(-> Tcl)
Line 218: Line 218:
end
end
handle Bind => print "Invalid number entered!\n"
handle Bind => print "Invalid number entered!\n"

==[[Tcl]]==
[[Category: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 [[IsNumeric | type can be checked]] with "<tt>if { string is integer $x }...</tt>"

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


==[[Toka]]==
==[[Toka]]==

Revision as of 22:07, 28 May 2007

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:

Integer Operations
Arithmetic | Comparison

Boolean Operations
Bitwise | Logical

String Operations
Concatenation | Interpolation | Comparison | Matching

Memory Operations
Pointers & references | Addresses

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.

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;

C++

#include <iostream>
#include <istream>
#include <ostream>

int main()
{
  int a, b;
  std::cin >> a >> b;

  // test for less-than
  if (a < b)
    std::cout << a << " is less than " << b << "\n";

  // test for equality
  if (a == b)
    std::cout << a << " is equal to " << b << "\n";

  // test for greater-than
  if (a > b)
    std::cout << a << " is greater than " << b << "\n";
}

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

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) { }
       }
} 

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 ;

Fortran

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

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.

Perl

Interpreter: Perl 5.x

Seperate tests for less than, greater than, and equals

sub test_num($ $){
  my ($f, $s) = @_;
  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){ # note = is a set, == is a test
    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($ $){
  my ($f, $s) = @_;
  return($f <=> $s);
}

Note in perl, $a and $b are reserved variable names, used in conjunction with the sort() function.

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());

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'

Standard ML

This example is incorrect. It does not accomplish the given task. Please fix the code and remove this message.
fun compare_integers(a, b) =
  if a < b then print "A is less than B\n"
  else if a > b then print "A is greater than B\n"
  else 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"

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

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