## Expressions and Operators

Learn about statements, expressions, arithmetic operators, and equality operators.

Published:  April 5, 2007
Last updated:  November 5, 2007
By Richard G. Baldwin

Alice Programming Notes # 160

## 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 graphic 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 "Syntax, Runtime, and Logic Errors" I taught you about syntax errors, runtime errors, and logic errors, and some of the ways to avoid them.

Up to this point in this series, we have pretty much been kicking the tires and polishing the chrome on this programming vehicle.  It's time to open the hood and start getting our hands dirty.

In this lesson, I will teach you about expressions, arithmetic operators, and equality operators.  Future lessons will teach you about the following topics, with a few other topics thrown in for good measure:

• Sequence, selection, and loop structures
• Relational and logical operators
• Counter loops, nested loops, and sentinel loops
• Arrays and lists
• Events and event handling
• Recursion
• The capabilities represented by these topics are the capabilities that separate a real computer from a programmable device such as a microwave oven or a VCR recorder, so this is the real core of computer programming.

### 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.

• Figure 1. Arithmetic operators.
• Figure 2. Arithmetic operators exposed.
• Figure 3. Two examples of mixed operator types.
• Figure 4. Equality operators.
• Figure 5. Illustration of "equal" and "not equal" operators.
• Figure 6. Output produced by the code in Figure 5.
• Figure 7. Illustration of "equal" and "not equal" operators.
• Figure 8. Output produced by the code in Figure 7.

### 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.

## Discussion

### Expressions

All of the computer programming languages with which I am familiar consist of statements, which in turn, consist of expressions.
(An expression is a specific combination of operators and operands, which evaluates to a particular result.

The operands can be variables, literals, or method calls that return a value.)

In your past experience, you may have referred to expressions by the names formulas or equations.

Although formulas and equations are not exactly the same thing as expressions, they are close enough to help you understand what expressions are and how they are used.

### Statements

A statement is a specific combination of expressions.  In Java, C++, and C# a statement is terminated by a semicolon.  The same appears to be true in Alice, but because the drag and drop paradigm takes care of syntax issues like that for you, it really isn't important.

The following is an example of a statement comprised of expressions.

z = x + y;

Operationally, in the above statement, values are retrieved from the variables named x and y.  These two values are added together.  The result is stored in (assigned to) the variable named z, replacing whatever value may previously have been contained in that variable.

### Operators and operands

Operators

Operators are the action elements of a computer program.

They perform actions such as:

• Dividing one variable by another variable
• Comparing one variable to another variable, etc.

Operands

Operators operate on operands.  Stated differently, operands are the things that are operated on by operators.

For example, in the following expression, the plus character is an operator while x and y are operands.

x + y

Assuming that x and y are numeric variables, this expression produces the sum of the values stored in the two variables.

In some languages, if x and y are string variables, this expression produces a new string, which is the concatenation of the string contents of the two string variables.  (Alice provides a function that is used to accomplish string concatenation.)  According to the current jargon, the plus character is an overloaded operator.  Its specific behavior depends on the types of its operands.

The variable x would be called the left operand and the variable y would be called the right operand.

Unary, binary, and ternary operators

Java, C++, and C# provide operators that can be used to perform an action on one, two, or three operands.

An operator that operates on one operand is called a unary operator.  (Alice supports at least one unary operator:  the increment operator.)

An operator that operates on two operands is called a binary operator.  (Alice supports several binary operators.)

An operator that operates on three operands is called a ternary operator.  (As near as I have been able to determine, Alice does not support ternary operators.)

Some operators can be either unary or binary

In Java, C++, and C#, some operators can behave either as a unary or as a binary operator.  The best known operator that can behave either way in those languages is the minus sign.  (While Alice has both unary and binary operators, as near as I have been able to determine, Alice does not support any operators that behave as both unary and binary operators.)

The minus sign as binary operator

As a binary operator, the minus sign causes its right operand to be subtracted from its left operand (provided that the two operands evaluate to numeric values).

For example, the following code subtracts the variable y from the variable x and assigns the result of the subtraction to the variable z.  After the third statement is executed, the variable z contains the value 1.

int x = 6;
int y = 5;
int z = x - y;

The minus sign as unary operator

Just to expand your thinking a little beyond Alice, in Java, C++, and C#, as a unary operator, the minus sign causes the algebraic sign of the right operand to be changed.

For example, the following two statements cause a value of -5 to be stored in the variable x.

