Loops are used to execute a sequence of instructions repeatedly. In order to exit from a loop, we must have a method for checking to see if we have completed our task. The testing of a boolean expression in a while-do or repeat-until statement provides this capability.
The if statement permits the optional execution of simple or compound statements and has the following form, or syntax, for one of its variants:
if expression then
statement
The boolean expression is checked for veracity. If it is found to be true, then the operation is performed; if it is false, then the operation is skipped. In order to test a condition, a set of six operators is provided in Pascal.
Relational operators are used to check on the current condition or situation. The condition to be tested is evaluated and a response of either true or false is returned. Below are the six relational operators used in Pascal, along with the sentence to be tested.
| = | The left side is EQUAL to the right side. |
| > | The left side is GREATER THAN the right side. |
| < | The left side is LESS THAN the right side. |
| <> | The left side is NOT EQUAL to the right side. |
| >= | The left side is GREATER THAN or EQUAL to the right side. |
| <= | The left side is LESS THAN or EQUAL to the right side. |
The following code segments illustrate how conditionals can be used to exit from loops and print messages to the user.
{ Calculate the sum of the first five Natural numbers }
naturalnum := 1;
total := 0;
repeat
total := total + naturalnum;
naturalnum := naturalnum + 1
until naturalnum > 5
{ Get a value from the user; accept only a number less than or equal to ten }
repeat
write('Type a number less than or equal to 10 and hit RETURN: ');
readln(num);
if num > 10 then
writeln('Your number is too big!')
until num <= 10