Basic Arithmetic and Logical Operators Explained
Master the basic operators in programming, from simple math to complex logical conditions, essential for algorithmic problem-solving.
The Verbs of Programming
If variables are the nouns of programming, operators are the verbs. They are the symbols that tell the computer to perform specific mathematical, relational, or logical operations.
Arithmetic Operators
These handle standard math operations.
- Addition (
+), Subtraction (-), Multiplication (*), Division (/). - Modulo (
%): This is incredibly important in DSA. It returns the remainder of a division. For example,10 % 3is 1. It is frequently used to check if a number is even (num % 2 == 0) or for wrap-around array logic.
Relational Operators
These compare two values and return a boolean (True/False).
- Equal to (
==), Not equal to (!=). - Greater/Less than (
>,<), Greater/Less than or equal to (>=,<=).
Logical Operators
These combine multiple conditions together.
- AND (
&&): Returns True only if BOTH sides are true. - OR (
||): Returns True if AT LEAST ONE side is true. - NOT (
!): Reverses the boolean value.
Short-Circuit Evaluation
Most modern languages use short-circuiting. In an AND (&&) statement, if the first condition is False, the computer doesn't even check the second condition (because the whole statement must be False). This is a useful trick to prevent out-of-bounds errors: if (index < array.length && array[index] == target).
The Takeaway
Operators are the core of decision-making and data manipulation. Mastering them, especially modulo and short-circuit logic, is a prerequisite for writing functional algorithms.
The modulo operator divides one number by another and returns the remainder. It is widely used to check for even/odd numbers or to constrain array indices.
A single '=' is used to assign a value to a variable. A double '==' is used to compare two values to see if they are equal.
It is an optimization where the program stops evaluating a logical expression as soon as the final result is guaranteed (e.g., the first part of an AND is false).
The NOT operator simply reverses the boolean value. If a condition is True, applying '!' makes it False, and vice versa.
In many languages, you can use the '+' operator to concatenate (join) strings together, but operators like '-' or '*' usually result in errors when used on strings.