int y = 5;
int x = -y;

Binary operators use infix notation

To keep you abreast of the current jargon, binary operators in Alice as well as Java, C++, and C# use infix notation.  This means that the operator appears between its operands.

Prefix and postfix notation

In those other languages, (but apparently not in Alice) there are some unary operators that use prefix notation.   In Alice and those other languages, there is at least one unary operator that uses postfix notation.  This operator is the increment operator, which I will explain in a future lesson.

For prefix notation, the operator appears before (to the left of) its operand.

For postfix notation, the operator appears after (to the right of) its operand.

General behavior of an operator

As a result of performing the specified action, an operator can be said to return a value (or evaluate to a value) of a given type.

The type of value returned depends on the operator and on the types of the operands.

(To evaluate to a value means that after the action is performed, the operator and its operands are effectively replaced in the expression by the value that is returned.)

Operator categories

There are many different categories of operators in most programming languages.  The operators in those different categories have different purposes.  This lesson will not attempt to teach you about, or even to introduce you to all of the different operators.  Rather, this lesson will teach you about arithmetic operators and equality operators.  Future lessons will teach you about relational operators and logical operators.

You will learn about many other operators in due time if you continue to pursue an education in computer programming using Java, C++, or C#.

### Arithmetic operators

Programming languages such as Java, C++, and C# typically support the five arithmetic operators shown in Figure 1.

Figure 1. Arithmetic operators.
 ```Operator    Description                        +        Adds its operands    -        Subtracts the right operand             from the left operand    *        Multiplies the operands     /        Divides the left operand by             the right operand    %        Remainder of dividing the              left operand by the right              operand - modulus operator```

 A bug in IEEERemainder function If you call the IEEERemainder function to get the remainder of 7/2, the value returned is -1, which is incorrect. If you call the IEEERemainder function to get the remainder of 8/3, the value returned is -1, which is incorrect. If you call the IEEERemainder function to get the remainder of 5/2, the value returned is 1, which is correct. Sometimes the function returns the correct answer and sometimes it returns the wrong answer. On the basis of a very limited amount of experimentation, it seems to return the correct answer for those cases where the correct answer is 0.

Alice supports four of the five

Alice supports the first four operators shown in Figure 1 but as near as I have been able to determine, does not support the modulus operator.  However, the world has a function named Math.IEEERemainder that may serve the same purpose.  Note, however, that it is a function and not an operator.

Using the arithmetic operators

The arithmetic operators in Alice are exposed whenever you click the triangle immediately to the right of a component in an expression that can serve as the left operand for the operator.  An example of this procedure is shown in Figure 2.

Figure 2. Arithmetic operators exposed.

How did I produce the outcome shown in Figure 2?

In Figure 2, I clicked the triangle immediately to the right of 1 meter.  That exposed the topmost menu shown in Figure 2.  One of the selections on that menu reads math.  When I selected the math item, the menu immediately to its right opened up showing the left operand and a choice of each of the four arithmetic operators.  When I selected the item that reads 1+, that exposed the rightmost menu in Figure 2.

The b at the top of that menu indicates that the rightmost menu represents the right operand for the selected arithmetic operator.  As usual, for numeric data, there was a choice of values plus the item that reads other...  As you have seen before, selecting other... exposes a numeric keypad that allows you to specify any numeric value.  It also allows you to compute the quotient of two numeric values and to specify that quotient as the right operand.

Mixing arithmetic operators

When using the drag and drop paradigm to construct expressions containing arithmetic operators, you must be careful to construct them in such a way that they will be evaluated properly.  An example of this situation is shown in Figure 3.

Figure 3. Two examples of mixed operator types.

Figure 3 contains two statements that evaluate an arithmetic expression using the current values of the variables a and b, along with the literal constant 3.  The expressions also include the addition operator (+) and the multiplication operator (*).  Given the values shown for the two variables, the result of evaluating the arithmetic expression in the first statement would be 21.  The result of evaluating the arithmetic expression in the second statement would be 11.

Can you see the difference?

Basically when expressions containing terms that are grouped within matching parentheses are evaluated, the contents of the inner-most pair of parentheses are evaluated first.  Then that pair of parentheses and its contents are replaced by the value that was produced and that value is used to evaluate the next inner-most pair of parentheses.  This process continues until all of the parentheses have been eliminated.  (Do you remember doing this in your high school algebra class?)

