Chapter 9: Variables and Assignment Statements Bradley Kjell (Revised 07/20/2008)

Similar documents
Chapter 2: Elements of Java

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Moving from CS 61A Scheme to CS 61B Java

Java Basics: Data Types, Variables, and Loops

Chapter 14: Boolean Expressions Bradley Kjell (Revised 10/08/08)

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

1.6 The Order of Operations

Java CPD (I) Frans Coenen Department of Computer Science

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Lab Experience 17. Programming Language Translation

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Base Conversion written by Cathy Saxton

1 Description of The Simpletron

Section 1.5 Exponents, Square Roots, and the Order of Operations

Chapter One Introduction to Programming

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Java Interview Questions and Answers

Order of Operations More Essential Practice

Example of a Java program

CS 106 Introduction to Computer Science I

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Variables, Constants, and Data Types

Part 1 Expressions, Equations, and Inequalities: Simplifying and Solving

Operations with positive and negative numbers - see first chapter below. Rules related to working with fractions - see second chapter below

Activity 1: Using base ten blocks to model operations on decimals

SAT Math Facts & Formulas Review Quiz

Introduction to Python

arrays C Programming Language - Arrays

In this Chapter you ll learn:

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Pre-Algebra Lecture 6

Chapter 3. Input and output. 3.1 The System class

0.8 Rational Expressions and Equations

Computer Science 281 Binary and Hexadecimal Review

Section 4.1 Rules of Exponents

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

MULTIPLICATION AND DIVISION OF REAL NUMBERS In this section we will complete the study of the four basic operations with real numbers.

Comp 255Q - 1M: Computer Organization Lab #3 - Machine Language Programs for the PDP-8

VHDL Test Bench Tutorial

Binary Adders: Half Adders and Full Adders

Click on the links below to jump directly to the relevant section

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Direct Translation is the process of translating English words and phrases into numbers, mathematical symbols, expressions, and equations.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

PAYCHEX, INC. BASIC BUSINESS MATH TRAINING MODULE

Chapter 1 Java Program Design and Development

Multiplication Rules! Tips to help your child learn their times tables

Introduction to Java. CS 3: Computer Programming in Java

PREPARATION FOR MATH TESTING at CityLab Academy

Some Scanner Class Methods

Chapter 5 Names, Bindings, Type Checking, and Scopes

Chapter 2 Elementary Programming

VB.NET Programming Fundamentals

Sources: On the Web: Slides will be available on:

Section 1.4 Place Value Systems of Numeration in Other Bases

2.6 Exponents and Order of Operations

Numbering Systems. InThisAppendix...

Encoding Text with a Small Alphabet

Introduction to Python

Chapter 2 Introduction to Java programming

Training Manual. Pre-Employment Math. Version 1.1

Chapter 7D The Java Virtual Machine

A single register, called the accumulator, stores the. operand before the operation, and stores the result. Add y # add y from memory to the acc

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

IP Subnetting: Practical Subnet Design and Address Determination Example

ALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

Session 29 Scientific Notation and Laws of Exponents. If you have ever taken a Chemistry class, you may have encountered the following numbers:

Oct: 50 8 = 6 (r = 2) 6 8 = 0 (r = 6) Writing the remainders in reverse order we get: (50) 10 = (62) 8

Visual Logic Instructions and Assignments

A PRACTICAL GUIDE TO db CALCULATIONS

Introduction to Java

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

Common Beginner C++ Programming Mistakes

Install Java Development Kit (JDK) 1.8

PL / SQL Basics. Chapter 3

This Unit: Floating Point Arithmetic. CIS 371 Computer Organization and Design. Readings. Floating Point (FP) Numbers

Semantic Analysis: Types and Type Checking

what operations can it perform? how does it perform them? on what kind of data? where are instructions and data stored?

Object Oriented Software Design

CAHSEE on Target UC Davis, School and University Partnerships

Part I. The Picture class

Number Representation

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

