C#: Using Mathematical and Logical Operators
In a C# program, it's important to be able to perform calculations and make decisions based on conditions. This is where mathematical and logical operators come into play. In this article, we will cover how to use these operators in C#.
Mathematical Operators
Mathematical operators allow you to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. Here are some common mathematical operators in C#:
- (addition)
- (subtraction)
- (multiplication)
- / (division)
- % (modulo)
For example:
javaint x = 10;
int y = 5;
int sum = x + y; // 15
int difference = x - y; // 5
int product = x * y; // 50
int quotient = x / y; // 2
int remainder = x % y; // 0
In the code above, we declared two variables x
and y
, and used mathematical operators to perform addition, subtraction, multiplication, division, and modulo operations on them.
Logical Operators
Logical operators allow you to make decisions based on conditions. They return a bool
value of true
or false
. Here are some common logical operators in C#:
- && (and)
- || (or)
- ! (not)
For example:
javaint x = 10;
int y = 5;
bool result1 = x > y && x < 20; // true
bool result2 = x > y || x < 5; // true
bool result3 = !(x == y); // true
In the code above, we used logical operators to check conditions and assign the result to a bool
variable.
In conclusion, mathematical and logical operators are essential for performing calculations and making decisions in a C# program. By using these operators, you can write more dynamic and effective programs.