Operators
Lesson 2.2: Operators
Operators are symbols that perform actions on values or variables. Think of them as the verbs of the C# language. This lesson covers three essential types of operators:
1. Arithmetic Operators
Arithmetic operators perform mathematical operations on numeric values (like int and double).
Operator Name Example Description
+ Addition 5 + 3 (result: 8) Adds two numbers together.
- Subtraction 10 - 4 (result: 6) Subtracts the second number from the first.
* Multiplication 6 * 2 (result: 12) Multiplies two numbers.
/ Division 20 / 5 (result: 4.0) Divides the first number by the second.
% Modulus 13 % 5 (result: 3) Returns the remainder after division.
Examples:
C#
int sum = 15 + 7; // sum will be 22
double product = 8.5 * 2; // product will be 17.0
int remainder = 23 % 6; // remainder will be 5
2. Comparison Operators
Comparison operators compare two values and return a Boolean result (true or false).
Operator Name Example Description
== Equal to 5 == 5 (result: true) Checks if two values are equal.
!= Not equal to 7 != 3 (result: true) Checks if two values are not equal.
< Less than 2 < 8 (result: true) Checks if the first value is less than the second.
> Greater than 10 > 6 (result: true) Checks if the first value is greater than the second.
<= Less than or equal to 4 <= 4 (result: true) Checks if the first value is less than or equal to the second.
>= Greater than or equal to 9 >= 5 (result: true) Checks if the first value is greater than or equal to the second.
Examples:
C#
bool isEqual = (10 == 10); // isEqual will be true
bool isNotEqual = (3 != 5); // isNotEqual will be true
bool isGreater = (8 > 2); // isGreater will be true
3. Logical Operators
Logical operators combine or modify Boolean expressions.
Operator Name Example Description
&& AND true && false (result: false) Returns true if both expressions are true, otherwise false.
|| OR true
! NOT !true (result: false) Reverses the logical value of an expression (true becomes false, and vice versa).
Examples:
C#
bool isSunny = true;
bool isWarm = false;
bool goodWeather = isSunny && isWarm; // goodWeather will be false
bool okayWeather = isSunny || isWarm; // okayWeather will be true
Let me know if you need more information