J a v a Quiz (Unit 3, Test 0 Practice)

1 Abstract Data Types Information Hiding

To convert an arbitrary power of 2 into its English equivalent, remember the rules of exponential arithmetic:

26 Integers: Multiplication, Division, and Order

Lecture 5: Java Fundamentals III

Financial Mathematics

SYSTEMS OF EQUATIONS AND MATRICES WITH THE TI-89. by Joseph Collison

YOU MUST BE ABLE TO DO THE FOLLOWING PROBLEMS WITHOUT A CALCULATOR!

The Hexadecimal Number System and Memory Addressing

=

Udacity cs101: Building a Search Engine. Extracting a Link

Integers are positive and negative whole numbers, that is they are; {... 3, 2, 1,0,1,2,3...}. The dots mean they continue in that pattern.

Transcription:

Chapter 9: Variables and Assignment Statements Bradley Kjell (Revised 07/20/2008) In all but the smallest programs, an executing program is constantly working with values. These values are kept in little sections of main memory called variables. Chapter Topics: Variables Assignment Statements Expressions Arithmetic Operators QUESTION 1: Do you imagine that a variable can change its value? Used by permission. Page 1 of 44

Yes that is why is is called a variable. Variables The billions of bytes of main storage in your home computer are used to store both machine instructions and data. The electronic circuits of main memory (and all other types of memory) make no distinction between the two. When a program is running, some memory locations are used for machine instructions and others for data. Later, when another program is running some of the bytes that previously held machine instructions may now hold data, and some that previously held data may now hold machine instructions. Using the same memory for both instructions and data was the idea of John von Neumann, a computer pioneer. (If you are unclear about bytes and memory locations, please read Chapter 3.) variable a named location in main memory which uses a particular data type to hold a value. Recall that a data type is a scheme for using bit patterns to represent a value. Think of a variable as a little box made of one or more bytes that can hold a value using a particular data type. To put a value in memory, and later to get it back, a program must have a name for each variable. Variables have names such as payamount. (Details will be given in a few pages.) QUESTION 2: Used by permission. Page 2 of 44

Must a variable always have a data type? Used by permission. Page 3 of 44

Yes. Otherwise it would not be clear what its bits represent. Declaration of a Variable The example program uses the variable payamount. The statement long payamount = 123; is a declaration of a variable. A declaration of a variable is where a program says that it needs a variable. For our small programs, place declaration statements between the two braces of the main method. The declaration gives a name and a data type for the variable. It may also ask that a particular value be placed in the variable. In a high level language (such as Java) the programmer does not need to worry about how the computer hardware actually does what was asked. If you ask for a variable of type long, you get it. If you ask for the value 123 to be placed in the variable, that is what happens. Details like bytes, bit patterns, and memory addresses are up to the Java compiler. In the example program, the declaration requests an eight-byte section of memory named payamount which uses the primitive data type long for representing values. When the program starts running, the variable will initially have the value 123 stored in it. A variable cannot be used in a program unless it has been declared. A variable can be declared only once. Used by permission. Page 4 of 44

QUESTION 3: What do you think the program prints on the monitor? (You should be able to figure this out.) Used by permission. Page 5 of 44

The variable contains: 123 Simulated Java Program To get the most out of these notes, copy the program to a text editor, save it to a file called Example.java, compile it, and run it. See Chapter 7 on how to do this. For a simulation of running the program, enter an integer in the text box below and click on "Compile", then click on "Run". (Note: if this does not work, your browser does not have JavaScript enabled.) This is just a simulation (using JavaScript), so it is not exactly like compiling and running a real Java program. Don't take it too seriously. Please do the real thing if you can. QUESTION 4: Try entering something like "rats" in the declaration. Does the program compile successfully? Used by permission. Page 6 of 44

