MacharSoft UniCOMAL FAQs - Complex Conditions

Complex Conditions

A "complex condition" contains two or more simple conditions linked by logic operators (AND and OR), like this:-

   IF score1>50 AND score2>50 THEN
      PRINT "You passed both the tests."
   ENDIF

Complex conditions are used in IF statements, CASE statements, WHILE loops and REPEAT...UNTIL loops in UniCOMAL.

AND or OR? - a user's problem

Usually, statements like this are fairly easy to read and understand. Sometimes, however, things are not quite so straightforward. A user recently sent us a problem like this:

   INPUT "Type 'C' to continue ":keypress$
   WHILE keypress$<>"c" OR keypress$<>"C" DO
      PRINT "Only the 'c' key works, sorry!"
      INPUT "Type 'c' to continue ":keypress$
   ENDWHILE

The intention was to validate the keypress and produce a section of code which would only allow the user to proceed if the user entered either lower-case "c" or upper-case "C". It doesn't work as shown above, because in this case the logic operator has to be AND rather than OR:

   WHILE keypress$<>"c" AND keypress$<>"C" DO

Why? Make sure you know about how AND and OR work (you might want to review the logic truth tables for AND and OR), then look at this hand-run of the original condition:

   keypress$        "C"    - user types upper-case 'C'
   keypress$<>"c"   TRUE
   OR
   keypress$<>"C"   FALSE
   whole condition  TRUE OR FALSE = TRUE

As you can see, the whole WHILE condition succeeds, so the program has to enter the loop, display the error message, and prompt the user for a new keypress, even though the user has entered the letter 'c' as the program requested. Very frustrating for the user and the programmer alike!

Now look at the AND condition:

   keypress$        "C"
   keypress$<>"c"   TRUE
   AND
   keypress$<>"C"   FALSE
   whole condition  TRUE AND FALSE = FALSE

This time, the WHILE conditions fails, so the program does not enter the loop, and lets the user proceed as planned.

An alternative method

Here is a rather different, simpler, way to validate a keypress. This method uses the UniCOMAL 'IN' function which tests for the presence of one string inside another string, and returns the character position of the first string if it is found, or 0 (FALSE) if it isn't.

   INPUT "Please type 'C' to continue: ":keypress$
   WHILE NOT keypress$ IN "Cc" DO
      PRINT "Only the 'C' key works, sorry!"
      INPUT "Please type 'C' to continue: ":keypress$
   ENDWHILE

Truth tables for logical AND and logical OR:

    AND |  TRUE  FALSE |          OR |  TRUE  FALSE |
  ------+--------------+       ------+--------------+ 
   TRUE |  TRUE  FALSE |        TRUE |  TRUE   TRUE |
  FALSE | FALSE  FALSE |       FALSE |  TRUE  FALSE |
  ------+--------------+       ------+--------------+


Uploaded 10 Nov 2001