Using this approach, we see that the result of evaluating the arithmetic expression in the first statement in Figure 3 is 7*3 or 21.  The result of evaluating the arithmetic expression in the second statement is 5+6 or 11.  Just remember, parentheses are always cleared out beginning with the inner-most parentheses and working outward to the outer-most pair of parentheses.

At this point in your studies, you should be able to create the two statements shown in Figure 3.  See if you can do it.

Mixed-type arithmetic

Programming languages such as Java, C++, and C# have several different numeric types.  Some of those types are whole number or integer types.  The others are types that can contain a fractional part.  However, Alice has only one numeric type (Number) and it is a type that can contain a fractional part.

When you master Alice and move on to those other programming languages, you will find that there are some subtle, somewhat tricky, and important issues involved in performing arithmetic using values of different types.  For the time being, however, you can relax because you won't have to deal with those issues with Alice.  Don't become too complacent, however.  If you continue in your efforts to become a computer programmer, the day will come when you too will have to deal with the problems associated with mixed-type arithmetic.

### Equality operators

There are two more operators that I want to teach you about before we leave this lesson:  the equality operators.  Each of these operators is a binary operator, which returns the boolean values true or false, depending on whether their two operands are equal or not.  The operators are pictured in Figure 4.

Figure 4. Equality operators.
 ```Operator    Description                        ==       Returns true if operands are equal. Otherwise returns false.    !=       Returns true if operands are not equal. Otherwise returns false.```

An example of equality operators

The Alice code in Figure 5 illustrates the behavior of both operators.

Figure 5. Illustration of "equal" and "not equal" operators.

 Variable names While I normally prefer to use meaningful variable names beginning with lower-case characters and camelCase, I elected to use single characters for the names in this example so that the code would fit into this narrow publication format without having to be reduced.  I elected to use upper-case characters because they stand out better in the text that discusses the variables.

Performing operations on three variables

The simple code in Figure 5 declares and initializes three variables named A, B, and C.  The variables A and B are each of type Number, and are given values of 5 and 2 respectively.  Thus, the values in these two variables are not equal to one another.

The variable named C is of type Boolean, and its initial value is immaterial because that value will be overwritten by the code in Figure 5 when the program is run.

Evaluating the expression

The first statement in Figure 5 evaluates the expression

`A==B`
and stores the value that is returned in the variable named C, overwriting the previous contents of C.  The second statement in Figure 5 prints the value stored in C, producing the first line of output text in Figure 6.  As you can see, the printed output indicates that the expression is false because A is not equal to B.

Figure 6. Output produced by the code in Figure 5.
 ```the value of world.main.C is false the value of world.main.C is true ```

Evaluating the other expression

The third statement in Figure 5 evaluates the expression

`A!=B`
and stores the result in variable C, once again overwriting the previous contents of C.  The fourth statement in Figure 5 prints the contents of C, producing the second line of text in Figure 6.  The printed output indicates that the expression is true because A is not equal to B.

Modify values for A and B

Figures 7 and 8 show the result of modifying the values of the two variables so that the value of A is equal to the value of B and running the program again.

Figure 7. Illustration of "equal" and "not equal" operators.

Figure 8. Output produced by the code in Figure 7.
 ```the value of world.main.C is true the value of world.main.C is false ```

Make certain that you understand the outcome

We will be using these two operators extensively in a future lesson on selection and loop structures, so you need to make certain that you understand their behavior before leaving this lesson.

## Summary

In this lesson, I taught you about expressions, arithmetic operators, and equality operators.

## What's next?

Future lessons will teach you about the following topics, with a few other topics thrown in for good measure:

• Sequence, selection, and loop structures
• Relational and logical operators
• Counter loops, nested loops, and sentinel loops
• Arrays and lists
• Events and event handling
• Recursion
• ## Lab project

There is no lab project for this lesson.  You will use the expressions and operators that you learned about in this lesson in the lab projects for the lessons that follow.

## Resources

General resources

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

• 100 Getting Started
• 105 Setting the Stage
• 110 Objects in 3D Space
• 115 Setting the Stage Manually, Part 1
• 120 Setting the Stage Manually, Part 2
• 125 Your First Alice Program
• 130 The Program Development Cycle
• 135 Functions that return values
• 140 Data Types and Variables
• 145 World-Level Methods
• 150 Class-Level Methods and Inheritance
• 155 Syntax, Runtime, and Logic Errors
• 900 Appendix A, Behavior of Primitive Methods

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.

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.

-end-