No. Syntax of Variable Declaration The word syntax means the grammar of a programming language. We can talk about the syntax of just a small part of a program, such as the syntax of variable declaration. There are several ways to declare variables: datatype variablename; This declares a variable, declares its data type, and reserves memory for it. It says nothing about what value is put in memory. (Later in these notes you will learn that in some circumstances the variable is automatically initialized, and that in other circumstances the variable is left uninitialized.) datatype variablename = initialvalue ; This declares a variable, declares its data type, reserves memory for it, and puts an initial value into that memory. The initial value must be of the correct data type. datatype variablenameone, variablenametwo ; This declares two variables, both of the same data type, reserves memory for each, but puts nothing in any variable. You can do this with more than two variables, if you want. datatype variablenameone = initialvalueone, variablenametwo = initialvaluetwo ; This declares two variables, both of the same data type, reserves memory, and puts an initial value in each variable. You can do this all on one line if there is room. Again, you can do this for more than two variables as long as you follow the pattern. If you have several variables of different types, use several declaration statements. You can even use several declaration statements for several variables of the same type. Used by permission. Page 7 of 44

QUESTION 5: Is the following correct? int answer; double rate = 0.05; Used by permission. Page 8 of 44

Yes as long as the names answer and rate have not already been used. Names for Variables The programmer picks a name for each variable in a program. Various things in a program are given names. A name chosen by a programmer is called an identifier. Here are the rules for identifiers: Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character '_', and character '$'. o An identifier can not contain the space character. Do not start with a digit. An identifier can be any length. Upper and lower case count as different characters. o SUM and Sum are different identifiers. An identifier can not be a reserved word. An identifier must not already be in use in this part of the program. A reserved word is a word which has a predefined meaning in Java. For example int, double, true, and import are reserved words. Rather than worry about the complete list of reserved words, just remember to avoid using names that you know already mean something, and be prepared to make a change if you accidentally use a reserved word you didn't know. As a matter of programming style, a name for a variable usually starts with a lower case letter. If a name for a variable is made of several words, capitalize each word except the first. For example, payamount and grandtotal. These conventions are not required by syntax, but make programs easier to read. QUESTION 6: Which of the following variable declarations are correct? int mypay, yourpay; long good-by ; Used by permission. Page 9 of 44

short shrift = 0; double bubble = 0, toil= 9, trouble = 8 byte the bullet ; int double; char thismustbetoolong ; int 8ball; float a=12.3; b=67.5; c= -45.44; Used by permission. Page 10 of 44

There are some syntax errors: int mypay, yourpay; // OK long good-by ; // bad identifier: "-" not allowed short shrift = 0; // OK double bubble = 0, toil= 9, trouble = 8 // missing ";" at end. byte the bullet ; space // bad identifier: can't contain a int double; word // bad identifier: double is a reserved char thismustbetoolong ; choice // OK in syntax, but a poor // for a variable name int 8ball; // bad identifier: can't start with a digit float a=12.3; b=67.5; c= -45.44; // bad syntax: don't use ";" to separate variables Example Program The example program, containis three variable declarations. The variables are given initial values. The character * means multiply. In the program, Used by permission. Page 11 of 44

(hoursworked * payrate) means to multiply the number stored in hoursworked by the number stored in payrate. Important Idea: When used as part of an expression, the name of a variable represents the value it holds. (An expression is a part of a statement that asks for a value to be calculated.) When it follows a character string, + means to add characters to the end of the character string. So "Hours Worked: " + hoursworked makes a character string starting with "Hours Worked: " and ending with characters for the value of hoursworked. The program prints: Hours Worked: 40 pay Amount : 400.0 tax Amount : 40.0 Remember that if you want to see this program run, copy it from your Web browser, paste it into Notepad or other text editor, save it to a file, compile, and run it. (See Chapter 7.) QUESTION 7: Why did the program print the first 40 without a decimal point, but printed the second one with a decimal point as 40.0? (Hint: look at the variable declarations.) Used by permission. Page 12 of 44

