If Statements

An if statement allows selection. There are two forms of if statement: if ... then and if ... then... else. In the first form, a group of statements may be executed or ignored, depending on the truth value following the if. In the second form, one of two alternative groups of statements will be executed. The following program has three if ... then forms of the statement followed by an if ... then ... else form. Note that there is no semicolon after the end preceding else because if ... then ... else is considered to be a single statement.

program Addition;
{$APPTYPE CONSOLE}
uses
  SysUtils;
var
  Num1, Num2, Sum, Answer: Integer;
begin
  write('Please enter your first whole number: ');
  readln(Num1);
  write('Please enter your second whole number: ');
  readln(Num2);
  Sum := Num1 + Num2;
  write('What is the sum? ');
  readln(Answer);
  if Answer > Sum then
    begin
      write('Your answer is too big.  Try again. ');
    end;
  if Answer < Sum then
    begin
      write('Your answer is too small.  Try again. ');
    end;
  if Answer <> Sum then
    begin
      readln(Answer);
      writeln('This is your second attempt.');
    end;
  if Answer = Sum then
    begin
      writeln('You are correct!');
      writeln('Well done!');
    end
  else
    begin
      writeln('You are wrong!');
      writeln('The sum is ', Sum, '.');
    end;
  readln;
end.

See program SUVAT for extensive use of if statements. You should be able to understand the code (if you have been working through the tutorials in order) with this added knowledge;

  • sleep(500) means "wait for 500 ms (0.5 s)";
  • the value of Sqr(T) is the square of the value of T.
Features introduced:
  • if ... then (three examples)
  • if ... then... else
  • The use of >, < and <> to test for greater than, less than and not equal to, respectively
  • The use of = (not :=) to test for equality
  • The end before else must not have a semicolon after it
Programming - a skill for life!

How to use if and case statements