Learn to Program using Alice

Relational and Logical Operators

You learned about two of Alice's relational and logical operators in an earlier lesson.  You will learn about the remaining seven relational and logical operators in this lesson.  You will also learn some of the theory behind relational and logical expressions as well as a little about De Morgan's law in this lesson.

Published:  April 10, 2007
Last updated:  April 25, 2007
By Richard G. Baldwin

Alice Programming Notes # 170


Preface

This tutorial lesson is part of a series designed to teach you how to program using the Alice programming environment under the assumption that you have no prior programming knowledge or experience.

Have some fun

Because Alice is an interactive graphics 3D programming environment, it is not only useful for learning how to program, Alice makes learning to program fun.  Therefore, you should be sure to explore the many possibilities for being creative provided by Alice while you are learning to program using these tutorials.  And above all have fun in the process of learning.

General

In the previous lesson titled "Sequence, Selection, and Loop Structures" (see Resources), I taught you about:

In the lesson titled "Expressions and Operators" (see Resources), I taught you about the equality operators:

  1. Equal to:  ==
  2. Not equal to:  !=

Seven more relational and logical operators

In this lesson, I will teach you about the following operators:

  1. Less than:  <
  2. Greater than:  >
  3. Less than or equal to:  <=
  4. Greater than or equal to:  >=
  5. Logical AND:  &&
  6. Logical inclusive OR:  ||
  7. Logical NEGATION:  !

The backbone of programming logic

To summarize, you learned about two of Alice's relational and logical operators in an earlier lesson.  You will learn about the remaining seven relational and logical operators in this lesson.  You will also learn some of the theory behind relational and logical expressions, as well as a little about De Morgan's law in this lesson.

Relational and logical operators, when combined with selection and loop structures form the backbone of programming logic, which is basically the thing that separates a computer from more mundane programmable devices such as VCR recorders.

Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.

Figures

Listings

Supplementary material

Once you have mastered Alice, I recommend that you also study the other lessons in my extensive collection of online programming tutorials.  You will find a consolidated index at www.DickBaldwin.com.

General background information

This lesson deals with two related but different topics:

Relational expressions and combinational logic are often combined to provide the programming logic required to accomplish the desired goal of a program.  Operators 1 through 4 in the above list are relational operators.  Operators 5 through 7 in the list are combinational logic operators.

Relational expressions

Relational operators are used to create relational expressions.  The evaluation rules regarding relational expressions are given below.  Assume that A and B are numeric variables or expressions that evaluate to numeric values.

A < B

The expression (A < B) will evaluate to true if A is algebraically less than B, and will return false otherwise.

A > B

The expression (A > B) will evaluate to true if A is algebraically greater than B, and will evaluate to false otherwise.

A <= B

The expression (A <= B) will evaluate to true if A is algebraically less than or is equal to B, and will evaluate to false otherwise.

A >= B

The expression (A >= B) will evaluate to true if A is algebraically greater than or is equal to B, and will evaluate to false otherwise.

A == B

The expression (A == B) will evaluate to true if A is equal to B, and will evaluate to false otherwise.

A != B

The expression (A != B) will evaluate to true if A is not equal to B, and will evaluate to false otherwise.

Combinational logic

Logic operators are used to create combinational logic expressions.  The evaluation rules regarding combinational logic expressions are given below.  Assume that X and Y are Boolean variables or expressions that evaluate to the Boolean values of true and false.

The logical AND operator (&&)

The expression (X && Y) will evaluate to true if both X and Y are true, and will evaluate to false otherwise.

Exclusive OR
There is also a logic expression called an exclusive OR, but it is beyond the scope of this lesson.

The logical inclusive OR operator (||)

The expression (X || Y) will evaluate to true if either X or Y is true, and will evaluate to false otherwise.

Don't confuse the symbols
Don't confuse the symbol for the NOT operator, which is an exclamation mark, with the symbol for the inclusive OR operator, which is a pair of vertical bar characters.  Sometimes that little dot on the exclamation mark is difficult to see.

The logical NEGATION or NOT operator (!)

If X is true, !X evaluates to false.

De Morgan's laws

According to Wikipedia, Augustus De Morgan originally observed that in classical propositional logic the following relationships hold:

not (P and Q) = (not P) or (not Q)
not (P or Q) = (not P) and (not Q)

When written in terms of Alice logic operators using X and Y as described above, the two expressions given above look like:

