Resources | Subject Notes | Computer Science
In programming, operators are symbols that perform operations on variables and values. This section focuses on arithmetic, logical, and Boolean operators, which are fundamental for decision-making and calculations within programs. Understanding how to use these operators effectively is crucial for writing efficient and correct code.
Arithmetic operators are used to perform mathematical calculations. The most common arithmetic operators are:
Here are some examples of how arithmetic operators are used:
Operator | Description | Example | Result |
---|---|---|---|
+ | Addition | $5 + 3$ | $8$ |
- | Subtraction | $10 - 4$ | $6$ |
$\times$ | Multiplication | $6 \times 7$ | $42$ |
$/$ | Division | $15 / 3$ | $5$ |
$\%$ | Modulus (remainder) | $17 \% 5$ | $2$ |
Logical operators are used to combine or modify boolean expressions (which evaluate to either true or false). The main logical operators are:
Here are the truth tables for the logical operators:
Operand 1 | Operand 2 | Result |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Operand 1 | Operand 2 | Result |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
Operand | Result |
---|---|
True | False |
False | True |
Boolean operators are used to evaluate boolean expressions. They are essentially the logical operators discussed above. They are used to create complex conditions that can be evaluated as either true or false.
Here are some examples of how logical operators are used in programming:
Operator precedence determines the order in which operations are performed in an expression. Generally, the order is as follows (from highest to lowest precedence):
Using parentheses can be used to override the default precedence and ensure that expressions are evaluated as intended.