The first value was stored in a variable of data type long, an integer type. Integers do not have fractional parts. The second forty was the result of a calculation involving a variable of data type double, a floating point type, which does have a fractional part. (Here, the fractional part was zero.) Calculation Look carefully at the statement highlighted in red. The parentheses around (hoursworked * payrate) force the multiplication to be done first. After it is done, the result is converted to characters and appended to the string "pay Amount : ". When you have a calculation as part of a System.out.println() statement, it is a good idea to surround the calculation with parentheses to show that you want it done first. Sometimes this is not necessary, but it does not hurt, and makes the program more readable. QUESTION 8: Would it be better to write some of those statements on two lines instead one one? Used by permission. Page 13 of 44

Yes. Several Lines per Statement You can use several lines for a statement. Anywhere a space character is OK you can split a statement. This means you can't split a statement in the middle of a name, nor between the quote marks of a string literal, nor in the middle of a numeric literal. Here is the program with some statements correctly put on two lines: Although correct, the division of statements is confusing to humans. It is also true that anywhere one space is OK any number of spaces are OK. Here is a better style for the program: Used by permission. Page 14 of 44

It is a good idea to indent the second half of a split statement further than the start of the statement. QUESTION 9: Is the following correct? cla ss Example { public static void main ( String[] args ) { long hoursworked = 40; double payrate = 10.0, taxrate = 0.10; System.out.println("Hours Worked: " + hoursworked ); System.out.println("pay Amount : " + (hours Worked * payrate) ); } } System.out.println("tax Amount : " + ( hoursworked * payrate * taxrate) ); Used by permission. Page 15 of 44