!(X && Y) = !X || !Y
!(X || Y) = !X && !Y

De Morgan's laws will be used in this lesson to show three different formulations that can be used to solve the same logic problem.

Preview

In this lesson, I will present and explain three simple Alice programs that illustrate the use of the relational and logical operators in the above list.  All three programs are designed to solve the same problem, but the three programs use different logic solutions based on De Morgan's laws.

Because all three programs behave in an identical fashion, one set of screen shots is sufficient to illustrate all three programs.  Figure 1 shows the dialog with which the program asks the user to enter an integer value between 1 and 3 inclusive.  Note however, that the user can comply with the request as given, or can enter a value that is outside the requested range.  The behavior of the program will be different depending on whether or not the user complies with the request.

Figure 1. Request for user input in programs named Alice0170x.

Entering an invalid number

Figure 2 shows the result of entering a value that is outside of the requested range.  The image shown in Figure 2 remains on the screen for a short period, and then the input dialog shown in Figure 1 returns to the screen.  This cycle continues for as long as the user continues to enter values that are outside the requested range.

Figure 2. Result of entering an invalid number in programs named Alice0170x.

Entering a valid number

Figure 3 shows the result of entering a value that is within the requested range.

Figure 3. Result of entering a valid number in programs named Alice0170x. 

In Figure 3, the penguin speaks as shown, turns, and walks off camera on the left side of the screen.  (Remember that penguins walk very slowly so it takes a while for the penguin to make it to the edge of the screen.)

Discussion and sample code

The program named Alice0170a

This is the most straightforward version of this program.  A complete listing of the program is presented in Listing 1.  (You can also download an executable version of this program.  See Resources.)

Listing 1 begins just like one of the programs that I explained in an earlier lesson on the while loop.  The first and only new code in the program is the statement shown in Figure 4.  (Note that I inserted line breaks in different locations in Figure 4 than they are in Listing 1 in order to make the statement easier to read and to understand.)

Figure 4. The critical statement in the program named Alice0170a.
testResult.set(value,
(((userInputValue < 1) || (userInputValue > 3))));
duration = 0 seconds

The purpose of the statement

The purpose of the statement in Figure 4 is to test and determine if the userInputValue is within the range from 1 through 3 inclusive and to store the result of that test in the Boolean variable named testResult.  This statement appears for the first time immediately after the user enters a value into userInputValue and before control enters the while loop.  The same statement appears again later at the end of the body of the while loop.

Less than 1 or greater than 3

The statement in Figure 4 tests to determine if the input value is less than 1 or greater than 3.  In other words, it tests to determine if the input value is outside the specified range.  If so, the value of testResult is set to true.  Otherwise, (meaning that the value is within the specified range), the value of testResult is set to false.

The conditional clause of the while loop

The value of testResult is used in the conditional clause of the while loop to determine whether to execute the code in the body of the loop or to skip (break out of) the body of the loop and execute the code that follows the loop.

If the value of testResult is true, (meaning that the input value was outside the specified range), the code in the body of the loop is executed.  The code in the body of the loop begins by producing the screen output shown in Figure 2.  Then the code in the body of the loop gets a new user input value and uses it to compute a new value for testResult using exactly the same statement as that shown in Figure 4 again.

Go back and test again

Following that, control goes back to the conditional clause at the top of the loop structure where the value of testResult is tested for true or false and the cycle is repeated.

When testResult is false

When the value of testResult is false, (meaning that the user input value was within the specified range), the body of the loop is skipped and the doTogether block of code at the end of Listing 1 is executed.  This produces the screen output shown in Figure 3.

The program named Alice0170b

This is probably the most complicated version of the program.  A complete listing of this program is shown in Listing 2.  You can also download an executable version of this program.  (See Resources.)

Without attempting to provide a formal derivation, I am simply going to tell you that by knowing and understanding De Morgan's laws, it is possible to determine that the program will behave in an identical fashion if the statement shown in Figure 4 is replaced by the statement shown in Figure 5.  (Note that an extra line break was required in Figure 5 to cause the statement to fit into this narrow publication format.)

Figure 5. The critical statement in the program named Alice0170b.
testResult.set(value,
(!(((!(userInputValue < 1)) && 
                             (!(userInputValue > 3))))));
duration = 0 seconds

The major difference

The major difference between Figure 4 and Figure 5 is that the logical inclusive OR operator (||) was replaced by a logical AND operator (&&) in Figure 5.  All of the other changes in Figure 5 relative to Figure 4 were required to make the program work with that modification.

