This series of programs illustrates the decision making using the IF-
THEN command. We start with a simple program and add more
decisions to it. The last example shows how a program can be written
in parts called procedures. If you wanted to write the last program in
this set it might be a very good idea to write the first program first
and then add more abilities just as I did. The sooner you get running
code the easier it will be to find your errors (because you will have
less code to look at.)
This is the simplest decision case. If the condition in the IF-THEN
statement is true then the writeln following the THEN is done.
Otherwise (i.e. the condition is false) this statement is skipped.
Run the program for prices above 10 and below 10. What happens
when the price is exactly 10? Notice that you can only enter whole
dollar amounts -- no decimal point is allowed. This is because the
number that you enter must be stored in a space that holds integers
This modification of the first program illustrates the IF-THEN-ELSE
combination of statements. That is, one writeln is done if and only if the
condition is true and the other is done if and only if the condition is false.
Again, run the program with different values.
In this example we add another IF-THEN-ELSE so that one of three
alternatives is selected.
Try to run this with different values. What happens if you change
value of cash so that it is more than 100? What happens if you change the
initial value of CreditBalance so that it is less than 10? Predict and
then try it.
This program adds lots more comments of the type that a good program
should have. In many examples my comments are aimed at you, the
student and would not be appropriate in a real program. In a real
program the comments should explain the logic but you should assume
that anyone who reads the program knows what the statements do. I
have also used BEGIN-END blocks to be able to do more than one
statement when an IF-THEN is true.
Can you add more statements to the BEGIN-END blocks? How about
making a BEGIN-END block after the final else?
This last example is a lot harder to understand at first, but it actually
illustrates a method of making big programs simpler. I have taken the
same code in the example just above this and I have broken it into
pieces called PROCEDURES. To read a program that has procedures you
have to find the main program which is always at the end of the
program. The program always starts at main. When you find a
procedure name instead of a statement, go to that procedure -- do what
it says -- then come back to main.
After you have looked at this example see if you can take the code from
the example above and divide it into procedures. At first make just one
procedure and test to see that the program runs. Then make more
testing each time.
Rules for writing Pascal statements
General Index to Sample Programs