Variables and Assignment Statements

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: Variables and Assignment Statements
Printed by: Guest user
Date: Friday, February 4, 2022, 4:52 PM

Description

Read this chapter, which covers variables and arithmetic operations and order precedence in Java.

1. Variables and Assignment Statements

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

bitBox

Chapter Topics:

      • Variables
      • Assignment Statements
      • Expressions
      • Arithmetic Operators

Question 1:

Do you imagine that a variable can change its value?


Source: Bradley Kjell, http://programmedlessons.org/Java9/chap09/ch09_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 License.

2. Variables


Answer:

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. It just holds bit patterns.

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

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

Variables come and go as a running program needs them. When a running program no longer needs a variable, that section of memory may be reused for some other purpose.


Question 2:

Must a variable always have a data type?

3. Declaration of a Variable


Answer:

Yes. Otherwise it would not be clear what its bits represent.

Remember that the meaning of a bit pattern is determined by its context. It is the data type that
gives the bits in a variable a context.

Declaration of a Variable

Declaration of a variable box

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

The name for a variable must be a legal Java identifier. (Details in a few pages.)

A variable cannot be used in a program unless it has been declared.


Question 3:

What do you think the program prints on the monitor? (You should be able to figure this out.)

4. Simulated Java Program


Answer:

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 a previous chapter 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". (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.

Try this page: http://ideone.com/. There, you can paste Java code into a web page text box, and then compile and run it with actual Java.

A similar site is http://javabat.com/.

  
  public class Example
  {
    public static void main ( String[] args )
    {
      long payAmount = ;    // declaration of a variable
  
      System.out.println("The variable contains: " + payAmount );
    }
  }
  
  
Simulated Monitor






Question 4:

Try entering something like "rats" in the declaration. Does the program compile successfully?

5. Syntax of Variable Declaration


Answer:

No

Syntax of Variable Deceleration

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.


Question 4:

Is the following correct?

    int answer; double rate = 0.05;

6. Names for Variables


Answer:

Yes — as long as the names  answer  and  rate  have not already been used.

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', and characters '$' and '_'.
      • 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.
        • 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.

reserved word is a word which has a predefined meaning in Java. For example intdoubletrue, 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.

Although dollar sign is legal in identifiers, by convention it is used for special purposes. Don't use it for ordinary variables, even if the compiler lets you.

Although legal, it is unwise to start an identifier with underscore. Also, older Java compilers allowed a single underscore as an identifier, but recent ones do not.

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? (click on a declaration to verify your answer)

int myPay, yourPay; 

long good-by ;

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;

7. Calculation


Answer:

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

public class 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  : " + (hoursWorked * payRate) );
    System.out.println("tax Amount  : " + (hoursWorked * payRate * taxRate) );
  }
}

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?

8. Several Lines per Statement


Answer:

Maybe.

Several Lines per Statment

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. Recall that a "literal" is an explicit value in the program. Here is the program with some statements correctly put on two lines:

public class 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 : "
+ (hoursWorked * payRate) );
System.out.println("tax Amount : " + (hoursWorked
* payRate * taxRate) );
}
}

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:


public class 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 : " +
(hoursWorked * payRate) );
System.out.println("tax Amount : " +
(hoursWorked * payRate * taxRate) );
}
}


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) );
  }
}

9. Assignment Statements


Answer:

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 Statement

public class AssignmentExample
{
public static void main ( String[] args )
{
long payAmount ; // payAmount is declared without an initial value payAmount = 123; // an assignment statement
System.out.println("The variable contains: " + payAmount );
}
}

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. The program 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 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?

10. Assignment Statement Syntax


Answer:

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 to be calculated.

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 ;

11. Assignment Statement Semantics


Answer:

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:

  1. First, do the calculation on the RIGHT of the equal sign.
    • If there is nothing to calculate, use the value on the right.
  2. Next, replace the contents of the variable on the LEFT of the equal sign with the result of the calculation.

For example:

total = 3 + 5;
  1. Do the calculation 3+5 to get 8.
  2. 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;
  1. Use the value 23.
  2. Put 23 in the variable named points.

Question 12:

What happens FIRST when the following statement executes?

    value = 2*3 ;

12. Two Steps


Answer:

FIRST, do the multiplication 2*3 to get the value 6.

Two Steps

FIRST, do the multiplication 2*3 to get the value 6.

Do First

NEXT, put the result of the calculation into the "litte box of memory" used for the variable value:

Do Second

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 );

13. More Practice


Answer:

    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:

Do First

NEXT, put the 5 in the variable:

Do Second


Question 14:

What will this program fragment write?

    int quantity = 7; quantity = 13; System.out.println( "quantity holds: " + quantity );

14. Adding a Number to a Variable


Answer:

    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.

Extra with 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:

Do First

The result of the calculation is 7. The second step puts 7 into the variable value:

Do Second

Question 15:

What will this program print out:

    // Example assignment statements
    int extra, value; extra = 5; value = extra + 2;
    System.out.println( "value now holds: " + value );

15. Same Variable Twice in an Assignment Statement


Answer:

The program will print out:

    value now holds: 7

Adding a Number to a Variable

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:

  1. Gets the number on the RIGHT of the equal sign: 5
  2. Look on the LEFT of the equal sign to see where to put the result.
    • Put the 5 in the variable value.

First Statement Do First

First Statement Do Second