I'm not going to try to paraphrase the statement in Figure 5 the way I paraphrased the statement in Figure 4.  It is simply too complicated to paraphrase in words and still have those words make sense.

The behavior of the program named Alice0170b is identical to the behavior of the program named Alice170a in spite of the fact that a different formulation is used for the program logic.

The program named Alice0170c

This program is a simplification of the program named Alice0170b.  This simplification is based on recognition that the expressions on the left in Figure 6 can be replaced by the expressions on the right in Figure 6.

Figure 6. Substitution of equivalent relational expressions in program Alice0170c.
(!(userInputValue < 1)) = (userInputValue >= 1)
(!(userInputValue > 3)) = (userInputValue <= 3)

In other words, we can recognize that if userInputValue is not less than 1, then it must be greater than or equal to 1.  Similarly, if the userInputValue is not greater than 3, then it must be less than or equal to 3.

A complete listing of this program is presented in Listing 3.  An executable version can also be downloaded.  (See Resources.)

Once again the behavior is identical

The behavior of this program is identical to the behavior of the previous two programs.  Figure 7 shows the formulation of the critical relational and logical statement in this program.  Compare it with Figure 5 and you should see the effect of making the substitution illustrated by Figure 6.

Figure 7. The critical statement in the program named Alice0170c.
testResult.set(value,
(!(((userInputValue >= 1) && (userInputValue <= 3)))));
duration = 0 seconds

I'm not trying to confuse you

Please believe me when I tell you that I didn't show you these three different formulations of the program to confuse you.  Rather, I showed you the three different formulations to impress on you that once you start constructing relational and logical statements, there is almost always more than one way that you can construct the statement and get the same result.  Generally, I would recommend that you try to use the simplest formulation of the statement.

Covers all seven possibilities

Another reason that I showed you the three different formulations was because I wanted to illustrate the use of all seven of the relational and logical operators in the above list.  The seven operators in that list plus the two operators in the earlier list, (which you learned about in the earlier lesson titled "Expressions and Operators") constitute the entire set of relational and logical operators supported by Alice.

Run the program

Executable versions of the programs that I explained in this lesson are available for downloading (see Resources).  I encourage you to either download those programs or copy the code from Listings 1 through 3 into your Alice development environment and play them.  Experiment with the code making changes and observing the results of your changes.

Summary

You learned about two of Alice's relational and logical operators in an earlier lesson.  You learned about the remaining seven relational and logical operators in this lesson.  You also learned some of the theory behind relational and logical expressions as well as a little about De Morgan's law in this lesson.

What's next?

In future lessons I will teach you about:

So stay tuned.  There is lots of fun ahead.

Lab project

There is no lab project specifically for this lesson.  You will use the material that you learned in this lesson while completing the lab projects for other lessons.

Resources

General resources

Resources from earlier lessons in the series titled "Learn to Program using Alice"

Downloads

Complete program listings

Complete listings of the programs discussed in this lesson are shown in Listings 1 through 3 below.

Listing 1. Source code for program named Alice0170a.

Alice0170a's Code

Created by: Dick Baldwin

world

Events

When the world starts
Do:
world.main ( );

