If Else in Ada

Branching with if and else in Ada is straightforward.

with Ada.Text_IO; use Ada.Text_IO;

procedure If_Else is
begin
   -- Here's a basic example.
   if 7 mod 2 = 0 then
      Put_Line("7 is even");
   else
      Put_Line("7 is odd");
   end if;

   -- You can have an if statement without an else.
   if 8 mod 4 = 0 then
      Put_Line("8 is divisible by 4");
   end if;

   -- Logical operators like and and or are often useful in conditions.
   if 8 mod 2 = 0 or 7 mod 2 = 0 then
      Put_Line("either 8 or 7 are even");
   end if;

   -- A declaration can precede conditionals; any variables
   -- declared in this statement are available in the current
   -- and all subsequent branches.
   declare
      Num : Integer := 9;
   begin
      if Num < 0 then
         Put_Line(Integer'Image(Num) & " is negative");
      elsif Num < 10 then
         Put_Line(Integer'Image(Num) & " has 1 digit");
      else
         Put_Line(Integer'Image(Num) & " has multiple digits");
      end if;
   end;
end If_Else;

To run the program, save it as if_else.adb and use the Ada compiler:

$ gnatmake if_else.adb
$ ./if_else
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in Ada, you don’t need parentheses around conditions, but the then keyword is required. The end if; is used to close an if statement.

Ada uses elsif for else-if conditions, and the and and or keywords for logical operators instead of symbols.

Ada doesn’t have a ternary operator, so you’ll need to use a full if statement even for basic conditions.