The second statement:

  1. 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
  2. Look on the LEFT of the equal sign to see where to put the result.
    • Put the 17 in the variable value.

Second Statement Do First

Second Statement Do Second


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:

What does the following program fragment write?

    value = 5; System.out.println("value is: " + value ); value = value + 10; System.out.println("value is: " + value );

16. A Sequence that Counts


Answer:

The program will print out:

    value is: 5
    value is: 15

A Sequence that Counts

Look at this program fragment. Click inside the program to see how it works.

int count = 0; // statement 1
System.out.println( count ) ; // statement 2 count = count + 1; // statement 3
System.out.println( count ) ; // statement 4




    

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.

17. Counting Higher


Answer:

Put a copy of statements 3 and 4 at the end.

Counting Higher

The following fragment:

int count = 0;                  // statement 1
System.out.println( count ) ;   // statement 2

count = count + 1;              // statement 3
System.out.println( count ) ;   // statement 4

count = count + 1;               
System.out.println( count ) ;



    

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.

What does the following assignment statement do:

sum = 2*sum ;

(What are the two steps, in order?)


Question 18:

What does the following assignment statement do:

    sum = 2*sum ;
(What are the two steps, in order?)

18. Expressions


Answer:

  1. Evaluate the expression: get the value in sum and multiply it by two.
  2. 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

This (slightly 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.)

Expression5312 - 3)x + 34*z   99sum + value
Correct or Not?

19. More Practice


Answer:

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.

Expression  sum + * 3      (12 - 3)        sum * 34 / 2       emf * ( e       3.14y  
Correct or Not?                               

Question 20:

Why is the last expression not correct?

20. Spaces Don't Much Matter


Answer:

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 improved 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

21. Arithmetic Operators


Answer:

12, since the expression means: 12 - 2 + 2

Arithmetic Operators

An arithmetic operator is a symbol that asks for two numbers to be combined by 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).

However,

5.0/2.0 is 2.5
5/10 is 0.5 .
More on this later.

    Operator                    Meaning                       precedence         
- unary minus highest
+ unary plus highest
* multiplication middle
/ division middle
% remainder middle
+ addition low
- subtraction low

Question 22:

What is the value of the following expressions? In each expression, do the
highest precedence operator first.

Expression 16 - 12 / 4 2 + 6 / 2 8 + 4*2 8+4 * 2 12/2 - 3 6/8 + 2
Value

22. Evaluation by Rewriting


Answer:

Expression
16 - 12 / 4
2 + 6 / 2
8 + 4*2
8+4 * 2
12/2 - 3
6/8 + 2
Value
13
5
16
16
3
2

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

23. Evaluate Equal Precedence from Left to Right


Answer:

    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 precedence, so calculate 2 * 7 first, then use that result with the second operator.

Here is a second example:

4 - 2 + 5
-----
2 + 5
-------
7

Now the operators are different, but they both have the same precedence, 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.)


Question 24:

What is the value of the following expression?

    2 + 4/2 + 1

24. Unary Minus


Answer:

    2 + 4/2 + 1 --- 2 + 2 + 1 ------ 4 + 1 --------- 5

Unary Minus

If you look in the operators, table of 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

25. Unary Minus


Answer:

    2 + 4/2 + 1 --- 2 + 2 + 1 ------ 4 + 1 --------- 5

Unary Minus

If you look in the operators, table of 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

26. Arrange what you want with Parentheses


Answer:

    +24 + 3 * -4 ------ +24 + -12 ----------- 12

The first + is a unary plus, so it has high precedence and applies only to the 24.

The - is a unary minus, so it applies only to the 4.

Next in order of precedence is the *, so three times negative four is calculated
yielding negative twelve.

Finally the low precedence + combines the positive twenty four with the negative twelve.

Arrange what you want with Parentheses

To show 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?

Expression
(8 - 2) / 2
(2 + 6) / 2 - 9
(8 + 4) * 2
8 + 4 * 2
8 + (4 * 2)
Value

27. Extra Parentheses


Answer:

Expression
(8 - 2) / 2
(2 + 6) / 2 - 9
(8 + 4) * 2
8 + 4 * 2
8 + (4 * 2)
Value
3
-5
24
16
16

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:

Equivalent Expressions
a + b + c * d
a + b + (c * d)
(a + b) + (c * d)
((a + b) + (c * d))


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?

Expression
8 + 2 / 2 + 3
(8 + 2) / (2 + 3)
(8 + 2) / 2 + 3
8 + 2 / (2 + 3)
Value

28. Nested Parentheses


Answer:

Expression
(8 + 2) / (2 + 3)
(8 + 2) / 2 + 3
8 + 2 / (2 + 3)
Value
12
2
8
8

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:

( ( ( 32 - 16 ) / ( 2 * 2 ) ) -  ( 4 - 8 ) ) + 7
    -----------

( (     16      / ( 2 * 2 ) ) -  ( 4 - 8 ) ) + 7
                  ---------

( (     16      /     4     ) -  ( 4 - 8 )  ) + 7
  ---------------------------

(               4             -  ( 4 - 8 )  ) + 7
                                  -------

(               4             -      -4     ) + 7
---------------------------------------------
                    
                     8                        + 7
                     ----------------------------

                                  15        


(Ordinarily you would not do this in such detail.)


Question 28:

What is the value of this expression:

    (12 / 4 ) + ( 12 / 3)

29. End of Chapter


Answer:

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.

The next chapter will continue with arithmetic expressions.