Lecture 8: Branching I (if ... then ... else) |
Until now, all the instructions that were put within the program were
executed. Moreover, they were executed exactly in the order that they were
placed. The first line of the program was executed first, then the second,
then the third, and so on. This is not always the case. With branching
(a branch is a part of a tree) we can control the flow of the program.
Imagine a program that specifies a number and the computer will calculate
the square-root of the number. Taking the square-root of a negative number
doesn't make sense (unless you are working with complex numbers, off course),
so you would like your program to generate an error and stop when the user
enters a negative number. You want text like
Negative numbers are not allowed! to appear on the screen. Obviously, you do not always want this text to appear on the screen; in case the user enters a positive number you just want the square-root to be calculated and appear on the screen: The square-root of 5 is 2.23607 You would like to have some way to check the number and depending on this result, execute parts of the program. |
The simplest way to have a control over the instructions that will
be executed is with the statement if .. then. The full syntax of the statement
is
For condition we will substitute
our condition and for instruction
we will put our instruction(s) that will be executed if and only if the
condition was true.
|
The normal execution of the program will resume after the block of instructions.
In the following example, instruction3 and instruction4
will be executed, regardless of the condition (a = b).
if (a = b) then
begin instruction1; instruction2; end; instruction3; instruction4; |
|
Note that here the analogy with branching in trees stops. In a tree,
the branches never meet again; once we are on a branch, it is never again
possible to join the main trunk.
If we also want to program to do things in case the condition is not
true we can do this with if ... then ... else statement. The general form
of this instruction is
Note the peculiarity of PASCAL: the instruction immediately before else is not terminated with ; example:
|
PROGRAM SquareRoot;
Var x: real;
root:
real;
begin
writeln('Give a number');
readln(x);
if (x<0) then
writeln('Negative numbers
are not allowed!')
else
begin
root := Sqrt(x);
writeln('The
square-root of ', x:0:4, ' is ', root:0:4);
end;
writeln('Have a nice day');
end.
Running the program; two examples:
Give a number
3.68 The square-root of 3.6800 is 1.9183 Have a nice day |
Give a number
-3.68 Negative numbers are not allowed! Have a nice day |