CSCI 150, Spring 2003
Home | | Course Schedule | | Assignments | | Lecture Notes
Programming Decision Trees
In Pascal, a decision is made using the if ... then ... else statement (also called a
conditional statement).
Example:
program Diagnose;
var
answer: string;
begin
writeln('Does your head ache?');
readln(answer);
if answer = 'yes' then
begin
writeln('Take two aspirin');
end
else
begin
writeln('Good!');
end;
end;
General form of if ... then ... else:
if Condition then begin Pascal Code A end else begin Pascal Code B end;
Other types of conditions:
Conditions can be any expression that has a value of true or false.
Example:
program Compare;
var
x, y: integer;
begin
writeln('Enter two integers');
readln(x);
readln(y);
if x > y then
begin
writeln(x, ' is greater than ', y);
end
else
begin
writeln(y, ' is greater than ', x);
end;
end.
Programming Three way Decision Trees
We can program a three-way decision by adding an else if ... to the if ... then ... else
statement.
Example:
program medals;
var
answer: string;
begin
writeln('Did you get first, second or third?');
readln(answer);
if answer = 'first' then
begin
writeln('You get the gold medal!');
end
else if answer = 'second' then
begin
writeln('You get the silver medal.');
end
else
begin
writeln('You get the bronze medal.');
end;
end.
Note that the second condition is tested in the else if clause in the middle.
If statements within other if statements (Nested Conditionals):
When a decision tree has several decision nodes along a single branch, this requires
another if statement within the original if statement. This is called a nested
conditional.
Example:
program skiSlopes; var skiAnswer, downHill : string; begin writeln('Do you like to ski?'); readln(skiAnswer); if skiAnswer = 'yes' then begin writeln('Downhill or cross country?'); readln(downHill); if downHill = 'downhill' then begin writeln('Try Wachusett Mountain'); end else begin writeln('Try the local trails'); end; end else begin writeln('That is too bad!'); end; end.