No. The incorrect splittings are highlighted in red: cla ss Example { public static void main ( String[] args ) { long hoursworked = 40; double payrate = 10.0, taxrate = 0.10; System.out.println("Hours Worked: " + hoursworked ); System.out.println("pay Amount : " + (hours Worked * payrate) ); System.out.println("tax Amount : " + ( hoursworked * payrate * taxrate) ); } The last statement is correct, although not done in a good style for easy human comprehension. The extra blank lines are OK. Assignment Statements So far, the example programs have been using the value initially put into a variable. Programs can change the value in a variable. An assignment statement changes the value that is held in a variable. Here is a program that uses an assignment statement: The assignment statement puts the value 123 into the variable. In other words, while the program is executing there will be a 64 bit section of memory that holds Used by permission. Page 16 of 44

the value 123. Remember that the word "execute" is often used to mean "run". You speak of "executing a program" or "executing" a line of the program. QUESTION 10: What does the program print to the monitor? Used by permission. Page 17 of 44

The variable contains: 123 The program prints out the same thing as the first example program. However, this program did not initialize the variable and so had to put a value into it later. Assignment Statement Syntax Assignment statements look like this: variablename = expression ; The equal sign = is the assignment operator. variablename is the name of a variable that has been declared previously in the program. expression is a collection of characters that calls for a value. Here are some example assignment statements (assume that the variables have already been declared): total = 3 + 5; price = 34.56; tax = total*0.05; In the source file, the variable must be declared before any assignment statement that uses that variable. QUESTION 11: Is the following correct? int sum; sum = 42-12 ; Used by permission. Page 18 of 44

Yes, the statements are syntactically correct. Assignment Statement Semantics The syntax of a programming language says what programs look like. It is the grammar of how to arrange the symbols. The semantics of a programming language says what the program does as it executes. It says what the symbols mean. This page explains the semantics of the assignment statement. An assignment statement does its work in two steps: First, do the calculation on the RIGHT of the equal sign. If there is nothing to calculate, use the value on the right. Next, replace the contents of the variable to the LEFT of the equal sign with the result of the calculation. For example: total = 3 + 5; Do the calculation 3+5 to get 8. Put 8 in the variable named total. It does not matter if total already has a number in it. Step 2 will replace whatever is already in total. For example: points = 23; Use the value 23. Put 23 in the variable named points. QUESTION 12: What happens FIRST when the following statement executes? value = 2*3 ; Used by permission. Page 19 of 44

FIRST, do the multiplication 2*3 to get the value 6. Two Steps FIRST, do the multiplication 2*3 to get the value 6. NEXT, put the result of the calculation into the "litte box of memory" used for the variable value: It will really, really help you to think carefully about these two steps. Sometimes even second year computer science majors get confused about this and write buggy code. QUESTION 13: What will this program fragment write? value = 2*3; System.out.println( "value holds: " + value ); Used by permission. Page 20 of 44

value holds: 6 More Practice Here is another program fragment: int extra; extra = 5; The assignment statement is correct. It matches the syntax: variablename = expression; The expression is the literal 5. No calculation needs to be done. But the assignment statement still takes two steps. FIRST, get the 5: NEXT, put the 5 in the variable: QUESTION 14: What does the following fragment write? int quantity = 7; quantity = 13; System.out.println( "quantity holds: " + quantity ); Used by permission. Page 21 of 44

quantity holds: 13 The assignment statement replaced the value that was originally in quantity with the value 13. Adding a Number to a Variable Assume that extra already contains the value 5. Here is another statement: value = extra + 2; The statement will be performed in two steps (as always). The first step performs the calculation extra + 2 by first copying the 5 from extra, and then adding 2 to it: The result of the calculation is 7. The second step puts 7 into the variable value: Used by permission. Page 22 of 44

QUESTION 15: What will the following program print out: // Example assignment statements int extra, value; extra = 5; value = extra + 2; System.out.println( "value now holds: " + value ); Used by permission. Page 23 of 44

The program will print out: value now holds: 7 Same Variable Twice in an Assignment Statement Look at the statements: value = 5; value = 12 + value; Assume that value has already been declared. The two statements execute one after the other, and each statement performs two steps. The first statement: Gets the number on the RIGHT of the equal sign: 5 Puts the 5 in the variable called value. Used by permission. Page 24 of 44

The second statement: Does the calculation on the RIGHT of the equal sign: 12 + value. Look into the variable value to get the number 5. Perform the sum: 12 + 5 to get 17 Look on the LEFT of the equal sign to see where to put the result. Put the 17 in the variable value. Note: A variable can be used on both the LEFT and the RIGHT of the = in the same assignment statement. When it is used on the right, it provides a number used to calculate a value. When it is used on the left, it says where in memory to save that value. The two roles are in separate steps, so they don't interfere with each other. Step 1 uses the original value in the variable. Then step 2 puts the new value (from the calculation) into the variable. QUESTION 16: Used by permission. Page 25 of 44

What does the following program fragment write? value = 5; System.out.println("value is: " + value ); value = value + 10; System.out.println("value is: " + value ); Used by permission. Page 26 of 44

The program will print out: value is: 5 value is: 15 A Sequence that Counts Look at this program fragment: Here is how the program works: 1. Statement 1 puts 0 into count. 2. Statement 2 writes out the 0 in count. 3. Statement 3 first gets the 0 from count, adds 1 to it, and puts the result back in count. 4. Statement 4 writes out the 1 that is now in count. When the fragment runs, it writes: 0 1 QUESTION 17: Think of a way to write 0, 1, and 2. Used by permission. Page 27 of 44

Put a copy of statements 3 and 4 at the end. Counting Higher The following fragment: prints out 0 1 2 The statement count = count + 1; increments the number in count. Sometimes programmers call this "incrementing a variable" although (of course) it is really the number in the variable that is incremented. QUESTION 18: What does the following assignment statement do: sum = 2*sum ; (What are the two steps, in order?) Used by permission. Page 28 of 44

Evaluate the expression: get the value in sum and multiply it by two. Then, put that value into sum. Expressions Sometimes you need to think carefully about the two steps of an assignment statement. The first step is to evaluate the expression on the right of the assignment operator. An expression is a combination of literals, operators, variable names, and parentheses used to calculate a value. This (slighly incomplete) definition needs some explanation: literal characters that directly give you a value, like: 3.456 operator a symbol like plus + or times * that asks for an arithmetic operation. variable a section of memory containing a value. parentheses ( and ). This might sound awful. Actually, this is stuff that you know from algebra, like: (32 - y) / ( x + 5 ) In the above, the character / means division. Not just any mess of symbols will work. The following 32 - y) / ( x 5 + ) is not a syntactically correct expression. There are rules for this, but the best rule is that an expression must look OK as algebra. However, multiplication must always be shown by using a * operator. You can't multiply two variables by placing them next to each other. So, although xy might be correct in algebra, you must use x*y in Java. QUESTION 19: Which of the following expressions are correct? (Assume that the variables have been properly declared elsewhere.) Used by permission. Page 29 of 44

