Operators are symbols in programming that perform operations on variables and values. They are the building blocks of any programming language, allowing you to perform various kinds of operations, such as arithmetic, comparison, logical, assignment, and more.
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and division.
+: Addition (e.g.,a + b)-: Subtraction (e.g.,a - b)*: Multiplication (e.g.,a * b)/: Division (e.g.,a / b)%: Modulus (e.g.,a % breturns the remainder of division)++: Increment (e.g.,a++increases the value ofaby 1)--: Decrement (e.g.,a--decreases the value ofaby 1)
Comparison operators compare two values and return a boolean value, either true or false.
==: Equal to (e.g.,a == b)!=: Not equal to (e.g.,a != b)>: Greater than (e.g.,a > b)<: Less than (e.g.,a < b)>=: Greater than or equal to (e.g.,a >= b)<=: Less than or equal to (e.g.,a <= b)
Logical operators are used to combine conditional statements.
&&: Logical AND (e.g.,a && bis true if bothaandbare true)||: Logical OR (e.g.,a || bis true if eitheraorbis true)!: Logical NOT (e.g.,!ais true ifais false)
Assignment operators are used to assign values to variables.
=: Assign (e.g.,a = bassigns the value ofbtoa)+=: Add and assign (e.g.,a += bis equivalent toa = a + b)-=: Subtract and assign (e.g.,a -= bis equivalent toa = a - b)*=: Multiply and assign (e.g.,a *= bis equivalent toa = a * b)/=: Divide and assign (e.g.,a /= bis equivalent toa = a / b)%=: Modulus and assign (e.g.,a %= bis equivalent toa = a % b)
Operators are used in programming to perform operations on variables and values. For example, in an if statement, comparison operators can be used to determine the flow of execution based on the comparison results.
int a = 10;
int b = 20;
// Using arithmetic operators
int sum = a + b; // sum is 30
// Using comparison operators
if (a > b) {
// This block will not execute since a is not greater than b
}
// Using logical operators
if (a < b && a > 0) {
// This block will execute since both conditions are true
}Operators allow you to write concise and efficient code, making them a fundamental aspect of programming.