🧮

Programming Arithmetic and Operators

Sep 6, 2025

Overview

This lecture covers integer and floating-point division, the modulus operation, operator precedence, and usage of arithmetic, concatenation, and relational operators in programming.

Integer and Floating-Point Division

  • Dividing two integers (e.g., 3 / 2) returns an integer result, discarding any decimal part (result: 1).
  • Dividing an integer by a floating-point number (e.g., 3 / 2.0) returns a floating-point result (result: 1.667).
  • If either the numerator or denominator is a float, the division result will be a float.
  • Example: 2 / 3 returns 0 (integer division); 2 / 3.0 returns approximately 0.667 (float).

Modulus (Remainder) Operation

  • The modulus operator (%) returns the remainder of integer division (e.g., 3 % 2 = 1).
  • Both operands must be integers; modulus with a float (e.g., 3 % 2.0) is invalid.
  • If the numerator is less than the denominator (e.g., 2 % 3), the result is the numerator (2).
  • Example: 20 % 114 returns 20.

Operator Precedence and Associativity

  • Parentheses have the highest precedence; evaluate expressions inside them first.
  • Multiplication, division, and modulus have equal precedence, followed by addition and subtraction.
  • When operators have the same precedence, evaluate them left to right (left associativity).
  • Example: 10 + 4 * 8 evaluates as 10 + (4 * 8) = 42.
  • Example: 20 / 4 * 9 evaluates as (20 / 4) * 9 = 45.

Expression Evaluation Examples

  • For complex expressions, always solve parentheses first, then multiplication/division/modulus, then addition/subtraction.
  • Example: 2 * 3 + 4 / 2 - (7 + 8) % 5 simplifies to 8.

String Concatenation

  • The plus (+) operator combines (concatenates) strings (e.g., "3" + "4" = "34").
  • Only strings can be concatenated; combining a string with a numeric value is incorrect.

Relational Operators

  • Common relational operators include: > (greater than), < (less than), >=, <=, != (not equal), == (equal).
  • Use programming-specific symbols for these operators, not math notation.

Key Terms & Definitions

  • Integer Division — Division between whole numbers; discards any fractional part.
  • Floating-point Division — Division where at least one operand is a decimal; result is a decimal.
  • Modulus Operator (%) — Returns the remainder after integer division.
  • Operator Precedence — The order in which operations are performed in an expression.
  • Associativity — The rule that determines the order for operators of the same precedence.
  • Concatenation — Combining two strings into one.

Action Items / Next Steps

  • Review operator precedence and associativity.
  • Practice evaluating complex arithmetic and string expressions.
  • Ensure proper use of integers with the modulus operator in code.