Expression 53 12-3) x + 34 *z 99 sum value + Correct or Not? Correct NOT Correct Correct NOT Correct Correct More Practice Let's try some more. Again, assume that all the variables have been correctly declared. Used by permission. Page 30 of 44

QUESTION 20: Why is the last expression not correct? Used by permission. Page 31 of 44

Multiplication must be shown with a * operator. (Another answer is that 3.14y is not a correct variable name.) Spaces Don't Much Matter An expression can be written without using any spaces. Operators and parentheses are enough to separate the parts of an expression. You can use one or more spaces in an expression to visually separate the parts without changing the meaning. For example, the following is a correct expression: (hoursworked*payrate)-deduction The following means exactly the same: (hoursworked * payrate) - deduction Use spaces wisely to make it clear what the expression means. By making things clear, you might save yourself hours of debugging. Spaces can't be placed in the middle of identifiers. The following is NOT correct: ( hours Worked * pay Rate) -deduction It is possible (but unwise) to be deceptive with spaces. For example, in the following: 12-4 / 2+2 it looks as if 4 is subtracted from 12, and then that the result, 8, is divided by 4. However, the spaces don't count, and the expression is the same as: 12-4/2 + 2 This arrangement of spaces makes it clear what the expression means. QUESTION 21: Based on what you know about algebra, what is the value of this expression: 12-4/2 + 2 Used by permission. Page 32 of 44

12, since the expression means: 12-2 + 2 Arithmetic Operators An arithmetic operator is a symbol that asks for doing some arithmetic. As the previous question illustrates, if several operators are used in an expression, the operations are done in a specific order. Operators of higher precedence are done first. The table shows the precedence of some Java operators. Some operators have equal precedence. For example, addition + and subtraction - have the same precedence. The unary minus and unary plus operators are used as part of a negative or a positive number. For example, -23 means negative twenty-three and +23 means positive twenty-three. More on this later. When both operands (the numbers) are integers, these operators do integer arithmetic. If one operand or both operands are floating point, then these operators do floating point arithmetic. This is especially important to remember with division, because the result of integer division is an integer. For example: 5/2 is 2 (not 2.5) 5/10 is 0 (not 0.5). More on this later. QUESTION 22:What is the value of the following expressions? In each expression, do the highest precedence operator first. Used by permission. Page 33 of 44

Used by permission. Page 34 of 44

The last result is correct. First 6/8 is done using integer division, resulting in 0. Then that 0 is added to 2. Evaluation by Rewriting When evaluating an expression, it can be helpful to do it one step at a time and to rewrite the expression after each step. Look at: 16-12 / 4 Do the division first, since it has highest precedence. Next, rewrite the expression replacing the division with its value: 16-3 Now evaluate the resulting expression: 13 You can write the process like this: 16-12 / 4 ------ 16-3 --------- 13 The dashed lines show what was done at each step. QUESTION 23: What is the value of the following expression? 24 / 2-8 Used by permission. Page 35 of 44

