Home » Blog » C# – Operators – Part 5

C# – Operators – Part 5

operators

We will learn about the various operators available in C#.

Arithmetic Operators

These help to carry out basic arithmetic operations on numbers.

Arithmetic OperatorsName
+Addition
Subtraction
*Multiplication
/Division
%Modulus
++Increment
– –Decrement


Let’s see these in action.

//Arithmetic operators
Console.WriteLine("Arithmetic Operators");
Console.WriteLine(10 + 10);
Console.WriteLine(100 - 10);
Console.WriteLine(10 * 10);
Console.WriteLine(20 / 10);
Console.WriteLine(12 % 10);

//Increment & Decrement operators only work with variables, properties, indexers
int myAge = 30;
myAge++;
Console.WriteLine(myAge);
int yourAge = 20;
yourAge--;
Console.WriteLine(yourAge);

Output:

Arithmetic Operators
20
90
100
2
2
31
19

Comparison Operators

As the name suggests, comparison operators are used to compare 2 values, returns a Boolean.

Comparison OperatorName
==Equal to
!=Not Equal to
>Greater than
<Lesser than
>=Greater than or equal to
<=Lesser than or equal to

Let’s see them in action.

//Comparison operators
Console.WriteLine("Comparison Operators");
Console.WriteLine(5 == 5);
Console.WriteLine(5 != 10);
Console.WriteLine(5 < 10);
Console.WriteLine(5 > 10);
Console.WriteLine(5 >= 10);
Console.WriteLine(5 <= 10);

Output:

Comparison Operators
True
True
True
False
False
True

Logical Operators

These operators are used with variables, expressions to determine the logic amongst them.

Let’s see them in action.

OperatorDescriptionExample
&&ANDnum1 < 10 && num1 > 5
||ORnum1 == 10 || num1 == 5
!NOT!(num1 > 10)
//Logical Operations
Console.WriteLine("Logical Operators");
int num1 = 100;
Console.WriteLine(num1 > 50 && num1 < 500);
Console.WriteLine(num1 == 100 || num1 == 50);
Console.WriteLine(!true);

Output:

Logical Operators
True
False
False

AND – Returns true only when both the expressions are true, returns false when any of the expressions are false

OR – Returns true when any one of the expressions are true

Logical operators when mixed with the assignment operator bring in more flavor in decision making, as demonstrated below.

num >=5 && num <=10;
num !=10 || num >=100; 

We will be dealing with operators more and more in the upcoming articles.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *