upgrade
upgrade

๐ŸงตProgramming Languages and Techniques I

Fundamental Arithmetic Operators

Study smarter with Fiveable

Get study guides, practice questions, and cheatsheets for all your subjects. Join 500,000+ students with a 96% pass rate.

Get Started

Why This Matters

Arithmetic operators are the foundation of every calculation your programs will ever perform. Whether you're building a game that tracks scores, a financial app that calculates interest, or an algorithm that processes data, you're relying on these operators to manipulate numbers. In Programming Languages I, you're being tested on more than just knowing that + adds thingsโ€”you need to understand operator behavior, type interactions, and evaluation rules that determine what your code actually produces.

The key concepts here include operator precedence, integer vs. floating-point division, commutativity, and side effects in expressions. When you encounter exam questions about unexpected output or debugging scenarios, the answer often traces back to how these operators behave with different data types. Don't just memorize symbolsโ€”know what each operator returns, when it might surprise you, and how to use it strategically.


Basic Binary Operators

These operators take two operands and return a result without modifying the original values. They form the core of mathematical computation in programming and follow predictable rules based on mathematical properties.

Addition (+)

  • Combines two values to produce a sumโ€”works with integers, floats, and in many languages, concatenates strings
  • Commutative property applies: a+b=b+aa + b = b + a, so operand order doesn't affect the result
  • Type promotion occurs when mixing types; adding an int to a float typically returns a float

Subtraction (-)

  • Calculates the difference between two operandsโ€”the left operand minus the right operand
  • Not commutative: aโˆ’bโ‰ bโˆ’aa - b \neq b - a, making operand order critical to your result
  • Unary form exists where -x negates a single value, serving a different purpose than binary subtraction

Multiplication (*)

  • Produces the product of two valuesโ€”supports integers, floats, and sometimes string repetition (e.g., "hi" * 3)
  • Commutative property applies: aร—b=bร—aa \times b = b \times a, giving flexibility in expression ordering
  • Higher precedence than addition/subtraction, meaning 2+3ร—4=142 + 3 \times 4 = 14, not 20

Compare: Addition vs. Multiplicationโ€”both are commutative and work across numeric types, but multiplication has higher precedence. If an exam question shows unexpected output from a mixed expression, check whether parentheses were needed to override default precedence.


Division Operators

Division in programming is trickier than in math class. Different division operators exist because programs need to handle both precise decimal results and whole-number-only scenarios. Understanding the distinction prevents countless bugs.

Division (/)

  • Returns the quotient of two numbersโ€”in most modern languages (Python 3, JavaScript), always returns a float
  • Division by zero throws an error or returns infinity/NaN depending on the language; never assume it's handled gracefully
  • Type behavior varies by language: Python 2 performed integer division with / on integers, while Python 3 always returns float

Integer Division (//)

  • Returns the floor of the quotientโ€”the largest integer less than or equal to the true result
  • Discards the fractional part: 7//2=37 // 2 = 3, not 3.5; useful when you need whole units only
  • Negative number behavior matters: โˆ’7//2=โˆ’4-7 // 2 = -4 (floors toward negative infinity), which surprises many students

Modulus (%)

  • Returns the remainder after divisionโ€”the "leftover" when dividing doesn't come out even
  • Classic use case: x % 2 == 0 tests if a number is even; x % n cycles values through range 0 to n-1
  • Sign of result varies by languageโ€”Python's modulus always matches the divisor's sign, while C matches the dividend's

Compare: Division (/) vs. Integer Division (//) vs. Modulus (%)โ€”these three operators answer different questions about the same division: what's the decimal result?, how many whole times does it fit?, and what's left over? FRQs often test whether you can pick the right one for a given scenario.


Exponentiation

Raising numbers to powers appears constantly in algorithms, from calculating compound interest to implementing search algorithms. Not all languages use the same syntax, so know your language's approach.

Exponentiation (**)

  • Raises the base to the given power: 210=10242^{10} = 1024 is written as 2 ** 10 in Python and JavaScript
  • Right-associative evaluation: 2322^{3^2} evaluates as 2(32)=29=5122^{(3^2)} = 2^9 = 512, not (23)2=64(2^3)^2 = 64
  • Alternative syntax exists: some languages use pow(base, exp) function or ^ operator (though ^ often means XOR)

Compare: Exponentiation (**) vs. Multiplication (*)โ€”both involve repeated operations conceptually, but exponentiation has higher precedence and is right-associative while multiplication is left-associative. Watch for expressions like 2 ** 3 ** 2 on exams.


Unary and Compound Operators

These operators modify variables directly, either incrementing/decrementing by one or combining an operation with assignment. They're shortcuts that make code more concise but introduce evaluation subtleties.

Increment (++)

  • Increases a variable's value by 1โ€”equivalent to x = x + 1 but more concise
  • Prefix vs. postfix matters: ++x increments then returns the value; x++ returns then increments
  • Not available in all languages: Python doesn't support ++; you must write x += 1 instead

Decrement (--)

  • Decreases a variable's value by 1โ€”the subtraction counterpart to increment
  • Same prefix/postfix behavior: --x decrements first; x-- returns original value then decrements
  • Common in loop control: while (count-- > 0) is a classic pattern, but the timing can cause off-by-one errors

Compare: Prefix (++x) vs. Postfix (x++)โ€”both add 1 to x, but they return different values in expressions. If x = 5, then y = ++x sets both to 6, while y = x++ sets y to 5 and x to 6. This distinction appears frequently in tracing exercises.

Compound Assignment Operators (+=, -=, *=, /=)

  • Combine operation and assignment: x += 5 is shorthand for x = x + 5, reducing repetition
  • Available for all basic operators: +=, -=, *=, /=, %=, **=, //= in most languages
  • Improves readability and reduces errors from typing variable names multiple times in complex expressions

Quick Reference Table

ConceptBest Examples
Commutative operatorsAddition (+), Multiplication (*)
Non-commutative operatorsSubtraction (-), Division (/), Modulus (%)
Returns float by defaultDivision (/)
Returns integerInteger division (//), Modulus (%)
Modifies variable in placeIncrement (++), Decrement (--), Compound assignment (+=)
Right-associativeExponentiation (**)
Causes runtime error if misusedDivision by zero (/), Modulus by zero (%)
Prefix/postfix behaviorIncrement (++), Decrement (--)

Self-Check Questions

  1. Which two operators share the commutative property, and which division-related operator does not?

  2. If x = 10, what is the difference in output between print(x++) and print(++x) in a language that supports both forms?

  3. Compare and contrast / and // when applied to the expression โˆ’7-7 divided by 22. What does each return, and why?

  4. A student writes total = total + bonus * 2 but expected addition to happen first. What concept explains the actual behavior, and how would you fix the code?

  5. You need to determine if a year is a leap year, which requires checking divisibility by 4, 100, and 400. Which operator would you use, and why is it better suited than division for this task?