In the world of programming, operators serve as the fundamental tools for manipulating data and directing the flow of operations within a program. They enable developers to perform a wide array of tasks, ranging from basic arithmetic operations to implementing complex logic for decision-making processes based on specific conditions.
🤡
What do cats and programmers have in common?
When either one is unusually happy and excited, it’s because they found a bug.
Different Operators
Arithmetic
Arithmetic operators are perhaps the most familiar, responsible for performing basic mathematical operations like addition, subtraction, multiplication, division, and modulus. These operators form the foundation for numerical computations in virtually every programming language.
a = 10
b = 5
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a % b) # Modulus
Assignment
Assignment operators are used to assign values to variables. While the basic assignment operator (=
) is the most common, programming languages offer compound assignment operators that combine arithmetic or bitwise operations with assignment.
// Example of compound assignment operators in Java
int x = 10;
x += 5; // Equivalent to x = x + 5
System.out.println(x); // Output: 15
Comparison
Comparison operators are employed to compare values and determine the relationship between them. These operators typically return a Boolean value (true
or false
) based on whether the comparison holds true or not.
// Example of comparison operators in JavaScript
let x = 5;
let y = 10;
console.log(x > y); // Output: false
console.log(x <= y); // Output: true
Logical
Logical operators are fundamental for making decisions and controlling the flow of execution within a program. These operators are used to combine multiple conditions and determine the overall truth value of a compound expression.
// Example of logical operators in C
int age = 25;
int income = 50000;
if (age > 18 && income > 30000) {
printf("Eligible for loan");
}
Bitwise
Bitwise operators manipulate individual bits within binary representations of data. These operators are particularly useful in low-level programming, such as device drivers and embedded systems, where direct manipulation of binary data is necessary.
# Example of bitwise operators in Python
a = 5 # Binary: 0101
b = 3 # Binary: 0011
print(a & b) # Bitwise AND: 0001 (Decimal: 1)
print(a | b) # Bitwise OR: 0111 (Decimal: 7)
print(a ^ b) # Bitwise XOR: 0110 (Decimal: 6)