Unit 3.3 Nesting If Statements, Maximum of Three Numbers

PROG

Take the maximum of three numbers--read in from screen

PED

To see nesting of if statements

To see our first stepwise-refinement

CONCEPT

If statements can appear in the begin-end pairs

PSEUDOCODE

IF A is not the maximum
set MAX to be the maximum of B and C
ELSE
IF B is not the maximum
set MAX to the be the maximum of A and C
END



Unit 3.3 Nesting of if's the maximum of three numbers

Click here to view Unit 3.3 Pascal program.

In the last unit, we saw a simple if statement with only a single statement between the begin-end pairs.

We can put several statements, separated by semicolons, between the begin-end pairs. This is called a compound statement.

More interestingly, we can put one if statement between the begin-end pair of another. We say that the if statement between the begin-end pair of the second is nested in the first.

In our example, we look at taking the maximum of three numbers and use the nesting concept. If we entered 3,7 and 2, the program should output 7, the largest of these three numbers.

We look at this problem the same way we would pair off people in a competition to determine who was the better player. We pair off the first two numbers. If the second is largest, then it gets to compete with the remaining number to see which is the maximum. If when we pair the first and second, it turns out that the first was the larger number, then it gets to compete with the third. We know that the second is not the best player of the three if it is beaten by the first in the first competition.

We write what is pseudocode for this which helps us understand what is going on. You see that on your transparency. Then we replace the English such as "A is not the maximum" by PASCAL in the program. This helps us think about the program. Computer scientists call this method of making our programming easier, stepwise refinement.

As we see from the pseudocode, the first part of the if-statement checks to see if A is not the maximum. On line 10, we see that if A<=B, then the code from lines 11 to 17 will be executed. This code will "set MAX to the maximum of B and C." We hav eliminated A as a possible candidate. We have to look at B and C.
Lines 11 to 17 set MAX to the maximum of b and c. We already know how to take the maximum of two numbers--that was discussed in unit 3.2. We simply take the maximum of B and C in these lines.

Line 20 will test to see if "B is not the maximum." If A is greater than B, we know that whatever the maximum is, it is not B. Lines 21 to 28 then let A and C fight it out, and computes the maximum of these two.

Line 29 outputs the final result in max.