🔢

Understanding Operator Precedence and Arithmetic

Oct 24, 2024

Lecture Notes on Operator Precedence and Arithmetic Expressions

Operator Precedence Overview

  • Parentheses have the highest precedence.
  • Unary minus follows.
  • Operators with the same priority:
    • Multiplication, Division, Modulus
    • Addition, Subtraction
  • Evaluation of same priority operators is from left to right.
  • Parentheses can change the precedence of evaluation.

Examples of Operator Precedence

Example Expression: A + B * C - D / E*

  • To avoid confusion, parentheses can be used:
    • Equivalent to A + (B * C) - (D / E).
  • Steps of evaluation:
    1. Calculate B * C (multiplication)
    2. Calculate D / E (division)
    3. Evaluate A + (result of B*C)
    4. Evaluate the final result*

Unary Operators

  • Unary operators will automatically imply parentheses during computation.
  • Example: If using -B, it means (-B).

Further Example: A - B + C + D

  • Same priority operators evaluated left to right.
  • Parentheses can determine specific order of operations:
    • E.g., ((A - B) + C) + D

Types of Arithmetic Expressions

Integer Arithmetic

  • Operands are integers.
  • Always yields integer values.

Real Arithmetic

  • Involves floating point values.
  • Example: 1.0 / 3.0 * 3.0 yields a real number.
  • Rounding may occur due to significant digits.
  • Modulus is not defined for real operands.*

Mixed Mode Arithmetic

  • Combines integers and real numbers.
  • Result is a real number if any operand is real.
  • Example: 25 / 10 results in 2 (integer), while 25.0 / 10 results in 2.5 (real).

Assignment Operations

  • Assign value from an expression or variable to another variable:
    • Example: V = U + F * T
  • Ensure compatibility of data types (int vs float).
  • Type casting may be necessary.*

Example of Type Casting

  • Casting integer to fit into a floating point representation.
  • Example: X = (int)(2 * R) where R is a float.*

Relational Operators

  • Used for comparison between two quantities:
    • Less than (<)
    • Greater than (>)
    • Less than or equal to (<=)
    • Greater than or equal to (>=)
    • Equality (==) - checks value equality
    • Not equal to (!=)

Important Notes on Relational Operators

  • They return only boolean values (0 or 1 for false or true).
  • Example comparisons:
    • X < Y returns true if X is less than Y.

Use in Conditional Statements

  • Example: Implementing logic:
    • If X > Y: Print "X is larger"
    • Else: Print "Y is larger"

Summary

  • Covered operator precedence and its significance in expressions.
  • Discussed integer arithmetic, real arithmetic, and mixed mode arithmetic.
  • Introduced relational operators and their use in comparisons and decision-making.
  • Next topic: Logical operators.