Methods

  public void main ( ) {
    Boolean testResult = true ; Number userInputValue = 1 ;
       // Copyright 2007, R.G.Baldwin
  doInOrder {
       // Illustrates use of relational and logical operators.
  // Program loops for as long as user keeps entering
  // integers outside the range of 1 to 3 inclusive.
  }
  // Perform a priming read and compute test result.
  doInOrder {
       userInputValue .set( value , ( NumberDialog( question = Enter an integer between 1 and 3 inclusive. ) ) ); duration = 0 seconds
  testResult .set( value , ( ( ( userInputValue < 1 ) || ( userInputValue > 3 ) ) ) ); duration = 0 seconds
  }
  // Execute a "while" loop.
  while ( testResult ) {
       // Execute this code when testResult is true.
  penguin .say( Out of range. Try again. ); duration = 2 seconds
  // Get new input and update value of testResult.
  doInOrder {
       userInputValue .set( value , ( NumberDialog( question = Enter an integer between 1 and 3 inclusive. ) ) ); duration = 0 seconds
  testResult .set( value , ( ( ( userInputValue < 1 ) || ( userInputValue > 3 ) ) ) ); duration = 0 seconds
  }
  }
  // Execute this code when testResult is false.
  doTogether {
       // Penguin speaks, turns, and walks away.
  penguin .say( Thanks, I'm outa here. ); duration = 20 seconds
  penguin .turn( RIGHT , .375 revolutions );
  penguin.walking ( x = 100 );
  }
  }

 

Listing 2. Source code for program named Alice0170b.

Alice0170b's Code

Created by: Dick Baldwin

world

Events

When the world starts
Do:
world.main ( );


Methods

  public void main ( ) {
    Boolean testResult = true ; Number userInputValue = 1 ;
       // Copyright 2007, R.G.Baldwin
  doInOrder {
       // Illustrates use of relational and logical operators.
  // This is a different formulation of the solution to
  // the same problem as in the program named Alice0170a.
  // This alternate solution is based on deMorgan's theorem.
  // Program loops for as long as user keeps entering
  // integers outside the range of 1 to 3 inclusive.
  }
  // Perform a priming read and compute test result.
  doInOrder {
       userInputValue .set( value , ( NumberDialog( question = Enter an integer between 1 and 3 inclusive. ) ) ); duration = 0 seconds
  testResult .set( value , ( ! ( ( ( ! ( userInputValue < 1 ) ) && ( ! ( userInputValue > 3 ) ) ) ) ) ); duration = 0 seconds
  }
  // Execute a "while" loop.
  while ( testResult ) {
       // Execute this code when testResult is true.
  penguin .say( Out of range. Try again. ); duration = 2 seconds
  // Get new input and update value of testResult.
  doInOrder {
       userInputValue .set( value , ( NumberDialog( question = Enter an integer between 1 and 3 inclusive. ) ) ); duration = 0 seconds
  testResult .set( value , ( ! ( ( ( ! ( userInputValue < 1 ) ) && ( ! ( userInputValue > 3 ) ) ) ) ) ); duration = 0 seconds
  }
  }
  // Execute this code when testResult is false.
  doTogether {
       // Penguin speaks, turns, and walks away.
  penguin .say( Thanks, I'm outa here. ); duration = 20 seconds
  penguin .turn( RIGHT , .375 revolutions );
  penguin.walking ( x = 100 );
  }
  }

 

Listing 3. Source code for program named Alice0170c.

Alice0170c's Code

Created by: Dick Baldwin

world

Events

When the world starts
Do:
world.main ( );


Methods

  public void main ( ) {
    Boolean testResult = true ; Number userInputValue = 1 ;
       // Copyright 2007, R.G.Baldwin
  doInOrder {
       // Illustrates use of relational and logical operators.
  // This is a different formulation of the solution to
  // the same problem as in the program named Alice0170a.
  // This alternate solution is based on deMorgan's theorem.
  // Program loops for as long as user keeps entering
  // integers outside the range of 1 to 3 inclusive.
  }
  // Perform a priming read and compute test result.
  doInOrder {
       userInputValue .set( value , ( NumberDialog( question = Enter an integer between 1 and 3 inclusive. ) ) ); duration = 0 seconds
  testResult .set( value , ( ! ( ( ( userInputValue >= 1 ) && ( userInputValue <= 3 ) ) ) ) ); duration = 0 seconds
  }
  // Execute a "while" loop.
  while ( testResult ) {
       // Execute this code when testResult is true.
  penguin .say( Out of range. Try again. ); duration = 2 seconds
  // Get new input and update value of testResult.
  doInOrder {
       userInputValue .set( value , ( NumberDialog( question = Enter an integer between 1 and 3 inclusive. ) ) ); duration = 0 seconds
  testResult .set( value , ( ! ( ( ( userInputValue >= 1 ) && ( userInputValue <= 3 ) ) ) ) ); duration = 0 seconds
  }
  }
  // Execute this code when testResult is false.
  doTogether {
       // Penguin speaks, turns, and walks away.
  penguin .say( Thanks, I'm outa here. ); duration = 20 seconds
  penguin .turn( RIGHT , .375 revolutions );
  penguin.walking ( x = 100 );
  }
  }

 


Copyright

Copyright 2007, Richard G. Baldwin.  Faculty and staff of public and private non-profit educational institutions are granted a license to reproduce and to use this material for purposes consistent with the teaching process.  This license does not extend to commercial ventures.  Otherwise, reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP).  His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments.  (TI is still a world leader in DSP.)  In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com

-end-