PROG
take the maximum of three numbers--read in from screen
PED
to see the use of and's and or's
CONCEPT
(condition1) and (condition2) will be true if both condition1 and condition2 are true
(condition1) or (condition2) will be true if either condition1 or condition2 are true
PSEUDOCODE
IF A is the maximum
set MAX to A
ELSE
IF B is the maximum
set MAX to B
END
ELSE
IF C is the maximum
set MAX to C
END
We learn in this condition, the combining of conditions with "and" and "or" condition, I mean something that is true or false such as A<B
If we want to execute some code when two conditions are both true, we write
if (condition1) and (condition2) then begin
statements to be executed if both conditions are true
end;
Note the required parentheses around condition1 and condition2.
(condition1) and (condition2) becomes one big condition which will be true if both are true.
We can write this as a truth table.
| condition1 | condition2 | condition1 and
condition2 |
if (condition1) or (condition2) then begin
statements to be executed if neither condition is true
end;
Note the required parentheses around condition1 and condition2.
Again, we can write this as a truth table.
| condition1 | condition2 | condition1 or condition2 | |||||||||
| T | T
| T | F | T
| F | T | T
| F | F | F
| |
((condition1) or (condition2))and(condition3)
((condition1) and (condition2))or(condition3)
((condition1) and (condition2) and (condition3))or((condition4) and
((condition5) or (condition6)))
Now we look at our exercise. We are again trying to take the maximum of three numbers. However, we approach it a different way.
We realize that the three fundamental alternatives are:
1. the first number is the maximum 2. the second number is the maximum 3. the third number is the maximumWe then thing about the definition of the maximum--a number is the maximum of a set if it larger than each one of them individually.
Thus 1) corresponds to (A>=B) and (A>=C).
2) corresponds to (B>=A) and (B>=C)
3) corresponds to (C>=A) and (C>=B)
Note that line 11 checks that A is bigger than both B and C as per 1 and if so, line 12 will set MAX to A.
Line 15 checks that B is bigger than both A and C and if so, it will set MAX to B.
And Line 19 checks that C is bigger than both B and A and if so, it will set MAX to C.