IF statements
A lot of times, we need to make decisions. IF statements are one of those tools.
If a condition is true, then a certain action is done. We can also assign an
alternate action for the condition.
Example :
program tutorial4;
var
num1, num2: integer;
begin
writeln('Type an integer in, please.');
readln(num1);
writeln('Type another integer in, please.');
readln(num2);
writeln;
if num1 > num2 then
writeln(num1, ' is greater than ', num2, '.')
else
writeln(num1, ' is not greater than ', num2, '.');
end.
We made a decision based on the size of the two numbers and
wrote the result of that decision.
You can use any of the following symbols :
Equal to is =
Not equals is <> in pascal.
Greater than or equal to is >= in pascal.
Less than or equal to is <= in pascal.
It is important to remember that if you have more than one statement inside an if or else statement, you must surround them with Begin and End statements. Make sure not to put a period after the End statement, only a semi colin if appropriate.
Also note that no semi colin is necessary on the statement right befor an Else.
Another Example :
program tutorial5;
var
one, two: integer;
option: char;
begin
writeln('Enter an integer.');
readln(one);
writeln('Enter another integer.');
readln(two);
writeln('Use a mathematical symbol (+, -, *, or /) to indicate what you want to do');
writeln('with these two numbers.');
readln(option);
if option = '+' then
begin
writeln(one, ' + ', two, ' = ', one + two, '.');
writeln('See, I can add.');
end
else
if option = '-' then
writeln(one, ' - ', two, ' = ', one - two, '.')
else
if option = '*' then
writeln(one, ' * ', two, ' = ', one * two, '.')
else
if option = '/' then
writeln(one, ' / ', two, ' = ', one / two :0:3, '.')
{ we want to have the decimal point, so we MUST have the
first one as well to be set to 0. }
else
writeln('Use +, -, *, or / as your operator. Try again.');
end.
We 'nest' as many ifs as we want, although it is best to minimize it
as much as possible. Also, keep in mind, we can use AND or OR to
multiply conditions. Say, on the division, if we wanted to only honor a
division if the first number was greater than the second number For that
section of code...