Operators and Expressions
In C#, operators are used to perform various operations on variables and values. They allow you to perform arithmetic calculations, compare values, and perform logical operations.
Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations. C# provides the following arithmetic operators:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Modulus (%)
Here's an example of using arithmetic operators:
1int x = 10;
2int y = 5;
3
4int addition = x + y;
5int subtraction = x - y;
6int multiplication = x * y;
7int division = x / y;
8int modulus = x % y;
9
10Console.WriteLine("Addition: " + addition);
11Console.WriteLine("Subtraction: " + subtraction);
12Console.WriteLine("Multiplication: " + multiplication);
13Console.WriteLine("Division: " + division);
14Console.WriteLine("Modulus: " + modulus);
Comparison Operators
Comparison operators are used to compare two values and determine the relationship between them. C# provides the following comparison operators:
- Equal to (==)
- Not equal to (!=)
- Greater than (>)
- Less than (<)
- Greater than or equal to (>=)
- Less than or equal to (<=)
Here's an example of using comparison operators:
1int x = 10;
2int y = 5;
3
4bool isEqual = x == y;
5bool isNotEqual = x != y;
6bool isGreater = x > y;
7bool isLess = x < y;
8bool isGreaterOrEqual = x >= y;
9bool isLessOrEqual = x <= y;
10
11Console.WriteLine("Is Equal: " + isEqual);
12Console.WriteLine("Is Not Equal: " + isNotEqual);
13Console.WriteLine("Is Greater: " + isGreater);
14Console.WriteLine("Is Less: " + isLess);
15Console.WriteLine("Is Greater or Equal: " + isGreaterOrEqual);
16Console.WriteLine("Is Less or Equal: " + isLessOrEqual);
Logical Operators
Logical operators are used to perform logical operations on boolean values. C# provides the following logical operators:
- AND (&&)
- OR (||)
- NOT (!)
Here's an example of using logical operators:
1bool isTrue = true;
2bool isFalse = false;
3
4bool andResult = isTrue && isFalse;
5bool orResult = isTrue || isFalse;
6bool notResult = !isTrue;
7
8Console.WriteLine("AND Result: " + andResult);
9Console.WriteLine("OR Result: " + orResult);
10Console.WriteLine("NOT Result: " + notResult);
Understanding and using operators correctly is an essential part of writing efficient and logical code in C#.
xxxxxxxxxx
}
using System;
public class Program
{
public static void Main()
{
// Arithmetic operators
int x = 10;
int y = 5;
int addition = x + y;
int subtraction = x - y;
int multiplication = x * y;
int division = x / y;
int modulus = x % y;
Console.WriteLine("Addition: " + addition);
Console.WriteLine("Subtraction: " + subtraction);
Console.WriteLine("Multiplication: " + multiplication);
Console.WriteLine("Division: " + division);
Console.WriteLine("Modulus: " + modulus);
// Comparison operators
bool isEqual = x == y;
bool isNotEqual = x != y;
bool isGreater = x > y;
bool isLess = x < y;
bool isGreaterOrEqual = x >= y;
bool isLessOrEqual = x <= y;