Skip to main content

Section 1.13 Compound Operators

Subgoals for evaluating an assignment statement.

  1. Decide order of operations
    1. Decompose as necessary
  2. Determine operator behavior based on operands
    1. Operator and operands must be compatible
  3. Solve arithmetic, expression, or operation
    1. Decompose as necessary

Subsection 1.13.1

Given the following code snippet, evaluate the final statement (the last line). If invalid, give the reason. If valid, what value is assigned to the variable?
alpha = 2
beta = 5
delta = 7
gamma = 5
omega = 2.5
theta = -1.3
kappa = 3.0

gamma += delta / alpha + beta % alpha

Subsection 1.13.2 SG1: Decide order of operations

The expression is usually the right-hand-side (RHS) of the statement, but compound assignment operators are a special shorthand than includes the compounded operation with the left-hand-side (LHS). A much simpler example could be gamma += 1, which would be a shorthand for gamma = gamma +1
Thus, the entire expression for this example is gamma + (delta / alpha + beta % alpha), which will be assigned back into gamma.
For that expression, the highest priority operator is the division, followed by the modulo. Then, the remaining additions will occur, starting with the one on the right and ending with the one on the left.

Subsection 1.13.3 SG2: Determine operator behavior based on operands

The expression delta / alpha is a division between two integers, so will result in a float. The expression beta % alpha is a modulo between two integers, and so will result in an integer. The result of those two expressions will be added together, producing a float, which when added to the current value of gamma will also produce a float.

Subsection 1.13.4 SG3: Solve arithmetic, expression, or operation

The variable delta is substituted for the value 7 and the variable alpha is substituted for the value 2. Dividing them produces the float 3.5
The variable beta is substituted for the value 5 and the variable alpha is substituted for the value 2. Their modulo is 1.
Adding those two numbers together produces 4.5.
The existing value stored in gamma is 5, so adding 4.5 produces 9.5, which is stored back into gamma.

Subsection 1.13.5 Questions to check understanding

  1. Is the left-hand-side (LHS) of the statement a variable? What type?
    Answer.
    Yes, the variable gamma will be a float.
  2. What is the resulting type after evaluating the right-hand-side (RHS)?
    Answer.
    A float.
  3. Would dividing using the // operator instead of the / operator change the type of the result?
    Answer.
    Yes, since the result of that division would be an integer (3), and all the other operations involved integers.
You have attempted of activities on this page.