-- Inputs 2 numbers in range 0 .. 999 and prints whether they are reverse of each other
-- Demonstrates declaring and calling functions
-- Functions are equivalent to methods with a non-void return type (eg int sqrt(int i))
-- Functions are used as values!
with ada.text_io; use ada.text_io;
with ada.integer_text_io; use ada.integer_text_io;
procedure func1 is
subtype Digit is Natural range 0 .. 9;
subtype Small_Nat is Natural range 0 .. 999;
-- Functions and procedures are declared and defined in the declaration section
function ones_dig(n: Small_Nat) return Digit is
begin
return n mod 10;
end ones_dig;
function tens_dig(n: Small_Nat) return Digit is
temp: constant Small_Nat range 0 .. 99 := n / 10;
begin
return temp mod 10;
end tens_dig;
function hundreds_dig(n: Small_Nat) return Digit is
temp: constant Small_Nat := n / 100;
begin
return temp;
end hundreds_dig;
function eq_rev(n1, n2: Small_Nat) return Boolean is
eq1, eq10, eq100: Boolean;
begin
eq1 := ones_dig(n1) = hundreds_dig(n2);
eq10 := tens_dig(n1) = tens_dig(n2);
eq100 := hundreds_dig(n1) = ones_dig(n2);
return eq1 and eq10 and eq100;
end eq_rev;
s1, s2: Small_Nat;
begin
get(s1);
get(s2);
if eq_rev(s1, s2) then -- How could you improve this if?
put_line(s1'img & " and " & s2'img & " are THE SAME in reverse");
else
put_line(s1'img & " and " & s2'img & " are DIFFERENT in reverse");
end if;
exception
when constraint_error => put_line("Value out of range");
when others => put_line("Error occurred");
end func1;
-- Input: 123 321
-- Output: 123 and 321 are THE SAME in reverse
-- Input: 123 123
-- Output: 123 and 123 are DIFFERENT in reverse