Arithmetic Operators

Understanding Arithmetic Operators

Arithmetic Operators

  • Arithmetic operators are symbols that tell the computer to perform specific mathematical computations.
  • Common arithmetic operators include: addition (+), subtraction (-), multiplication (*), division (/) and modulus (%).

Usage of Arithmetic Operators

  • These operators are used to perform basic calculations. For example, in most programming languages, 2+3 would yield a result of 5.
  • The subtraction operator - is used similarly, 4-2 would yield 2.
  • The multiplication operator * is used for multiplication operations, e.g., 5*4 would return 20.
  • The division operator / is used for division operations, e.g., 10/2 would give 5.
  • The modulus operator % returns the remainder of a division operation, e.g., 10%3 would give a result of 1 because when 10 is divided by 3, the remainder is 1.

Operator Precedence

  • Operator precedence refers to the rules that govern the order of operations in expressions containing more than one arithmetic operator.
  • Certain operators take precedence over others. For instance, multiplication and division are performed before addition and subtraction.
  • You can control operator precedence using parentheses. Operations inside parentheses are performed before those outside.

Integer Division

  • When both operands are integer types, some languages perform integer division, meaning the result is also an integer, with the decimal portion truncated.
  • For instance, in integer division, 9/2 would return 4, not 4.5.

Floating Point Arithmetic

  • To get accurate decimal results, one or more of the operands must be a float type.
  • If one operand is a float, the other is automatically converted into a float before the operation is carried out, and a float is returned. For example, 9.0/2 or 9/2.0 would return 4.5.

Key Takeaway

  • Understanding how to use arithmetic operators and their precedence is crucial to writing correct utilizable code. Further, awareness of integer division and floating point arithmetic can help handle numerical calculations without introducing errors.