24 / 2-8 ------ 12-8 --------- 4 Evaluate Equal Precedence from Left to Right When there are two (or more) operators of equal precedence, evaluate the expression from left to right. 2 * 7 * 3 ----- 14 * 3 ------- 42 Since both operators are *, each has equal precidence, so calculate 2 * 7 first, then use that result with the second operator. 4-2 + 5 ----- 2 + 5 ------- 7 Here the operators are different, but they both have the same precidence, so they are evaluated left to right. Usually it doesn't matter if evaluation is done left to right or in any other order. In algebra it makes no difference. But with floating point math it sometimes makes an important difference. Also, when an expression uses a method it can make a very big difference. (Methods are discussed in part 6 of these notes.) Used by permission. Page 36 of 44

QUESTION 24: What is the value of the following expression? 2 + 4/2 + 1 Used by permission. Page 37 of 44

2 + 4/2 + 1 --- 2 + 2 + 1 ------ 4 + 1 --------- 5 Unary Minus If you look in the table of operators you will see that the character - is listed twice. That is because - is used for two purposes. In some contexts, - is the unary minus operator. In other contexts, - is the subtraction operator. The unary minus is used to show a negative number. For example: -97.34 means "negative ninety seven point thirty four." The subtraction operator is used to show a subtraction of one number from another. For example: 95-12 asks for 12 to be subtracted from 95. The unary minus operator has high precedence. Addition and subtraction have low precedence. For example -12 + 3 means add 3 to negative 12 (resulting in -9). The unary minus is done first, so it applies only to the twelve. unary plus + can be applied to a number to show that it is positive. It also has high precedence. It is rarely used. QUESTION 25: What is the value of the following expression? +24 + 3 * -4 Used by permission. Page 38 of 44

+24 + 3 * -4 ------ +24 + -12 ----------- 12 The first + is a unary plus, so it has high precidence and applies only to the 24. The - is a unary minus, so it applies only to the 4. Next in order of precidence is the *, so three times negative four is calculated yielding negative twelve. Finally the low precidence + combines the postive twenty four with the negative twelve. Arrange what you want with Parentheses To say exactly what numbers go with each operator, use parentheses. For example -1 * ( 9-2 ) * 3 means do 9-2 first. The "( )" groups together what you want done first. After doing the subtraction, the ( 9-2 ) becomes a 7: -1 * 7 * 3 Now follow the left-to-right rule for operators of equal precedence: -1 * 7 * 3 ------ -7 * 3 -------- -21 QUESTION 26: What is the value of each of the following expressions? Used by permission. Page 39 of 44

Used by permission. Page 40 of 44

Extra Parentheses Notice that the last expression (above) did not need parentheses. It does not hurt to use parentheses that are not needed. For example, all of the following are equivalent: Warning! Look out for division. The / operator is a constant source of bugs! Parentheses will help. QUESTION 27: What is the value of each of the following expressions? Used by permission. Page 41 of 44

The last answer is correct. It is done like this: 8 + 2 / (2 + 3 ) -------- 8 + 2 / 5 ----- 8 + 0 ----- 8 2/5 is 0 with integer division. Nested Parentheses Sometimes in a complicated expression one set of parentheses is not enough. In that case use several nested sets to show what you want. The rule is: The innermost set of parentheses is evaluated first. Start evaluating at the most deeply nested set of parentheses, and then work outward until there are no parentheses left. If there are several sets of parentheses at the same level, evaluate them left to right. For example: Used by permission. Page 42 of 44

Ordinarily you would not do this in such detail. QUESTION 28: What is the value of this expression: (12 / 4 ) + ( 12 / 3) Used by permission. Page 43 of 44

7 End of the Chapter Here is a list of subjects you may wish to review. Click on a high precedence subject to go to where it was discussed. What variables are. Declaring variables. Syntax of declaring variables. Names for variables. Reserved words. Assignment statements Semantics Expressions. Table of operators and their precedence. How parentheses change the order of evaluation. The next chapter will continue with arithmetic expressions. Used by permission. Page 44 of 44